package com.ghy.web.controller.goods;

import cn.hutool.core.collection.CollectionUtil;
import com.ghy.common.annotation.Log;
import com.ghy.common.constant.UserConstants;
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.enums.BusinessType;
import com.ghy.common.utils.ShiroUtils;
import com.ghy.common.utils.StringUtils;
import com.ghy.goods.domain.CategoryInsuranceRelation;
import com.ghy.goods.domain.GoodsCategory;
import com.ghy.goods.domain.InsuranceManager;
import com.ghy.goods.service.GoodsCategoryService;
import com.ghy.goods.service.ICategoryInsuranceRelationService;
import com.ghy.goods.service.IInsuranceManagerService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

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

/**
 * @author HH 2022/3/19
 */
@Controller
@RequestMapping("/goods/category")
public class GoodsCategoryController extends BaseController {

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

    @Resource
    private GoodsCategoryService goodsCategoryService;

    @Resource
    private IInsuranceManagerService insuranceManagerService;

    @Resource
    private ICategoryInsuranceRelationService categoryInsuranceRelationService;

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


    /**
     * 新增部门
     */
    @GetMapping("/add/{parentCategoryId}")
    public String add(@PathVariable("parentCategoryId") Long parentCategoryId, ModelMap mmap) {
        mmap.put("goodsCategory", goodsCategoryService.selectById(parentCategoryId));
        mmap.put("insurances", insuranceManagerService.selectInsuranceManagerList(new InsuranceManager()));
        return PREFIX + "/add";
    }

    /**
     * 新增商品类别页面
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        mmap.put("insurances", insuranceManagerService.selectInsuranceManagerList(new InsuranceManager()));
        return PREFIX + "/add";
    }

    /**
     * 修改商品类别页面
     */
    @RequiresPermissions("goods:category:edit")
    @GetMapping("/edit/{goodsId}")
    public String edit(@PathVariable("goodsId") Long goodsId, ModelMap mmap) {
        GoodsCategory goodsCategory = goodsCategoryService.selectById(goodsId);
        mmap.put("goodsCategory", goodsCategory);
        List<InsuranceManager> list = insuranceManagerService.selectInsuranceManagerList(new InsuranceManager());
        CategoryInsuranceRelation param = new CategoryInsuranceRelation();
        param.setGoodsCategoryId(goodsCategory.getGoodsCategoryId());
        List<CategoryInsuranceRelation> relations = categoryInsuranceRelationService.selectCategoryInsuranceRelationList(param);
        if(CollectionUtil.isNotEmpty(relations)){
            Map<Long, List<CategoryInsuranceRelation>> map = relations.stream().collect(Collectors.groupingBy(CategoryInsuranceRelation::getInsuranceId));
            list.forEach(model->{
                if(map.containsKey(model.getId())){
                    model.setFlag(true);
                }
            });
        }
        mmap.put("insurances", list);
        return PREFIX + "/edit";
    }

    /**
     * 新增商品类别接口
     */
    @RequiresPermissions("goods:category:add")
    @Log(title = "商品类别管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated GoodsCategory category) {
//        if (goodsCategoryService.checkGoodsCategoryNameUnique(category)) {
//            return error("新增商品类别'" + category.getGoodsCategoryName() + "'失败，商品类别名称已存在");
//        } else if (goodsCategoryService.checkGoodsCategoryCodeUnique(category)) {
//            return error("新增商品类别'" + category.getGoodsCategoryCode() + "'失败，商品类别编码已存在");
//        }
        category.setCreateBy(getLoginName());
        return toAjax(goodsCategoryService.insertGoodsCategory(category));
    }

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

    /**
     * 修改商品类别接口
     */
    @RequiresPermissions("goods:category:edit")
    @Log(title = "商品类别管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    @Transactional
    public AjaxResult editSave(@Validated GoodsCategory category) {
        // 更新保险设置
        categoryInsuranceRelationService.updateCategoryInsuranceRelation(category.getInsuranceIds(), category.getGoodsCategoryId());
        category.setUpdateBy(getLoginName());
        return toAjax(goodsCategoryService.updateGoodsCategory(category));
    }

    /**
     * 选择部门树
     *
     * @param categoryId 类目ID
     * @param excludeId  排除ID
     */
    @GetMapping(value = {"/selectGoodsCategoryTree/{categoryId}", "/selectGoodsCategoryTree/{categoryId}/{excludeId}"})
    public String selectDeptTree(@PathVariable("categoryId") Long categoryId,
                                 @PathVariable(value = "excludeId", required = false) String excludeId, ModelMap mmap) {
        mmap.put("goodsCategory", goodsCategoryService.selectById(categoryId));
        mmap.put("excludeId", excludeId);
        return PREFIX + "/tree";
    }

    /**
     * 商品类目树
     */
    @GetMapping("/treeData")
    @ResponseBody
    public List<Ztree> treeData() {
        return goodsCategoryService.selectCategoryTree(new GoodsCategory());
    }

    @GetMapping("/tree")
    @ResponseBody
    public List<Ztree> tree(Integer type) {
        Long deptId = ShiroUtils.getSysUser().getDept().getParentId();
        return goodsCategoryService.tree(deptId, type);
    }

    /**
     * 加载部门列表树（排除下级）
     */
    @GetMapping("/treeData/{excludeId}")
    @ResponseBody
    public List<Ztree> treeDataExcludeChild(@PathVariable(value = "excludeId", required = false) Long excludeId) {
        return goodsCategoryService.selectCategoryTree(new GoodsCategory());
    }

    /**
     * 选择服务类目树
     */
    @GetMapping("/selectServiceCategoryTree")
    public String selectServiceCategoryTree(ModelMap mmap) {
        return PREFIX + "/serviceTree";
    }

    /**
     * 获取服务类目树数据
     */
    @GetMapping("/serviceTreeData")
    @ResponseBody
    public List<Ztree> serviceTreeData() {
        GoodsCategory category = new GoodsCategory();
        category.setType(1); // 1表示服务类
        return goodsCategoryService.selectCategoryTree(category);
    }

    /**
     * 商品类别表
     */
//    @RequiresPermissions("goods:goods:list")
    @PostMapping("/list")
    @ResponseBody
    public List<GoodsCategory> list(GoodsCategory category) {
        return goodsCategoryService.selectGoodsCategoryList(category);
    }

    /**
     * 校验商品类别名称
     */
    @PostMapping("/checkGoodsNameUnique")
    @ResponseBody
    public String checkGoodsNameUnique(GoodsCategory category) {
        return goodsCategoryService.checkGoodsCategoryNameUnique(category) ?
                UserConstants.GOODS_CATEGORY_NAME_NOT_UNIQUE : UserConstants.GOODS_CATEGORY_NAME_UNIQUE;
    }

    /**
     * 校验商品类别编码
     */
    @PostMapping("/checkGoodsCodeUnique")
    @ResponseBody
    public String checkGoodsCodeUnique(GoodsCategory category) {
        return goodsCategoryService.checkGoodsCategoryCodeUnique(category) ?
                UserConstants.GOODS_CATEGORY_CODE_NOT_UNIQUE : UserConstants.GOODS_CATEGORY_CODE_UNIQUE;
    }
}
