package com.ghy.web.controller.goods;

import com.ghy.common.annotation.Log;
import com.ghy.common.core.controller.BaseController;
import com.ghy.common.core.domain.AjaxResult;
import com.ghy.common.core.page.TableDataInfo;
import com.ghy.common.enums.BusinessType;
import com.ghy.common.utils.ExceptionUtil;
import com.ghy.common.utils.ShiroUtils;
import com.ghy.common.utils.StringUtils;
import com.ghy.common.utils.bean.BeanUtils;
import com.ghy.common.utils.poi.ExcelUtil;
import com.ghy.goods.domain.*;
import com.ghy.goods.service.*;
import com.ghy.system.domain.SysArea;
import com.ghy.system.service.ISysAreaService;
import io.swagger.annotations.ApiModel;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/goods/goods")
public class GoodsController extends BaseController {

    private static final String PREFIX = "goods/goods";

    @Resource
    private GoodsService goodsService;
    @Resource
    private DeptGoodsCategoryService deptGoodsCategoryService;
    @Resource
    private GoodsCategoryService goodsCategoryService;
    @Resource
    private GoodsImgsService goodsImgsService;
    @Resource
    private GoodsAreaService goodsAreaService;
    @Resource
    private GoodsStandardService goodsStandardService;
    @Resource
    private ISysAreaService sysAreaService;
    @Resource
    private IInsuranceManagerService insuranceManagerService;
    @Resource
    private IDeptCategoryInsuranceRelationService deptCategoryInsuranceRelationService;

