package com.bjtdba.order.controller;


import com.bjtdba.entity.order.Recommend;
import com.bjtdba.entity.order.StoreProduct;
import com.bjtdba.order.service.RecommendService;
import com.bjtdba.order.service.StoreProductService;
import com.bjtdba.order.util.gong.Sha1;
import com.bjtdba.order.util.gong.WeixinUtil;
import com.bjtdba.order.util.redis.RedisUtil;
import com.bjtdba.order.vo.CategoryVo;
import com.bjtdba.order.vo.ProductXihuan;
import com.bjtdba.order.vo.RecommendDetailVo;
import com.bjtdba.order.vo.RecommendVo;
import com.bjtdba.utils.DateUtils;
import com.bjtdba.utils.ResponseUtil;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * (Recommend)大仓的接口
 *
 * @author makejava
 * @since 2022-10-19 13:24:00
 */
@RestController
@RequestMapping("order_service/recommend")
public class RecommendController {
    /**
     * 服务对象
     */
    @Resource
    private RecommendService recommendService;
    @Autowired
    private StoreProductService storeProductService;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 大仓推荐列表
     * @return
     */
    @PostMapping("/lists")
    public Object lsts(){

        List<Date> shoutime=recommendService.queryShowTime();
         List res=new ArrayList();
         Recommend queryRem=new Recommend();
         queryRem.setStatus(1);
         queryRem.setDates(shoutime);
        List<Recommend> mmList=recommendService.querList(queryRem);// 查询推荐的集合

        // 通过日期进行数据装载
        for (Date d:shoutime ) {
            Map<String, Object> obj = new HashMap<String, Object>();
            obj.put("date", DateUtils.getMonthDay(d)+"月"+DateUtils.getDay(d)+"日");
            List<RecommendVo> list=new ArrayList<RecommendVo>();
            for (Recommend recommend:mmList) {
                // 查询两个时间间隔的天数
                long num=DateUtils.getDistinceDay(d,recommend.getShowTime());
                if(num==0){
                    RecommendVo recommendVo=new RecommendVo();
                    recommendVo.setRecommend_image(recommend.getRecommendImage());
                    recommendVo.setId(recommend.getId());
                    recommendVo.setShow_time(DateUtils.dateToStr(recommend.getShowTime()));
                    list.add(recommendVo);
                }
            }
            obj.put("list",list);

            res.add(obj);
        }


        return ResponseUtil.ok(res);
    }

    /**
     * 大仓推荐详情
     * @param map
     * @return
     */
    @PostMapping("/detail")
    public Object Detail(@RequestBody Map<String,String> map){
        if(!map.containsKey("id")){
            return ResponseUtil.fail("参数错误");
        }
        Integer id=Integer.parseInt(map.get("id"));
        RecommendDetailVo recommendDetailVo= recommendService.queryDetail(id);
        if(recommendDetailVo==null){
            return ResponseUtil.fail("查询的商品不存在");
        }

        StoreProduct storeProduct=storeProductService.queryById(Long.parseLong(recommendDetailVo.getProduct_id()+""));
           BigDecimal yanglao=new BigDecimal(0);
           yanglao=storeProductService.yanglaojin(storeProduct,new BigDecimal(0),new BigDecimal(1));
           recommendDetailVo.setYanglaojin(yanglao);

       return ResponseUtil.ok(recommendDetailVo);
    }

    /**
     * 查询大仓分类
     * @return
     */
    @GetMapping("/nologin/classify")
    public Object classify(){
        List<CategoryVo> categoryVo=recommendService.queryCategorylist();
        return ResponseUtil.ok(categoryVo);
    }



    /**
     * 大仓商品列表
     */

