package com.ghy.web.controller.goods;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
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.domain.Ztree;
import com.ghy.common.core.text.Convert;
import com.ghy.common.enums.BusinessType;
import com.ghy.common.enums.ImgType;
import com.ghy.common.utils.ExceptionUtil;
import com.ghy.common.utils.ShiroUtils;
import com.ghy.common.utils.StringUtils;
import com.ghy.goods.domain.*;
import com.ghy.goods.service.*;
import com.ghy.web.pojo.vo.AppCategoryRequest;
import com.ghy.web.pojo.vo.HotCategoryResponse;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@CrossOrigin(origins = "*")
@RequestMapping("goods/deptcategory")
public class GoodsDeptCategoryController extends BaseController {

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

    @Resource
    DeptGoodsCategoryService deptGoodsCategoryService;

    @Resource
    private GoodsCategoryService goodsCategoryService;

    @Resource
    ICategoryInsuranceRelationService categoryInsuranceRelationService;

    @Resource
    IDeptCategoryInsuranceRelationService deptCategoryInsuranceRelationService;

    @Resource
    IInsuranceManagerService insuranceManagerService;

    @Autowired
    private GoodsImgsService goodsImgsService;

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

    @RequiresPermissions("goods:deptcategory:add")
    @GetMapping("/add/{type}")
    public String add(@PathVariable("type") Integer type, ModelMap mmap) {
        mmap.put("type", type);
        return PREFIX + "/add";
    }

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

    @RequiresPermissions("goods:deptcategory:add")
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult add(String menuIds) {
        Long parentId = ShiroUtils.getSysUser().getDept().getParentId();
        Long[] categoryIds = Convert.toLongArray(menuIds);
        return deptGoodsCategoryService.batchAdd(parentId, categoryIds);
    }

    @PostMapping("/listByStep")
    @ResponseBody
    public AjaxResult listByStep(@RequestBody DeptGoodsCategory deptGoodsCategory) {
        try {
            return AjaxResult.success(deptGoodsCategoryService.listByStep(deptGoodsCategory));
        } catch (Exception e) {
            logger.error(e.getMessage());
            return AjaxResult.error(ExceptionUtil.getExceptionMessage(e));
        }

    }

    @PostMapping("/app/listByStep")
    @ResponseBody
    public AjaxResult appListByStep(@RequestBody DeptGoodsCategory deptGoodsCategory) {
        List<DeptGoodsCategory> resList = new ArrayList<>();
        try {
            if (deptGoodsCategory.getIsAllNode() == null || !deptGoodsCategory.getIsAllNode()) {
                List<DeptGoodsCategory> list = deptGoodsCategoryService.listByStep(deptGoodsCategory);
                if (!CollectionUtils.isEmpty(list) && list.get(0).getLevel() > 1) {
                    DeptGoodsCategory allGoodsNode = new DeptGoodsCategory();
                    allGoodsNode.setGoodsCategoryName("全部");
                    allGoodsNode.setIsAllNode(true);
                    resList.add(allGoodsNode);
                }
                resList.addAll(list);
            }
            return AjaxResult.success(resList);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return AjaxResult.error(ExceptionUtil.getExceptionMessage(e));
        }

    }

    @PostMapping("/app/hot/category")
    @ResponseBody
    public AjaxResult appHotCategory(@RequestBody DeptGoodsCategory deptGoodsCategory) {
        try {
            deptGoodsCategory.setIsHot(1);
            deptGoodsCategory.setStatus(0);
            List<DeptGoodsCategory> hotCategories = deptGoodsCategoryService.list(deptGoodsCategory);
            List<HotCategoryResponse> responses = new ArrayList<HotCategoryResponse>();
            for (DeptGoodsCategory hotCategory: hotCategories) {
                // 查询展示的图片
                GoodsImgs qryImgsObj = new GoodsImgs();
                qryImgsObj.setRemark(hotCategory.getDeptGoodsCategoryId().toString());
                qryImgsObj.setImgType(ImgType.HOT_CATEGORY_IMG.getId());
                qryImgsObj.setGoodsId(0L);
                List<GoodsImgs> goodsImgs = goodsImgsService.qryGoodsImgs(qryImgsObj);
                hotCategory.setHotCategoryImgs(goodsImgs.stream().map(GoodsImgs::getImgUrl).collect(Collectors.toList()));

                HotCategoryResponse hotCategoryResponse = new HotCategoryResponse();
                BeanUtils.copyProperties(hotCategory, hotCategoryResponse);
                hotCategoryResponse.setId(hotCategory.getDeptGoodsCategoryId());
                if(StringUtils.isNotEmpty(hotCategory.getHotName())){
                    hotCategoryResponse.setName(hotCategory.getHotName());
                }else {
                    hotCategoryResponse.setName(hotCategory.getGoodsCategoryName());
                }
                hotCategoryResponse.setDesc(hotCategory.getRemark());
                hotCategoryResponse.setImgs(hotCategory.getHotCategoryImgs());
                responses.add(hotCategoryResponse);
            }
            return AjaxResult.success(responses);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return AjaxResult.error(ExceptionUtil.getExceptionMessage(e));
        }

    }

