package com.platform.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.platform.annotation.CanUserUpdateRecord;
import com.platform.entity.*;
import com.platform.service.BrandService;
import com.platform.service.GoodsGalleryService;
import com.platform.service.GoodsService;
import com.platform.service.custom.MySysUserBrandService;
import com.platform.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import sun.rmi.runtime.Log;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Controller
 *
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2017-08-21 21:19:49
 */
@RestController
@RequestMapping("goods")
@Slf4j
public class GoodsController extends AbstractController{
    @Autowired
    private GoodsService goodsService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private GoodsGalleryService goodsGalleryService;


    @Autowired
    private MySysUserBrandService mySysUserBrandService;


    @Value("${api.host.query.url}")
    private String apiHostQueryUrl;
    @Value("${api.id}")
    private String appId;

    @Value("${api.secret}")
    private String appSecret;

    /**
     * 查看列表
     */
    @RequestMapping("/list")
    public Result list(@RequestBody Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        PageUtils pageUtil = new PageUtils(new ArrayList<>(), 0, query.getLimit(), query.getPage());
        List<Long> roleIdList = getUser().getRoleIdList();
        if (!roleIdList.contains(1L) && !roleIdList.contains(5L)) {
            // 获取用户角色
            HashMap<String, Object> brandQuery = new HashMap<>();
            // 公司管理员能获取改公司下面所有的直播间的数据
            if (roleIdList.contains(6L)) {
                if (null == getDeptId()) {
                    return Result.success(pageUtil);
                }
                brandQuery.put("deptIdList", getDeptId());
            } else if (roleIdList.contains(8L) || roleIdList.contains(2L)) {
                // 公司员工只能获取当前绑定当前用户直播间的商品数据
                List<Long> brandIds = mySysUserBrandService.queryBrandIdList(getUserId());
                if(ObjectUtils.isEmpty(brandIds)){
                    return Result.success(pageUtil);
                }
                brandQuery.put("idList", brandIds);
            }
            List<BrandEntity> brandList = brandService.queryList(brandQuery);
            if (CollectionUtils.isEmpty(brandList)) {
                return Result.success( pageUtil);
            } else {
                query.put("brandIdList", brandList.stream().map(BrandEntity::getId).collect(Collectors.toList()));
            }
        }
        query.put("isDelete", 0);
        List<GoodsEntity> goodsList = goodsService.queryList(query);
        int total = goodsService.queryTotal(query);

        pageUtil = new PageUtils(goodsList, total, query.getLimit(), query.getPage());

        return Result.success(pageUtil);
    }

    /**
     * 查看信息
     */
    @RequestMapping("/info/{id}")
    public Result info(@PathVariable("id") Integer id) {
        GoodsEntity goods = goodsService.queryObject(id);
        return Result.success(goods);
    }

    /**
     * 保存
     */
    @CanUserUpdateRecord
    @RequestMapping("/save")
    @Transactional(rollbackFor = Exception.class)
    public Result save(@RequestBody GoodsEntity goods) {
        if(goods.getName().length() > 15){
            return Result.failure("商品名称名称不能超过15个字符");
        }
        if(StringUtils.isEmpty(goods.getBrandId())){
            throw new RRException("直播间名称为空");
        }
        BrandEntity brand = brandService.queryObject(goods.getBrandId());
        if(brand == null){
            throw new RRException("直播间为空");
        }
        goodsService.save(goods);
        //发送数据给api平台
        sendDataToApi(goods);

        return Result.success();
    }

