package com.hzs.sale.product.controller.manage;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hzs.common.core.annotation.AccessPermissions;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.WaresConstants;
import com.hzs.common.core.constant.msg.ProductMsgConstants;
import com.hzs.common.core.enums.EOperationBusiness;
import com.hzs.common.core.enums.EOperationMethod;
import com.hzs.common.core.enums.EOperationModule;
import com.hzs.common.core.enums.EYesNo;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.core.web.page.TableDataInfo;
import com.hzs.common.domain.sale.product.BdAreaClassify;
import com.hzs.common.domain.sale.product.BdAreaClassifySpecialArea;
import com.hzs.common.security.service.UserTokenService;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.util.TransactionUtils;
import com.hzs.sale.product.controller.manage.params.AreaClassifyParam;
import com.hzs.sale.product.service.IBdAreaClassifyService;
import com.hzs.sale.product.service.IBdAreaClassifySpecialAreaService;
import com.hzs.sale.product.vo.AreaClassifyVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 商品分类列表
 */
@Slf4j
@RestController
@RequestMapping("/manage/area-classify")
public class BdAreaClassifyController extends BaseController {

    @Autowired
    private IBdAreaClassifyService iBdAreaClassifyService;
    @Autowired
    private IBdAreaClassifySpecialAreaService iBdAreaClassifySpecialAreaService;
    @Autowired
    private UserTokenService userTokenService;

    /**
     * 查询分类列表
     *
     * @return
     */
    @AccessPermissions("GoodsClassify")
    @Log(module = EOperationModule.AREA_CLASSIFY, business = EOperationBusiness.AREA_CLASSIFY, method = EOperationMethod.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(AreaClassifyParam areaClassifyParam) {
        startPage();
        areaClassifyParam.setPkCountry(SecurityUtils.getPkCountry());
        List<AreaClassifyVo> list = iBdAreaClassifyService.selectByAreaClassifyList(areaClassifyParam);
        for (AreaClassifyVo areaClassifyVo : list) {
            LambdaQueryWrapper<BdAreaClassifySpecialArea> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BdAreaClassifySpecialArea::getPkAreaClassify, areaClassifyVo.getPkId());
            List<Integer> specialValue = new ArrayList<>();
            List<BdAreaClassifySpecialArea> specialList = iBdAreaClassifySpecialAreaService.list(queryWrapper);
            for (BdAreaClassifySpecialArea cps : specialList) {
                specialValue.add(cps.getSpecialArea());
            }
            LambdaQueryWrapper<BdAreaClassify> qw = new LambdaQueryWrapper<>();
            qw.eq(BdAreaClassify::getPkParent, areaClassifyVo.getPkId());
            int count = iBdAreaClassifyService.count(qw);
            if (areaClassifyVo.getIsRecommend() == null) {
                areaClassifyVo.setIsRecommend(EYesNo.NO.getIntValue());
            }
            areaClassifyVo.setLevelCount(count);
            areaClassifyVo.setSpecialArea(specialValue);
        }
        return getDataTable(list);
    }