    @GetMapping("nologin/da_cang_product_lst")
    public Object seckill(@RequestParam Map<String,String> pmap){
        if(!pmap.containsKey("page")||!pmap.containsKey("limit")){
            return  ResponseUtil.fail("参数错误");
        }
        int page=Integer.parseInt(pmap.get("page")+"");
        int limit=Integer.parseInt(pmap.get("limit"));



//        'is_used'=>1,
//                'mer_status'=>1,
//                'type'=>5,
//                'is_show'=>1,
//                'is_hide'=>0
         //转载查询条件
        StoreProduct querSP=new StoreProduct();
            querSP.setIsUsed(1);
            querSP.setMerStatus(1);
            querSP.setType(5);
            querSP.setIsShow(1);
            querSP.setIsHide(0);

//查询分类子集
        if(pmap.containsKey("cateid")&&!pmap.get("cateid").equals("")) {
            Integer cateId = Integer.parseInt(pmap.get("cateid"));
            String cateIds = storeProductService.getCateIds(cateId);
            cateIds = cateIds.replace("$,", "");
            String[] cateIdsList = cateIds.split(",");
            System.out.println("cateIds=====" + cateIds);
            querSP.setCateIds(cateIdsList);
        }
        //判断排序参数
        if(pmap.containsKey("is_newDES")&&!pmap.get("is_newDES").equals("")){
            querSP.setIsNewDES("is_newDES");
        }
        if(pmap.containsKey("salesDES")&&!pmap.get("salesDES").equals("")){
            querSP.setSalesDES("salesDES");
        }
        if(pmap.containsKey("rankDES")&&!pmap.get("rankDES").equals("")){
            querSP.setRankDES("rankDES");
        }
        if (pmap.containsKey("priceType")&&!pmap.get("priceType").equals("")){
            querSP.setPriceType(pmap.get("priceType"));
        }

        PageHelper.startPage(page,limit);
        List<StoreProduct> storeProductList=storeProductService.queryList(querSP);
//        List<StoreProduct> resList=storeProductService.queryList(querSP);
        if(storeProductList!=null&&storeProductList.size()!=0){
             int  num=0;
            for (StoreProduct sp:storeProductList) {
                storeProductList.get(num).setFlag(1);
                sp.setFlag(1);
                BigDecimal yanglaojin=storeProductService.yanglaojin(sp,new BigDecimal(0),new BigDecimal(1));
                storeProductList.get(num).setYanglao(yanglaojin);
//                sp.setYanglao(yanglaojin);
//                resList.add(sp);
                num++;
            }
        }

        return  ResponseUtil.ok(storeProductList);

    }

    /**
     * 大仓推荐分享
     * @param map
     * @return
     */
    @PostMapping("/share")
    public Object Share(@RequestBody Map<String,String> map){

        if(!map.containsKey("id")){
            return ResponseUtil.fail("参数错误");
        }
        Integer id= Integer.parseInt(map.get("id")+"");
        Map<String,String> resObj=recommendService.queryByIdShare(id);

        return ResponseUtil.ok(resObj);
    }


    @PostMapping("/wx_config")
    public Object wx_config(@RequestBody Map<String,String> map) throws NoSuchAlgorithmException {
            if(!map.containsKey("url")){
                return ResponseUtil.fail("参数错误");
            }
            String url=map.get("url").toString(); //url地址
            String noncestr=getRandStr(16);//随机16个字符串
            String jsapi_ticket=WeixinUtil.get_ticket();//
            Long timestamp=new Date().getTime();
            String sign= Sha1.sha1("jsapi_ticket="+jsapi_ticket+"&noncestr="+noncestr+"&timestamp="+timestamp+"&url="+url);
            Map<String,Object> data=new HashMap<String,Object>();
            data.put("signature",sign);
            data.put("timestamp",timestamp);
            data.put("noncestr",noncestr);

        return ResponseUtil.ok(data);
    }



    //获取指定位数的随机字符串(包含小写字母、大写字母、数字,0<length)
    public static String getRandStr(int length) {
        //随机字符串的随机字符库
        String KeyString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuffer sb = new StringBuffer();
        int len = KeyString.length();
        for (int i = 0; i < length; i++) {
            sb.append(KeyString.charAt((int) Math.round(Math.random() * (len - 1))));
        }
        return sb.toString();
    }



    /**
     * 猜你喜欢查询list
     * @param pmap
     * @return
     */
    @GetMapping("/lst")
    public Object lst(@RequestParam Map<String,String> pmap){

        if(!pmap.containsKey("page")||!pmap.containsKey("limit")){
            return  ResponseUtil.fail("参数错误");
        }
        int page=Integer.parseInt(pmap.get("page")+"");
        int limit=Integer.parseInt(pmap.get("limit"));
        //分页
        PageHelper.startPage(page,limit);
        List<ProductXihuan> list=storeProductService.Productxihuan();
        if(list!=null&&list.size()!=0){
            int num=0;
            for (ProductXihuan xihuan:list){
                StoreProduct sp=new StoreProduct();
                sp.setProductId(Long.parseLong(xihuan.getProduct_id()));
                sp.setMerId(Long.parseLong(xihuan.getMer_id()));
                sp.setExtensionType(xihuan.getExtension_type());
                sp.setType(xihuan.getType());
                sp.setPrice(new BigDecimal(xihuan.getPrice()));
                BigDecimal yanglaojin=storeProductService.yanglaojin(sp,new BigDecimal(0),new BigDecimal(0));//1为大仓商品
                list.get(num).setYanglaojin(yanglaojin+"");
                num++;
            }

        }
        Map<String,Object> data=new HashMap<String,Object>();
        data.put("list",list);
        return ResponseUtil.ok(data);
    }

    /**
     * 店铺分类
     */
    @GetMapping("/merchant/category/lst/{id}")
    public Object queryCategorylistMerid(@PathVariable Integer id){

        List<CategoryVo>  categoryVoList=recommendService.queryCategorylistMerid(id);
        return ResponseUtil.ok(categoryVoList);

    }

}

