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.QueryWrapper;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.WaresConstans;
import com.hzs.common.core.constant.msg.ProductMsgConstants;
import com.hzs.common.core.enums.ELanguages;
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.utils.TransactionUtils;
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.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.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.*;

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

/**
 * @Description: 商品分类列表
 * @Author: yuhui
 * @Time: 2022/9/5 10:57
 * @Classname: BdAreaClassifyController
 * @PackageName: com.hzs.sale.product.controller.manage
 */
@Slf4j
@RestController
@RequestMapping("/manage/area-classify")
public class BdAreaClassifyController extends BaseController {

    @Autowired
    private IBdAreaClassifyService areaClassifyService;
    @Autowired
    private IBdAreaClassifySpecialAreaService areaClassifySpecialAreaService;
    @Autowired
    private UserTokenService userTokenService;

    /**
     * 查询分类列表
     *
     * @return
     */
    @Log(module = EOperationModule.AREA_CLASSIFY_LIST, method = EOperationMethod.SELECT)
    @GetMapping("list")
    public TableDataInfo list(AreaClassifyParam areaClassifyParam) {
        startPage();
        areaClassifyParam.setPkCountry(SecurityUtils.getPkCountry());

        // 临时处理分类名称国际化
        this.handleLanguage(areaClassifyParam);

        List<AreaClassifyVo> list = areaClassifyService.selectByAreaClassifyList(areaClassifyParam);
        for (AreaClassifyVo areaClassifyVo : list) {
            QueryWrapper<BdAreaClassifySpecialArea> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("PK_AREA_CLASSIFY", areaClassifyVo.getPkId());
            List<Integer> specialValue = new ArrayList<>();
            List<BdAreaClassifySpecialArea> specialList = areaClassifySpecialAreaService.list(queryWrapper);
            for (BdAreaClassifySpecialArea cps : specialList) {
                specialValue.add(cps.getSpecialArea());
            }
            QueryWrapper<BdAreaClassify> qw = new QueryWrapper<>();
            qw.eq("PK_PARENT", areaClassifyVo.getPkId());
            int count = areaClassifyService.count(qw);
            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 (areaClassifyParam.getHierarchy() == EYesNo.YES.getIntValue()) {
//            // 一级
//            if (StringUtils.isBlank(areaClassifyParam.getClassifyImg())) {
//                return AjaxResult.error(ProductMsgConstants.WARES_AREA_CLASSIFY_IMG_REQUIRED);
//            }
//            if (areaClassifyParam.getSpecialAreaList() == null) {
//                return AjaxResult.error(ProductMsgConstants.SPECIAL_AREA_REQUIRED);
//            }
//
//        } else if (areaClassifyParam.getHierarchy() == EYesNo.NO.getIntValue()) {
//            if (areaClassifyParam.getPkParent() == null) {
//                return AjaxResult.error(ProductMsgConstants.WARES_PARENT_AREA_CLASSIFY_REQUIRED);
//            }
//        }
        if (StringUtils.isBlank(areaClassifyParam.getClassifyName())) {
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.SPECIAL_AREA_CLASSIFY_REQUIRED));
        }
        QueryWrapper<BdAreaClassify> wrapper = new QueryWrapper<>();
        wrapper.eq("CLASSIFY_NAME", areaClassifyParam.getClassifyName());
        wrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        int areaClassifyCount = areaClassifyService.count(wrapper);
        if (areaClassifyCount > 0) {
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.CLASSIFY_NAME_REPEAT));
        }
        if (areaClassifyParam.getSort() > WaresConstans.MAX_SORT) {
            // 排序值超出限制
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.SORT_VALUES_OVERLIMIT));
        }

        if (areaClassifyParam.getPkParent() == 0) {
            // 表示第一级
            areaClassifyParam.setHierarchy(0);
        } else {
            BdAreaClassify areaClassify = areaClassifyService.getById(areaClassifyParam.getPkParent());
            areaClassifyParam.setHierarchy(areaClassify.getHierarchy() + 1);
        }

        QueryWrapper<BdAreaClassify> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("SORT", areaClassifyParam.getSort());
        queryWrapper.eq("HIERARCHY", areaClassifyParam.getHierarchy());
        queryWrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        int count = areaClassifyService.count(queryWrapper);
        if (count > 0) {
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.SORT_REPEAT));
        }
        areaClassifyService.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));
        }
        QueryWrapper<BdAreaClassify> wrapper = new QueryWrapper<>();
        wrapper.eq("CLASSIFY_NAME", areaClassifyParam.getClassifyName());
        wrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        wrapper.notIn("PK_ID", areaClassifyParam.getPkId());
        int areaClassifyCount = areaClassifyService.count(wrapper);
        if (areaClassifyCount > 0) {
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.CLASSIFY_NAME_REPEAT));
        }
        if (areaClassifyParam.getSort() > WaresConstans.MAX_SORT) {
            // 排序值超出限制
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.SORT_VALUES_OVERLIMIT));
        }
        QueryWrapper<BdAreaClassify> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("SORT", areaClassifyParam.getSort());
        queryWrapper.eq("HIERARCHY", areaClassifyParam.getHierarchy());
        queryWrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        queryWrapper.notIn("PK_ID", areaClassifyParam.getPkId());
        int count = areaClassifyService.count(queryWrapper);
        if (count > 0) {
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.SORT_REPEAT));
        }
        areaClassifyService.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 = areaClassifyService.getAreaClassify(pkId);
        if (areaClassify.getHierarchy() == 0) {
            QueryWrapper<BdAreaClassify> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("PK_PARENT", pkId);
            int count = areaClassifyService.count(queryWrapper);
            if (count > 0) {
                return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.THIS_CLASSIFY_EXIST_BELOW));
            }
        }
        areaClassifyService.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());
        areaClassifyService.updateById(areaClassify);
        return AjaxResult.success();
    }

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

        List<Integer> specialAreaList = new ArrayList<>();
        QueryWrapper<BdAreaClassifySpecialArea> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PK_AREA_CLASSIFY", pkId);
        List<BdAreaClassifySpecialArea> list = areaClassifySpecialAreaService.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);

        // 临时处理分类名称国际化
        this.handleLanguage(areaClassifyParam);

        List<AreaClassifyVo> list = areaClassifyService.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());

        // 临时处理分类名称国际化
        this.handleLanguage(areaClassifyParam);

        List<AreaClassifyVo> list = areaClassifyService.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) {

        // 临时处理分类名称国际化
        this.handleLanguage(areaClassifyParam);

        List<AreaClassifyVo> list = areaClassifyService.selectByAreaClassifyList(areaClassifyParam);
        for (AreaClassifyVo areaClassifyVo : list) {
            QueryWrapper<BdAreaClassifySpecialArea> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("PK_AREA_CLASSIFY", areaClassifyVo.getPkId());
            List<Integer> specialValue = new ArrayList<>();
            List<BdAreaClassifySpecialArea> specialList = areaClassifySpecialAreaService.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());
        areaClassifyService.updateById(bdAreaClassify);
        return AjaxResult.success();
    }

    /**
     * 处理国际化
     *
     * @param areaClassifyParam
     */
    private void handleLanguage(AreaClassifyParam areaClassifyParam) {
        String languageTag = LocaleContextHolder.getLocale().toLanguageTag();
        if (StringUtils.isNotEmpty(languageTag)) {
            ELanguages language = ELanguages.getLanguagesByLocal(languageTag);
            if (null != language) {
                areaClassifyParam.setLanguageColumn(language.getColumn());
            }
        }
    }

}