    /**
     * 新增商品分类信息
     *
     * @return
     */
    @Log(module = EOperationModule.AREA_CLASSIFY_SAVE, method = EOperationMethod.INSERT)
    @PostMapping("/save")
    public AjaxResult save(@RequestBody AreaClassifyParam areaClassifyParam) {
        if (StringUtils.isBlank(areaClassifyParam.getClassifyName())) {
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.SPECIAL_AREA_CLASSIFY_REQUIRED));
        }
        LambdaQueryWrapper<BdAreaClassify> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BdAreaClassify::getClassifyName, areaClassifyParam.getClassifyName());
        wrapper.eq(BdAreaClassify::getPkCountry, SecurityUtils.getPkCountry());
        int areaClassifyCount = iBdAreaClassifyService.count(wrapper);
        if (areaClassifyCount > 0) {
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.CLASSIFY_NAME_REPEAT));
        }
        if (areaClassifyParam.getSort() > WaresConstants.MAX_SORT) {
            // 排序值超出限制
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.SORT_VALUES_OVERLIMIT));
        }

        if (areaClassifyParam.getPkParent() == 0) {
            // 表示第一级
            areaClassifyParam.setHierarchy(0);
        } else {
            BdAreaClassify areaClassify = iBdAreaClassifyService.getById(areaClassifyParam.getPkParent());
            areaClassifyParam.setHierarchy(areaClassify.getHierarchy() + 1);
        }
        LambdaQueryWrapper<BdAreaClassify> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BdAreaClassify::getSort, areaClassifyParam.getSort());
        queryWrapper.eq(BdAreaClassify::getHierarchy, areaClassifyParam.getHierarchy());
        queryWrapper.eq(BdAreaClassify::getPkCountry, SecurityUtils.getPkCountry());
        int count = iBdAreaClassifyService.count(queryWrapper);
        if (count > 0) {
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.SORT_REPEAT));
        }
        iBdAreaClassifyService.saveAreaClassify(areaClassifyParam, userTokenService.getLoginUser());
        return AjaxResult.success();
    }

    /**
     * 修改商品分类信息
     *
     * @param areaClassifyParam
     * @return
     */
    @Log(module = EOperationModule.AREA_CLASSIFY_UPDATE, method = EOperationMethod.UPDATE)
    @PostMapping("/update")
    public AjaxResult update(@RequestBody AreaClassifyParam areaClassifyParam) {
        if (areaClassifyParam.getHierarchy() == EYesNo.YES.getIntValue()) {
            // 一级
            if (StringUtils.isBlank(areaClassifyParam.getClassifyImg())) {
                return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.WARES_AREA_CLASSIFY_IMG_REQUIRED));
            }
            if (areaClassifyParam.getSpecialAreaList() == null) {
                return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.SPECIAL_AREA_REQUIRED));
            }

        } else if (areaClassifyParam.getHierarchy() == EYesNo.NO.getIntValue()) {
            if (areaClassifyParam.getPkParent() == null) {
                return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.WARES_PARENT_AREA_CLASSIFY_REQUIRED));
            }
        }
        if (StringUtils.isBlank(areaClassifyParam.getClassifyName())) {
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.SPECIAL_AREA_CLASSIFY_REQUIRED));
        }
        LambdaQueryWrapper<BdAreaClassify> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BdAreaClassify::getClassifyName, areaClassifyParam.getClassifyName());
        wrapper.eq(BdAreaClassify::getPkCountry, SecurityUtils.getPkCountry());
        wrapper.notIn(BdAreaClassify::getPkId, areaClassifyParam.getPkId());
        int areaClassifyCount = iBdAreaClassifyService.count(wrapper);
        if (areaClassifyCount > 0) {
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.CLASSIFY_NAME_REPEAT));
        }
        if (areaClassifyParam.getSort() > WaresConstants.MAX_SORT) {
            // 排序值超出限制
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.SORT_VALUES_OVERLIMIT));
        }
        LambdaQueryWrapper<BdAreaClassify> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BdAreaClassify::getSort, areaClassifyParam.getSort());
        queryWrapper.eq(BdAreaClassify::getHierarchy, areaClassifyParam.getHierarchy());
        queryWrapper.eq(BdAreaClassify::getPkCountry, SecurityUtils.getPkCountry());
        queryWrapper.notIn(BdAreaClassify::getPkId, areaClassifyParam.getPkId());
        int count = iBdAreaClassifyService.count(queryWrapper);
        if (count > 0) {
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.SORT_REPEAT));
        }
        iBdAreaClassifyService.updateAreaClassify(areaClassifyParam, userTokenService.getLoginUser());
        return AjaxResult.success();
    }

    /**
     * 根据分类id 删除
     *
     * @return
     */
    @Log(module = EOperationModule.AREA_CLASSIFY_DELETE, method = EOperationMethod.DELETE)
    @DeleteMapping("/{pkId}")
    public AjaxResult remove(@PathVariable Integer pkId) {
        BdAreaClassify areaClassify = iBdAreaClassifyService.getAreaClassify(pkId);
        if (areaClassify.getHierarchy() == 0) {
            LambdaQueryWrapper<BdAreaClassify> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BdAreaClassify::getPkParent, pkId);
            int count = iBdAreaClassifyService.count(queryWrapper);
            if (count > 0) {
                return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.THIS_CLASSIFY_EXIST_BELOW));
            }
        }
        iBdAreaClassifyService.deleteAreaClassify(pkId);
        return AjaxResult.success();
    }

    /**
     * 修改分类状态
     *
     * @param pkId   商品分类id
     * @param enable 启用状态 0 启用 1 禁用
     * @return
     */
    @Log(module = EOperationModule.AREA_CLASSIFY_UPDATE_ENABLE, method = EOperationMethod.UPDATE)
    @PostMapping("/updateEnable/{pkId}/{enable}")
    public AjaxResult updateEnable(@PathVariable Integer pkId, @PathVariable Integer enable) {
        BdAreaClassify areaClassify = new BdAreaClassify();
        areaClassify.setEnableState(enable);
        areaClassify.setPkId(pkId);
        areaClassify.setPkModified(SecurityUtils.getUserId());
        areaClassify.setModifiedTime(new Date());
        iBdAreaClassifyService.updateById(areaClassify);
        return AjaxResult.success();
    }

    /**
     * 查询详情
     */
    @GetMapping("/detail")
    public AjaxResult detail(Integer pkId) {
        BdAreaClassify areaClassify = iBdAreaClassifyService.getById(pkId);
        AreaClassifyParam areaClassifyParam = BeanUtil.copyProperties(areaClassify, AreaClassifyParam.class);

        List<Integer> specialAreaList = new ArrayList<>();
        LambdaQueryWrapper<BdAreaClassifySpecialArea> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BdAreaClassifySpecialArea::getPkAreaClassify, pkId);
        List<BdAreaClassifySpecialArea> list = iBdAreaClassifySpecialAreaService.list(queryWrapper);
        for (BdAreaClassifySpecialArea acs : list) {
            specialAreaList.add(acs.getSpecialArea());
        }
        areaClassifyParam.setSpecialAreaList(specialAreaList);
        return AjaxResult.success(areaClassifyParam);
    }

    /**
     * 查询第一层分类
     */
    @GetMapping("/get-first-classify")
    public AjaxResult getFirstClassify(AreaClassifyParam areaClassifyParam) {
        areaClassifyParam.setHierarchy(0);
        List<AreaClassifyVo> list = iBdAreaClassifyService.selectByAreaClassifyList(areaClassifyParam);
        return AjaxResult.success(list);
    }

    /**
     * 查询
     *
     * @param areaClassifyParam
     * @return
     */
    @GetMapping("/get-hierarchy-list")
    public AjaxResult getLevelList(AreaClassifyParam areaClassifyParam) {
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setDeep(4);
        areaClassifyParam.setPkCountry(SecurityUtils.getPkCountry());
        List<AreaClassifyVo> list = iBdAreaClassifyService.selectByAreaClassifyList(areaClassifyParam);
        List<Tree<String>> build = TreeUtil.build(list, "0", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getPkId().toString());
                    tree.setParentId(treeNode.getPkParent().toString());
                    tree.setName(treeNode.getClassifyName());
                    tree.put("value", treeNode.getPkId());
                    tree.put("label", treeNode.getClassifyName());
                    tree.put("enableState", treeNode.getEnableState());
                    if (treeNode.getEnableState() == EYesNo.YES.getIntValue()) {
                        tree.put("disabled", false);
                    } else {
                        tree.put("disabled", true);
                    }

                });
        return AjaxResult.success(build);
    }

    /**
     * 查询分类列表
     *
     * @return
     */
    @Log(module = EOperationModule.AREA_CLASSIFY_LIST, method = EOperationMethod.SELECT)
    @GetMapping("/find-all")
    public AjaxResult findAll(AreaClassifyParam areaClassifyParam) {

        List<AreaClassifyVo> list = iBdAreaClassifyService.selectByAreaClassifyList(areaClassifyParam);
        for (AreaClassifyVo areaClassifyVo : list) {
            LambdaQueryWrapper<BdAreaClassifySpecialArea> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BdAreaClassifySpecialArea::getPkAreaClassify, areaClassifyVo.getPkId());
            List<Integer> specialValue = new ArrayList<>();
            List<BdAreaClassifySpecialArea> specialList = iBdAreaClassifySpecialAreaService.list(queryWrapper);
            for (BdAreaClassifySpecialArea cps : specialList) {
                specialValue.add(cps.getSpecialArea());
            }
            areaClassifyVo.setSpecialArea(specialValue);
        }
        return AjaxResult.success(list);
    }

    /**
     * 推荐分类
     *
     * @return
     */
    @PostMapping("/classify-recommend")
    public AjaxResult classifyRecommend(@RequestBody AreaClassifyParam areaClassifyParam) {
        BdAreaClassify bdAreaClassify = new BdAreaClassify();
        bdAreaClassify.setPkId(areaClassifyParam.getPkId());
        bdAreaClassify.setIsRecommend(areaClassifyParam.getIsRecommend());
        iBdAreaClassifyService.updateById(bdAreaClassify);
        return AjaxResult.success();
    }

}