    private Result sendDeleteDataToApi(GoodsEntity goods){
        if(null == goods){
            return Result.failure("商品信息为空，无法请求api平台");
        }
        Map<String, Object> reqData = new HashMap<>();
        reqData.put("goodsId" , goods.getId());
        reqData.put("goodsName" , goods.getName());
        reqData.put("goodsIsOnSale" , goods.getIsOnSale());
        reqData.put("goodsImageList" , getGoodsImageList(goods));
        reqData.put("retailPriceLow" , goods.getRetailPrice());
        reqData.put("retailPriceHigh" , goods.getRetailPrice());
        reqData.put("retailPriceStr" , getGoodsRetailPrice(goods));
        reqData.put("goodsDesc" , goods.getGoodsSimpleDesc());
        reqData.put("goodsCategoryId" , goods.getCategoryId());
        reqData.put("goodsCategoryName" , goods.getCategoryName());
        reqData.put("goodsNumber" , goods.getGoodsNumber());
        reqData.put("goodsAddTime" , goods.getAddTime());
        reqData.put("goodsUpdateTime" , goods.getUpdateTime());
        reqData.put("goodsPrimaryPicUrl" , goods.getPrimaryPicUrl());
        reqData.put("goodsListPicUrl" , goods.getListPicUrl());
        reqData.put("goodsIsHot" , goods.getIsHot());
        reqData.put("goodsMarketPrice" , goods.getMarketPrice());
        reqData.put("attributeCategoryName" , goods.getAttributeCategoryName());
        reqData.put("brandId" , goods.getBrandId());
        reqData.put("realShopUrl" , goods.getRealShopUrl());
        reqData.put("origin" , ResourceUtil.getConfigByName("origin"));
        reqData.put("enable" , 0);
        BrandEntity brandEntity = brandService.queryObject(goods.getBrandId());
        if(StringUtils.isEmpty(goods.getBrandName())){
            if(null != brandEntity){
                reqData.put("brandName" , brandEntity.getName());
            }
        }else{
            reqData.put("brandName" , goods.getBrandName());
        }

        if(null != brandEntity && !StringUtils.isEmpty(brandEntity.getSceneNum())){
            reqData.put("sceneNum" , brandEntity.getSceneNum());
            reqData.put("appId" , appId);
            log.info("获取到的api平台的app_id={}, app_secret={}" , appId , appSecret);
            Long timeStamp = System.currentTimeMillis();
            //token=app_id+app_secret+timestamp
            String token = SHAUtils.getSHA256(appId + appSecret + timeStamp.toString());
            Map<String , Object> sortMap = sortMapByKey(reqData);
            String sortMapStr = JSONObject.toJSONString(sortMap);
            log.info("待加密的数据={}" ,sortMapStr + appSecret + timeStamp);
            String sign  = SHAUtils.getSHA256(sortMapStr + appSecret + timeStamp);
            String openApiurl = apiHostQueryUrl.concat("?appId=").concat(appId).concat("&sign=")
                    .concat(sign).concat("&token=").concat(token).concat("&timeStamp=").concat(""+timeStamp);
            log.info("请求链接：{}" ,openApiurl);
            String apiResultStr = HttpClientUtil.doPostJson(openApiurl , sortMapStr);
            log.info("api平台返回结果:{}" , apiResultStr);
            return Result.success(apiResultStr);
        }else{
            log.info("当前商品[{}]的品牌没有vr场景或者场景码为空，不需要上送api平台" , goods.getId());
            return Result.success();
        }

    }

    private Result sendDataToApi(GoodsEntity goods){
        if(null == goods){
            return Result.failure("商品信息为空，无法请求api平台");
        }
        Map<String, Object> reqData = new HashMap<>();
        reqData.put("goodsId" , goods.getId());
        reqData.put("goodsName" , goods.getName());
        reqData.put("goodsIsOnSale" , goods.getIsOnSale());
        reqData.put("goodsImageList" , getGoodsImageList(goods));
        reqData.put("retailPriceLow" , goods.getRetailPrice());
        reqData.put("retailPriceHigh" , goods.getRetailPrice());
        reqData.put("retailPriceStr" , getGoodsRetailPrice(goods));
        reqData.put("goodsDesc" , goods.getGoodsSimpleDesc());
        reqData.put("goodsCategoryId" , goods.getCategoryId());
        reqData.put("goodsCategoryName" , goods.getCategoryName());
        reqData.put("goodsNumber" , goods.getGoodsNumber());
        reqData.put("goodsAddTime" , goods.getAddTime());
        reqData.put("goodsUpdateTime" , goods.getUpdateTime());
        reqData.put("goodsPrimaryPicUrl" , goods.getPrimaryPicUrl());
        reqData.put("goodsListPicUrl" , goods.getListPicUrl());
        reqData.put("goodsIsHot" , goods.getIsHot());
        reqData.put("goodsMarketPrice" , goods.getMarketPrice());
        reqData.put("attributeCategoryName" , goods.getAttributeCategoryName());
        reqData.put("brandId" , goods.getBrandId());
        reqData.put("realShopUrl" , goods.getRealShopUrl());
        reqData.put("origin" , ResourceUtil.getConfigByName("origin"));
        BrandEntity brandEntity = brandService.queryObject(goods.getBrandId());
        if(StringUtils.isEmpty(goods.getBrandName())){
           if(null != brandEntity){
               reqData.put("brandName" , brandEntity.getName());
           }
        }else{
            reqData.put("brandName" , goods.getBrandName());
        }

        if(null != brandEntity && !StringUtils.isEmpty(brandEntity.getSceneNum())){
            reqData.put("sceneNum" , brandEntity.getSceneNum());
            reqData.put("appId" , appId);

            log.info("获取到的api平台的app_id={}, app_secret={}" , appId , appSecret);

            Long timeStamp = System.currentTimeMillis();

            //token=app_id+app_secret+timestamp
            String token = SHAUtils.getSHA256(appId + appSecret + timeStamp.toString());

            Map<String , Object> sortMap = sortMapByKey(reqData);
            String sortMapStr = JSONObject.toJSONString(sortMap);
            log.info("待加密的数据={}" ,sortMapStr + appSecret + timeStamp);
            String sign  = SHAUtils.getSHA256(sortMapStr + appSecret + timeStamp);
            String openApiurl = apiHostQueryUrl .concat("?appId=").concat(appId).concat("&sign=")
                    .concat(sign).concat("&token=").concat(token).concat("&timeStamp=").concat(""+timeStamp);
            log.info("请求链接：{}" ,openApiurl);
            String apiResultStr = HttpClientUtil.doPostJson(openApiurl , sortMapStr);
            log.info("api平台返回结果:{}" , apiResultStr);
            return Result.success(apiResultStr);
        }else{
            log.info("当前商品[{}]的品牌没有vr场景或者场景码为空，不需要上送api平台" , goods.getId());
            return Result.success();
        }

    }