    @RequiresPermissions("goods:deptcategory:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        DeptGoodsCategory deptGoodsCategory = deptGoodsCategoryService.get(id);
        CategoryInsuranceRelation relation = new CategoryInsuranceRelation();
        relation.setGoodsCategoryId(deptGoodsCategory.getGoodsCategoryId());
        List<CategoryInsuranceRelation> relations = categoryInsuranceRelationService.selectCategoryInsuranceRelationList(relation);
        // 当第四级没有的时候，往上找三级
        if(CollectionUtil.isEmpty(relations)){
            GoodsCategory model = goodsCategoryService.selectById(deptGoodsCategory.getGoodsCategoryId());
            CategoryInsuranceRelation parentRelation = new CategoryInsuranceRelation();
            parentRelation.setGoodsCategoryId(model.getParentCategoryId());
            relations = categoryInsuranceRelationService.selectCategoryInsuranceRelationList(parentRelation);
            // 当第三级没有的时候，往上找二级
            if(CollectionUtil.isEmpty(relations)){
                GoodsCategory parentModel = goodsCategoryService.selectById(model.getParentCategoryId());
                CategoryInsuranceRelation topRelation = new CategoryInsuranceRelation();
                topRelation.setGoodsCategoryId(parentModel.getParentCategoryId());
                relations = categoryInsuranceRelationService.selectCategoryInsuranceRelationList(topRelation);
            }
        }
        // pc保险设置
        List<InsuranceManager> pcInsuranceList = new ArrayList<>();
        // 商城保险设置
        List<InsuranceManager> shopInsuranceList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(relations)){
            List<InsuranceManager> list = insuranceManagerService.selectByIds(relations.stream().map(CategoryInsuranceRelation::getInsuranceId).collect(Collectors.toList()));
            list.forEach(model->{
                model.setInsuranceName(model.getCompanyName() + "||" + model.getInsuranceName() + "||" + model.getInsuranceAmount() + "元");
                // 查看pc勾选状态
                DeptCategoryInsuranceRelation pcParam = new DeptCategoryInsuranceRelation();
                pcParam.setType("02");
                pcParam.setInsuranceId(model.getId());
                pcParam.setDeptCategoryId(deptGoodsCategory.getDeptGoodsCategoryId());
                InsuranceManager pcModel = new InsuranceManager();
                BeanUtil.copyProperties(model, pcModel);
                if(CollectionUtil.isNotEmpty(deptCategoryInsuranceRelationService.selectDeptCategoryInsuranceRelationList(pcParam))){
                    pcModel.setFlag(true);
                }
                pcInsuranceList.add(pcModel);

                DeptCategoryInsuranceRelation shopParam = new DeptCategoryInsuranceRelation();
                shopParam.setType("01");
                shopParam.setInsuranceId(model.getId());
                shopParam.setDeptCategoryId(deptGoodsCategory.getDeptGoodsCategoryId());
                InsuranceManager shopModel = new InsuranceManager();
                BeanUtil.copyProperties(model, shopModel);
                if(CollectionUtil.isNotEmpty(deptCategoryInsuranceRelationService.selectDeptCategoryInsuranceRelationList(shopParam))){
                    shopModel.setFlag(true);
                }
                shopInsuranceList.add(shopModel);
            });
        }
        mmap.put("pcInsurances", pcInsuranceList);
        mmap.put("shopInsurances", shopInsuranceList);
        mmap.put("deptGoodsCategory", deptGoodsCategory);
        return PREFIX + "/edit";
    }

    @RequiresPermissions("goods:deptcategory:edit")
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult edit(DeptGoodsCategory category) {
        // 更新保险设置
        deptCategoryInsuranceRelationService.updateDeptCategoryInsuranceRelation(category.getPcInsuranceIds(), category.getShopInsuranceIds(), category.getDeptGoodsCategoryId());
        category.setUpdateBy(getLoginName());
        deptGoodsCategoryService.edit(category);
        return AjaxResult.success();
    }

    /**
     * 商品类别表
     */
    @RequiresPermissions("goods:deptcategory:list")
    @PostMapping("/list")
    @ResponseBody
    public List<DeptGoodsCategory> list(DeptGoodsCategory category) {
        Long parentId = ShiroUtils.getSysUser().getDept().getParentId();
        category.setDeptId(parentId);
        return deptGoodsCategoryService.list(category);
    }

    @GetMapping("/tree")
    @ResponseBody
    public List<Ztree> goodsDeptCategoryTree() {
        Long parentId = ShiroUtils.getSysUser().getDept().getParentId();
        return deptGoodsCategoryService.tree(parentId);
    }

    @PostMapping("/app/list")
    @ResponseBody
    public AjaxResult appList(@RequestBody DeptGoodsCategory deptGoodsCategory) {
        return AjaxResult.success(deptGoodsCategoryService.appList(deptGoodsCategory));
    }

    @PostMapping("/app/category")
    @ResponseBody
    public AjaxResult appCategory(@RequestBody AppCategoryRequest request) {
        try {

            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 删除子公司商品类别接口
     */
    @RequiresPermissions("goods:deptcategory:remove")
    @Log(title = "子公司商品类别管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove/{ids}")
    @ResponseBody
    public AjaxResult remove(@PathVariable("ids") String ids) {
        try {
            return toAjax(deptGoodsCategoryService.delete(ids));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }
}