    @RequiresPermissions("goods:goods:view")
    @GetMapping()
    public String goods() {
        return PREFIX + "/goods";
    }

//    @RequiresPermissions("goods:goods:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Goods goods) {
        startPage();
        List<Goods> list = goodsService.selectGoodsList(goods);
        list.forEach(one -> {
            // 补全商品
            List<GoodsArea> goodsAreas = goodsAreaService.selectByGoodsId(one.getGoodsId());
            one.setGoodsAreaList(goodsAreas);

            // 补全商品类别
            List<GoodsStandard> goodsStandards = goodsStandardService.selectByGoodsId(one.getGoodsId());
            one.setGoodsStandardList(goodsStandards);
        });
        return getDataTable(list);
    }

    @PostMapping("/app/detail")
    @ResponseBody
    public AjaxResult appDetail(@RequestBody Goods goods){
        try {
            GoodsEditReq goodsEditReq = new GoodsEditReq();
            List<Goods> list = goodsService.selectGoodsList(goods);
            if(CollectionUtils.isNotEmpty(list)){
                BeanUtils.copyProperties(list.get(0), goodsEditReq);
            }
            // 补全商品服务区域
            List<GoodsArea> goodsAreas = goodsAreaService.selectByGoodsId(goodsEditReq.getGoodsId());
            if(CollectionUtils.isNotEmpty(goodsAreas)){
                String areaName;
                GoodsArea goodsArea = goodsAreas.get(0);
                // 第三级
                SysArea sysArea3 = sysAreaService.selectById(goodsArea.getCountryAreaId());
                // 第二级
                SysArea sysArea2 = sysAreaService.selectByAreaCode(sysArea3.getParentCode());
                // 第一级
                SysArea sysArea1 = sysAreaService.selectByAreaCode(sysArea2.getParentCode());
                areaName = sysArea1.getAreaName() + "-" + sysArea2.getAreaName();
                goodsEditReq.setAreaConcatName(areaName);
                goodsEditReq.setParentAreaId(sysArea2.getAreaId());
            }
            goodsEditReq.setGoodsAreaList(goodsAreas);


            // 补全商品规格
            List<GoodsStandard> goodsStandards = goodsStandardService.selectByGoodsId(goodsEditReq.getGoodsId());
            if(CollectionUtils.isNotEmpty(goodsStandards)){
                String standardConcatName;
                GoodsStandard goodsStandard = goodsStandards.get(0);
                DeptGoodsCategory deptGoodsCategory = deptGoodsCategoryService.get(goodsStandard.getDeptGoodsCategoryId());
                // 当前层级4
                GoodsCategory goodsCategory4 = goodsCategoryService.selectById(deptGoodsCategory.getGoodsCategoryId());
                GoodsCategory goodsCategory3 = goodsCategoryService.selectById(goodsCategory4.getParentCategoryId());
                GoodsCategory goodsCategory2 = goodsCategoryService.selectById(goodsCategory3.getParentCategoryId());
                GoodsCategory goodsCategory1 = goodsCategoryService.selectById(goodsCategory2.getParentCategoryId());
                standardConcatName = goodsCategory1.getGoodsCategoryName() + "-" + goodsCategory2.getGoodsCategoryName() + "-" + goodsCategory3.getGoodsCategoryName();
                goodsEditReq.setCategoryConcatName(standardConcatName);
            }
            //
            goodsStandards.forEach(goodsStandard -> {
                DeptGoodsCategory deptGoodsCategory = deptGoodsCategoryService.get(goodsStandard.getDeptGoodsCategoryId());
                GoodsCategory category = goodsCategoryService.selectById(deptGoodsCategory.getGoodsCategoryId());
                goodsStandard.setGoodsCategoryName(category.getGoodsCategoryName());
                goodsStandard.setChecked(true);
                goodsStandard.setOneRate(deptGoodsCategory.getOneRate());
                goodsStandard.setTwoRate(deptGoodsCategory.getTwoRate());
                goodsStandard.setThreeRate(deptGoodsCategory.getThreeRate());
                goodsStandard.setDeptRate(deptGoodsCategory.getDeptRate());
                goodsStandard.setDeptMoney(deptGoodsCategory.getDeptMoney());
                goodsStandard.setRetainMoney(deptGoodsCategory.getRetainMoney());
                goodsStandard.setRetainRate(deptGoodsCategory.getRetainRate());

            });
            goodsEditReq.setGoodsStandardList(goodsStandards);

            // 补全商品类目及父级类目信息
            GoodsCategory goodsCategory = goodsCategoryService.selectById(goodsEditReq.getDeptGoodsCategoryId());
            goodsEditReq.setDeptGoodsCategoryName(goodsCategory.getGoodsCategoryName());
            if (goodsCategory.getParentCategoryId() != null) {
                GoodsCategory parGoodsCategory = goodsCategoryService.selectById(goodsCategory.getParentCategoryId());
                goodsEditReq.setParGoodsCategoryId(parGoodsCategory.getGoodsCategoryId());
                goodsEditReq.setParGoodsCategoryName(parGoodsCategory.getGoodsCategoryName());
            }
            List<String> detailUrl = new ArrayList<>();
            List<String> lbUrl = new ArrayList<>();
            List<GoodsImgs> goodsImgs = goodsImgsService.selectByGoodsId(goods.getGoodsId());
            goodsImgs.forEach(imgs -> {
                if(imgs.getImgType() == 0){
                    lbUrl.add(imgs.getImgUrl());
                }else if(imgs.getImgType() == 1){
                    detailUrl.add(imgs.getImgUrl());
                }
            });
            goodsEditReq.setLbUrl(lbUrl);
            goodsEditReq.setDetailUrl(detailUrl);
            return AjaxResult.success(goodsEditReq);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

    @PostMapping("/app/list")
    @ResponseBody
    public TableDataInfo appList(@RequestBody Goods goods) {
        // 判断类目id是否为第三级，不是的话需要找到所有符合条件的第三级类目id作为新的条件
        if (goods.getDeptGoodsCategoryId() != null) {
            logger.info("入参：" + goods.getDeptGoodsCategoryId());
            GoodsCategory goodsCategory = goodsCategoryService.selectById(goods.getDeptGoodsCategoryId());
            logger.info("查询到的类目：" + goodsCategory);
            if (goodsCategory.getLevel() == 0) {
                goods.setDeptGoodsCategoryId(null);
            } else if (goodsCategory.getLevel() == 1) {
                GoodsCategory params = new GoodsCategory();
                params.setParentCategoryId(goodsCategory.getGoodsCategoryId());
                List<GoodsCategory> secondCategories = goodsCategoryService.selectGoodsCategoryList(params);
                List<Long> secondCategoryIds = secondCategories.stream().map(GoodsCategory::getGoodsCategoryId).collect(Collectors.toList());
                List<Long> thirdCategoryIds = new ArrayList<Long>();
                secondCategoryIds.forEach(id -> {
                    params.setParentCategoryId(id);
                    List<GoodsCategory> thirdCategories = goodsCategoryService.selectGoodsCategoryList(params);
                    thirdCategoryIds.addAll(thirdCategories.stream().map(GoodsCategory::getGoodsCategoryId).collect(Collectors.toList()));
                });
                if (CollectionUtils.isNotEmpty(thirdCategoryIds)) {
                    goods.setDeptGoodsCategoryId(null);
                    goods.setDeptGoodsCategoryIds(thirdCategoryIds);
                } else {
                    goods.setDeptGoodsCategoryId(-1l);
                }
            } else if (goodsCategory.getLevel() == 2) {
                GoodsCategory params = new GoodsCategory();
                params.setParentCategoryId(goodsCategory.getGoodsCategoryId());
                List<GoodsCategory> filteredCategory = goodsCategoryService.selectGoodsCategoryList(params);
                List<Long> filteredCategoryIds = filteredCategory.stream().map(GoodsCategory::getGoodsCategoryId).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(filteredCategoryIds)) {
                    goods.setDeptGoodsCategoryId(null);
                    goods.setDeptGoodsCategoryIds(filteredCategoryIds);
                } else {
                    goods.setDeptGoodsCategoryId(-1l);
                }
            }
        }

        startPage();

        List<Goods> list = goodsService.selectGoodsList(goods);
        list.forEach(one -> {
            // 补全商品服务区域
            List<GoodsArea> goodsAreas = goodsAreaService.selectByGoodsId(one.getGoodsId());
            one.setGoodsAreaList(goodsAreas);

            // 补全商品规格
            List<GoodsStandard> goodsStandards = goodsStandardService.selectByGoodsId(one.getGoodsId());
            one.setGoodsStandardList(goodsStandards);

            // 补全商品类目及父级类目信息
            GoodsCategory goodsCategory = goodsCategoryService.selectById(one.getDeptGoodsCategoryId());
            one.setDeptGoodsCategoryName(goodsCategory.getGoodsCategoryName());
            if (goodsCategory.getParentCategoryId() != null) {
                GoodsCategory parGoodsCategory = goodsCategoryService.selectById(goodsCategory.getParentCategoryId());
                one.setParGoodsCategoryId(parGoodsCategory.getGoodsCategoryId());
                one.setParGoodsCategoryName(parGoodsCategory.getGoodsCategoryName());
            }
        });
        return getDataTable(list);
    }

    @PostMapping("/hot/list")
    @ResponseBody
    public TableDataInfo hotList(@RequestBody Goods goods) {
        DeptGoodsCategory deptGoodsCategory = new DeptGoodsCategory();
        deptGoodsCategory.setDeptId(goods.getDeptId());
        deptGoodsCategory.setIsHot(1);
        deptGoodsCategory.setLevel(2);
        List<DeptGoodsCategory> categoryList = deptGoodsCategoryService.list(deptGoodsCategory);
        Collection<Long> ids = new ArrayList<>();
        categoryList.forEach(category -> {
            ids.add(category.getGoodsCategoryId());
        });

        startPage();
        List<Goods> list = goodsService.selectByCategoryIds(ids);
        list = list.stream().filter(x -> x.getStatus() == 0).collect(Collectors.toList());
        list.forEach(one -> {
            // 补全商品图片信息
            List<GoodsImgs> goodsImgs = goodsImgsService.selectByGoodsId(one.getGoodsId());
            Map<Integer, List<GoodsImgs>> listMap = new HashMap<>();
            for (GoodsImgs goodsImg : goodsImgs) {
                listMap.computeIfAbsent(goodsImg.getImgType(), k -> new ArrayList<>()).add(goodsImg);
            }
            one.setGoodsImgsMap(listMap);

            // 补全商品
            List<GoodsArea> goodsAreas = goodsAreaService.selectByGoodsId(one.getGoodsId());
            one.setGoodsAreaList(goodsAreas);

            // 补全商品类别
            List<GoodsStandard> goodsStandards = goodsStandardService.selectByGoodsId(one.getGoodsId());
            one.setGoodsStandardList(goodsStandards);
        });
        return getDataTable(list);
    }

    @PostMapping("/addGoods")
    @ResponseBody
    public AjaxResult addGoods(@RequestBody Goods goods) {
        try {
            goodsService.addGoods(goods);
            return AjaxResult.success("新增成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return AjaxResult.error(ExceptionUtil.getExceptionMessage(e));
        }
    }

    @PostMapping("/getDetail")
    @ResponseBody
    public AjaxResult getDetail(@RequestBody Goods goods) {
        try {
            Goods result = goodsService.selectById(goods.getGoodsId());

            // 补全商品类目及父级类目信息
            GoodsCategory goodsCategory = goodsCategoryService.selectById(result.getDeptGoodsCategoryId());
            result.setDeptGoodsCategoryName(goodsCategory.getGoodsCategoryName());
            if (goodsCategory.getParentCategoryId() != null) {
                GoodsCategory parGoodsCategory = goodsCategoryService.selectById(goodsCategory.getParentCategoryId());
                result.setParGoodsCategoryId(parGoodsCategory.getGoodsCategoryId());
                result.setParGoodsCategoryName(parGoodsCategory.getGoodsCategoryName());
            }

            // 补全商品图片信息
            List<GoodsImgs> goodsImgs = goodsImgsService.selectByGoodsId(result.getGoodsId());
            Map<Integer, List<GoodsImgs>> listMap = new HashMap<>();
            for (GoodsImgs goodsImg : goodsImgs) {
                listMap.computeIfAbsent(goodsImg.getImgType(), k -> new ArrayList<>()).add(goodsImg);
            }
            result.setGoodsImgsMap(listMap);

            // 补全商品区域
            List<GoodsArea> goodsAreas = goodsAreaService.selectByGoodsId(result.getGoodsId());
            result.setGoodsAreaList(goodsAreas);

            // 补全商品类别
            List<GoodsStandard> goodsStandards = goodsStandardService.selectByGoodsId(result.getGoodsId());
            goodsStandards.stream().forEach(goodsStandard -> {
                if (StringUtils.isEmpty(goodsStandard.getGoodsUnit())) {
                    goodsStandard.setGoodsUnit(result.getGoodsUnit());
                }
                BigDecimal finalPrice = BigDecimal.ZERO;
                // 获取规格的扣点
                DeptGoodsCategory deptGoodsCategory = deptGoodsCategoryService.get(goodsStandard.getDeptGoodsCategoryId());
                if(deptGoodsCategory.getOneRate() != null){
                    finalPrice = finalPrice.add(BigDecimal.valueOf(Double.parseDouble(deptGoodsCategory.getOneRate())).multiply(goodsStandard.getGoodsPrice()));
                }
                if(deptGoodsCategory.getTwoRate() != null){
                    finalPrice = finalPrice.add(BigDecimal.valueOf(Double.parseDouble(deptGoodsCategory.getTwoRate())).multiply(goodsStandard.getGoodsPrice()));
                }
                if(deptGoodsCategory.getThreeRate() != null){
                    finalPrice = finalPrice.add(BigDecimal.valueOf(Double.parseDouble(deptGoodsCategory.getThreeRate())).multiply(goodsStandard.getGoodsPrice()));
                }
                if(goodsStandard.getExtMoney() != null){
                    finalPrice = finalPrice.add(goodsStandard.getExtMoney());
                }
                goodsStandard.setFinalPrice(finalPrice);
            });
            result.setGoodsStandardList(goodsStandards);
            // 所有保险信息
            List<InsuranceManager> insuranceManagers = insuranceManagerService.selectInsuranceManagerList(new InsuranceManager());
            // 查询本类目保险信息
            DeptCategoryInsuranceRelation param = new DeptCategoryInsuranceRelation();
            param.setType("01");
            param.setDeptCategoryId(goodsStandards.get(0).getDeptGoodsCategoryId());
            List<DeptCategoryInsuranceRelation> deptCategoryInsuranceRelations = deptCategoryInsuranceRelationService.selectDeptCategoryInsuranceRelationList(param);
            if(CollectionUtils.isNotEmpty(deptCategoryInsuranceRelations)){
                Map<Long, List<DeptCategoryInsuranceRelation>> insuranceMap = deptCategoryInsuranceRelations.stream().collect(Collectors.groupingBy(DeptCategoryInsuranceRelation::getInsuranceId));
                // 目标保险
                List<InsuranceManager> goal = new ArrayList<>();
                insuranceManagers.forEach(model->{
                    if(insuranceMap.containsKey(model.getId())){
                        goal.add(model);
                    }
                });
                result.setInsuranceManagers(goal);
            }
            return AjaxResult.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return AjaxResult.error(ExceptionUtil.getExceptionMessage(e));
        }
    }

    @Log(title = "商品管理", businessType = BusinessType.EXPORT)
    @RequiresPermissions("goods:goods:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Goods goods) {
        List<Goods> list = goodsService.selectGoodsList(goods);
        ExcelUtil<Goods> util = new ExcelUtil<Goods>(Goods.class);
        return util.exportExcel(list, "商品数据");
    }

    @RequiresPermissions("goods:goods:remove")
    @Log(title = "商品管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove/{ids}")
    @ResponseBody
    public AjaxResult remove(@PathVariable String ids) {
        try {
            return toAjax(goodsService.deleteGoodsByIds(ids));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 新增商品
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        Long parentId = ShiroUtils.getSysUser().getParentId();
        DeptGoodsCategory category = new DeptGoodsCategory();
        category.setDeptId(parentId);
        mmap.put("deptGoodsCategories", deptGoodsCategoryService.list(category));
        return PREFIX + "/add";
    }

    /**
     * 新增保存商品
     */
    @RequiresPermissions("goods:goods:add")
    @Log(title = "商品管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated Goods goods) {
        goods.setCreateBy(getLoginName());
        goods.setDeptId(getSysUser().getDeptId());
        return toAjax(goodsService.insertGoods(goods));
    }

    /**
     * 修改商品
     */
    @RequiresPermissions("goods:goods:edit")
    @GetMapping("/edit/{goodsId}")
    public String edit(@PathVariable("goodsId") Long goodsId, ModelMap mmap) {
        Long parentId = ShiroUtils.getSysUser().getParentId();
        DeptGoodsCategory category = new DeptGoodsCategory();
        category.setDeptId(parentId);
        mmap.put("deptGoodsCategories", deptGoodsCategoryService.list(category));
        mmap.put("goods", goodsService.selectById(goodsId));
        return PREFIX + "/edit";
    }

    /**
     * 修改保存商品
     */
    @RequiresPermissions("goods:goods:edit")
    @Log(title = "商品管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated Goods goods) {
        goods.setUpdateBy(getLoginName());
        return toAjax(goodsService.updateGoods(goods));
    }

    @PostMapping("/app/edit")
    @ResponseBody
    public AjaxResult appEditSave(@RequestBody @Validated Goods goods) {

        goodsService.edit(goods);
        return AjaxResult.success();
    }

    /**
     * 校验商品名称
     */
    @PostMapping("/checkGoodsNameUnique")
    @ResponseBody
    public String checkGoodsNameUnique(Goods goods) {
        return goodsService.checkGoodsNameUnique(goods);
    }

    /**
     * 校验商品编码
     */
    @PostMapping("/checkGoodsCodeUnique")
    @ResponseBody
    public String checkGoodsCodeUnique(Goods goods) {
        return goodsService.checkGoodsCodeUnique(goods);
    }

    /**
     * 修改商品状态
     *
     * @param goodsId 商品ID
     * @param status  0=上架,1=下架,2删除
     */
    @PostMapping("/status")
    @ResponseBody
    public AjaxResult status(Long goodsId, Integer status) {
        try {
            Goods goods = new Goods();
            goods.setGoodsId(goodsId);
            goods.setStatus(status);
            goodsService.updateGoods(goods);
            return AjaxResult.success("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return AjaxResult.error(ExceptionUtil.getExceptionMessage(e));
        }
    }

    /**
     * 修改商品状态
     */
    @PostMapping("/app/updateStatus")
    @ResponseBody
    public AjaxResult status(@RequestBody Goods goods) {
        try {
            goodsService.updateGoods(goods);
            return AjaxResult.success("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return AjaxResult.error(ExceptionUtil.getExceptionMessage(e));
        }
    }
}