    /**
     *  根据map的key进行字典升序排序
     * @param map
     * @return map
     */
    private   Map<String, Object> sortMapByKey(Map<String, Object>map) {
        Map<String, Object> treemap = new TreeMap<String, Object>(map);
        List<Map.Entry<String, Object>> list = new ArrayList<Map.Entry<String, Object>>(treemap.entrySet());
        Collections.sort(list, (o1, o2) -> org.apache.commons.lang3.StringUtils.compare(o1.getKey() , o2.getKey()));
        return treemap;
    }

    private List<String> getGoodsImageList(GoodsEntity goodsEntity){
        List<String> imageList = new ArrayList<>();
        if(null == goodsEntity){
            return imageList;
        }
        Map<String, Object> params = new HashMap<>();
        params.put("goodsId", Integer.valueOf(goodsEntity.getId()));
        List<GoodsGalleryEntity> list = goodsGalleryService.queryList(params);
        //获取图片列表
        imageList.add(goodsEntity.getPrimaryPicUrl());

        if(!CollectionUtils.isEmpty(list)){
            for(GoodsGalleryEntity galleryEntity : list){
                imageList.add(galleryEntity.getImgUrl());
            }
        }
        return imageList;
    }

    private String getGoodsRetailPrice(GoodsEntity goodsEntity){
        if(null == goodsEntity){
            return "";
        }
        Map<String, Object> params = new HashMap<>();
        params.put("goodsId", Integer.valueOf(goodsEntity.getId()));
        List<GoodsGalleryEntity> list = goodsGalleryService.queryList(params);

        String retailPrice = "0";
        if(goodsEntity.getRetailPrice() != null){
            retailPrice = goodsEntity.getRetailPrice().toString();
        }
        if(goodsEntity.getProductList() != null && goodsEntity.getProductList().size() > 1){
            BigDecimal bigPrice = goodsEntity.getProductList().get(0).getRetailPrice();
            BigDecimal smallPrice = goodsEntity.getProductList().get(0).getRetailPrice();
            for(int i = 1, len = goodsEntity.getProductList().size(); i < len; i ++){
                if(null != bigPrice && bigPrice.compareTo(goodsEntity.getProductList().get(i).getRetailPrice()) < 0){
                    bigPrice = goodsEntity.getProductList().get(i).getRetailPrice();
                }

                if(null != smallPrice && smallPrice.compareTo(goodsEntity.getProductList().get(i).getRetailPrice()) > 0){
                    smallPrice = goodsEntity.getProductList().get(i).getRetailPrice();
                }
            }

            retailPrice = (smallPrice == null? "0" : smallPrice.toString()) +
                    "-" + (bigPrice == null? "0" : bigPrice.toString());
        }
        return retailPrice;
    }

    /**
     * 修改
     */
    @CanUserUpdateRecord
    @RequestMapping("/update")
    @Transactional(rollbackFor = Exception.class)
    public Result update(@RequestBody GoodsEntity goods) {
        if(goods.getName().length() > 15){
            return Result.failure("商品名称名称不能超过15个字符");
        }
        if(null == goods.getUpdateUserId()){
            return Result.failure("数据的更新者ID不能为空");
        }
        GoodsEntity goodsEntity = goodsService.queryObject(goods.getId());
        if(null == goodsEntity){
            return Result.failure("商品不存在");
        }
        if(StringUtils.isEmpty(goods.getBrandId())){
            throw new RRException("直播间名称为空");
        }
        BrandEntity brand = brandService.queryObject(goods.getBrandId());
        if(brand == null){
            throw new RRException("直播间为空");
        }
        goodsService.update(goods);

        //发送数据给api平台
        sendDataToApi(goods);

        return Result.success();
    }

    /**
     * 删除
     */
    @CanUserUpdateRecord
    @RequestMapping("/delete")
    public Result delete(@RequestBody Integer[] ids) {
        if(null != ids && ids.length > 0){
            for(int i = 0 ;i<ids.length ; i++){
                int id = ids[i];
                GoodsEntity goodsEntity = goodsService.queryObject(id);
                if(null != goodsEntity){
                    //将删除信息更新到api
                    sendDeleteDataToApi(goodsEntity);
                }
            }
        }
        goodsService.deleteBatch(ids);

        return Result.success();
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    public Result queryAll(@RequestBody Map<String, Object> params) {
        List<Long> roleIdList = getUser().getRoleIdList();
        if (!roleIdList.contains(1L) && !roleIdList.contains(5L)) {
            params.put("brandIdList", mySysUserBrandService.queryBrandIdList(getUserId()));
        }

        params.put("isDelete", 0);
        List<GoodsEntity> list = goodsService.queryList(params);

        return Result.success( list);
    }


    /**
     * 商品回收站
     *
     * @param params
     * @return
     */
    @RequestMapping("/historyList")
    public Result historyList(@RequestBody Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        PageUtils pageUtil = new PageUtils(new ArrayList<>(), 0, query.getLimit(), query.getPage());
        query.put("isDelete", 1);
        long userId = getUserId();
        List<Long> roleIdList = getUser().getRoleIdList();
        if (!roleIdList.contains(1L) && !roleIdList.contains(5L)) {
            if(null == getDeptId()){
                return Result.success( pageUtil);
            }
            query.put("deptIdList" , getDeptId());
        }
        List<GoodsEntity> goodsList = goodsService.queryList(query);
        int total = goodsService.queryTotal(query);

        pageUtil = new PageUtils(goodsList, total, query.getLimit(), query.getPage());

        return Result.success( pageUtil);
    }

    /**
     * 商品从回收站恢复
     */
    @RequestMapping("/back")
    public Result back(@RequestBody Integer[] ids) {
        goodsService.back(ids);

        return Result.success();
    }

    /**
     * 总计
     */
    @RequestMapping("/queryTotal")
    public Result queryTotal(@RequestBody Map<String, Object> params) {

        params.put("isDelete", 0);
        int sum = goodsService.queryTotal(params);
        return Result.success(sum);
    }

    /**
     * 上架
     */
    @CanUserUpdateRecord
    @RequestMapping("/enSale")
    public Result enSale(@RequestBody String id) {
        for(String ids : id.split(",")){
            goodsService.enSale(Integer.parseInt(ids));
        }

        return Result.success();
    }

    /**
     * 下架
     */
    @CanUserUpdateRecord
    @RequestMapping("/unSale")
    public Result unSale(@RequestBody String id) {
        for(String ids : id.split(",")){
            goodsService.unSale(Integer.parseInt(ids));
        }

        return Result.success();
    }

    /**
     * 根据场景码过去商品分类列表
     */
    @GetMapping("/getGoods")
    public Result getGoodsById(@RequestParam(name =  "goodsId") Integer goodsId) {
        if(StringUtils.isEmpty(goodsId)){
            return Result.failure("入参不完整，请检查入参");
        }
        GoodsEntity goodsEntity =  goodsService.queryObject(goodsId);
        Map<String ,Object> resultMap = new HashMap<>();
        resultMap.put("goods" , goodsEntity);
        return Result.success(resultMap);
    }

    @GetMapping("/getGoodsDetail")
    public Result getGoodsDetail(@RequestParam(name =  "goodsId") String goodsId,
                            @RequestParam(name =  "brandId") String brandId,
                            @RequestParam(name =  "sceneNum") String sceneNum) {
        if(StringUtils.isEmpty(goodsId)){
            return Result.failure("入参不完整，请检查入参");
        }

        List resultList = new ArrayList();
        Map<String ,Object> result = new HashMap<>();

        if(!StringUtils.isEmpty(brandId) && !StringUtils.isEmpty(sceneNum)){
            Integer brand = brandService.queryIdByScene("?m=" + sceneNum);
            if(null == brand || !brandId.equals(brand.toString()) ){
                return Result.success(result);
            }
        }

        String[] ids = goodsId.split(",");
        for(String id : ids){
            GoodsEntity goodsEntity =  goodsService.queryObject(Integer.valueOf(id));
            if(goodsEntity == null){
                return Result.failure("商品不存在");
            }

            Map<String, Object> params = new HashMap<>();
            params.put("goodsId", Integer.valueOf(id));
            List<GoodsGalleryEntity> list = goodsGalleryService.queryList(params);

            String retailPrice = "0";
            if(goodsEntity.getRetailPrice() != null){
                retailPrice = goodsEntity.getRetailPrice().toString();
            }
            if(goodsEntity.getProductList() != null && goodsEntity.getProductList().size() > 1){
                BigDecimal bigPrice = goodsEntity.getProductList().get(0).getRetailPrice();
                BigDecimal smallPrice = goodsEntity.getProductList().get(0).getRetailPrice();
                for(int i = 1, len = goodsEntity.getProductList().size(); i < len; i ++){
                    if(bigPrice.compareTo(goodsEntity.getProductList().get(i).getRetailPrice()) < 0){
                        bigPrice = goodsEntity.getProductList().get(i).getRetailPrice();
                    }

                    if(smallPrice.compareTo(goodsEntity.getProductList().get(i).getRetailPrice()) > 0){
                        smallPrice = goodsEntity.getProductList().get(i).getRetailPrice();
                    }
                }

                retailPrice = (smallPrice == null? "0" : smallPrice.toString()) +
                        "-" + (bigPrice == null? "0" : bigPrice.toString());
            }

            //获取图片列表
            List<String> imageList = new ArrayList<>();
            imageList.add(goodsEntity.getPrimaryPicUrl());

            if(list != null && list.size() > 0){
                for(GoodsGalleryEntity galleryEntity : list){
                    imageList.add(galleryEntity.getImgUrl());
                }
            }

            Map<String ,Object> resultMap = new HashMap<>();
            resultMap.put("id", goodsEntity.getId());
            resultMap.put("name", goodsEntity.getName());
            resultMap.put("desc", goodsEntity.getGoodsSimpleDesc());
            resultMap.put("isOnSale", goodsEntity.getIsOnSale());
            resultMap.put("imageList", imageList);
            resultMap.put("retailPrice", retailPrice);

            resultList.add(resultMap);
            result.put("goods", resultList);
        }


        return Result.success(result);
    }

    /**
     * 根据场景码过去商品分类列表
     */
    @GetMapping("/getCategoryListByScene")
    public Result getGoodsListByScene(@RequestParam(name =  "sceneNum") String sceneNum) {
        if(StringUtils.isEmpty(sceneNum)){
            return Result.failure("入参不完整，请检查入参");
        }
        Integer brandId = brandService.queryIdByScene("?m=" + sceneNum);
        if(null == brandId){
            return Result.failure("当前场景码获取不到brandId");
        }
        QueryWrapper<GoodsEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("brand_id" , brandId);
        List<Map<String,Object>> categoryList = goodsService.queryGoodsCategory(queryWrapper);
        Map<String ,Object> resultMap = new HashMap<>();
        resultMap.put("list" , categoryList);
        return Result.success(resultMap);
    }

    /**
     * 根据场景码查询商品列表
     */
    @GetMapping("/getGoodsListByScene")
    public Result getGoodsListByScene(@RequestParam(name =  "sceneNum") String sceneNum,
                                 @RequestParam(name =  "categoryId") Integer categoryId,
                                 @RequestParam(name =  "goodsName") String goodsName,
                                 @RequestParam(name =  "pageNum") Long pageNum,
                                 @RequestParam(name =  "pageSize") Long pageSize) {
        if(StringUtils.isEmpty(sceneNum) || null == pageNum || null == pageSize){
            return Result.failure("入参不完整，请检查入参");
        }
        Integer brandId = brandService.queryIdByScene("?m=" + sceneNum);
        if(null == brandId){
            return Result.failure("当前场景码获取不到brandId");
        }
        IPage<Map<String,Object>> page = new Page<>(pageNum , pageSize);
        IPage<Map<String,Object>> resultPage = goodsService.queryListTwoWithoutFilter(page , brandId , categoryId , goodsName);
        if(null == resultPage){
            return Result.failure("当前场景码获取不到商品列表");
        }
        return Result.success(PageUtils.assembleResult(resultPage.getTotal() , resultPage.getPages() ,
                     resultPage.getCurrent(), pageSize , resultPage.getRecords()));
    }
}
