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

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzs.common.core.annotation.AccessPermissions;
import com.hzs.common.core.annotation.Log;
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.utils.StringUtils;
import com.hzs.common.core.utils.poi.ExcelUtil;
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.classify.BdSpecs;
import com.hzs.common.domain.sale.classify.BdSpecsType;
import com.hzs.common.domain.sale.product.BdProductSpecs;
import com.hzs.common.domain.sale.wares.BdWaresSpecs;
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.SpecsTypeParam;
import com.hzs.sale.product.service.IBdProductSpecsService;
import com.hzs.sale.product.service.IBdSpecsService;
import com.hzs.sale.product.service.IBdSpecsTypeService;
import com.hzs.sale.product.vo.SpecsTypeVo;
import com.hzs.sale.wares.service.IBdWaresSpecsService;
import com.hzs.system.sys.dto.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * @Description: 规格分类controller
 * @Author: yuhui
 * @Time: 2022/8/29 10:59
 * @Classname: BdSpecsTypeController
 * @PackageName: com.hzs.sale.product.controller.manage
 */
@Slf4j
@RestController
@RequestMapping("/manage/specsType")
public class BdSpecsTypeController extends BaseController {

    @Autowired
    private IBdProductSpecsService productSpecsService;
    @Autowired
    private IBdSpecsTypeService specsTypeService;
    @Autowired
    private IBdSpecsService specsService;
    @Autowired
    private UserTokenService userTokenService;
    @Autowired
    private IBdWaresSpecsService waresSpecsService;

    /**
     * 查询规格分类
     *
     * @param specsType
     * @return
     */
    @AccessPermissions("ggpz")
    @Log(module = EOperationModule.SPECIFICATIONS_CONFIG, business = EOperationBusiness.SPECIFICATIONS_CONFIG, method = EOperationMethod.SELECT)
    @GetMapping("list")
    public TableDataInfo list(BdSpecsType specsType) {

        startPage();
        specsType.setPkCountry(SecurityUtils.getPkCountry());
        List<SpecsTypeVo> list = specsTypeService.selectSpecsTypeList(specsType);
        for (SpecsTypeVo specsTypeVo : list) {
            QueryWrapper<BdSpecs> query = new QueryWrapper<>();
            query.eq("PK_SPECS_TYPE", specsTypeVo.getPkId());
            specsTypeVo.setSpecsList(specsService.list(query));
        }

        return getDataTable(list);
    }

    /**
     * 新增规格分类
     *
     * @param specsTypeParam
     * @return
     */
    @PostMapping("save")
    @Log(module = EOperationModule.SPECS_TYPE_SAVE, method = EOperationMethod.INSERT)
    public AjaxResult save(@RequestBody SpecsTypeParam specsTypeParam) {
        // 类型名称不能为空
        if (StringUtils.isBlank(specsTypeParam.getTypeName())) {
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.PRODUCT_SPECS_TYPE_NAME_REQUIRED));
        }
        if (specsTypeParam.getPkClassify() == null) {
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.PRODUCT_SPECS_TYPE_PKCLASSIFY_REQUIRED));
        }
        if (specsTypeParam.getSpecsList().size() == 0) {
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.PRODUCT_SPECS_TYPE_SPECS_REQUIRED));
        }
        QueryWrapper<BdSpecsType> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("SORT", specsTypeParam.getSort());
        queryWrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        int count = specsTypeService.count(queryWrapper);
        if (count > 0) {
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.SORT_REPEAT));
        }

        // 规格分类已被占用
        QueryWrapper<BdSpecsType> nameWrapper = new QueryWrapper<>();
        nameWrapper.eq("PK_CLASSIFY", specsTypeParam.getPkClassify());
        nameWrapper.eq("TYPE_NAME", specsTypeParam.getTypeName());
        nameWrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        int nameCount = specsTypeService.count(nameWrapper);
        if (nameCount > 0) {
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.SPECS_TYPE_IS_USE));
        }
        specsTypeService.saveSpecsType(specsTypeParam, userTokenService.getLoginUser());
        return AjaxResult.success();
    }

    /**
     * 修改规格分类
     *
     * @param specsTypeParam
     * @return
     */
    @PostMapping("update")
    @Log(module = EOperationModule.SPECS_TYPE_UPDATE, method = EOperationMethod.UPDATE)
    public AjaxResult update(@RequestBody SpecsTypeParam specsTypeParam) {
        // 类型名称不能为空
        if (StringUtils.isBlank(specsTypeParam.getTypeName())) {
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.PRODUCT_SPECS_TYPE_NAME_REQUIRED));
        }
        if (specsTypeParam.getPkClassify() == null) {
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.PRODUCT_SPECS_TYPE_PKCLASSIFY_REQUIRED));
        }
        if (specsTypeParam.getSpecsList().size() == 0) {
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.PRODUCT_SPECS_TYPE_SPECS_REQUIRED));
        }
        QueryWrapper<BdSpecsType> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("SORT", specsTypeParam.getSort());
        queryWrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        queryWrapper.notIn("PK_ID", specsTypeParam.getPkId());
        int count = specsTypeService.count(queryWrapper);
        if (count > 0) {
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.SORT_REPEAT));
        }
        specsTypeService.updateSpecsType(specsTypeParam, userTokenService.getLoginUser());
        return AjaxResult.success();
    }

    /**
     * 删除
     *
     * @param pkId
     * @return
     */
    @DeleteMapping("/{pkId}")
    @Log(module = EOperationModule.SPECS_TYPE_DELETE, method = EOperationMethod.DELETE)
    public AjaxResult delete(@PathVariable Integer pkId) {
        LoginUser loginUser = userTokenService.getLoginUser();

        QueryWrapper<BdSpecs> qy = new QueryWrapper<>();
        qy.eq("PK_SPECS_TYPE", pkId);
        int count = specsService.count(qy);
        if (count > 0) {
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.SPECS_TYPE_IS_USE));
        }
        QueryWrapper<BdProductSpecs> qw = new QueryWrapper<>();
        qw.eq("PK_SPECS_TYPE", pkId);
        int specsTypeCount = productSpecsService.count(qw);
        if (specsTypeCount > 0) {
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.SPECS_TYPE_IS_USE));
        }
        // 查询商品占用
        QueryWrapper<BdWaresSpecs> qwe = new QueryWrapper<>();
        qwe.eq("PK_SPECS_TYPE", pkId);
        int spCount = waresSpecsService.count(qwe);
        if (spCount > 0) {
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.SPECS_TYPE_IS_USE));
        }
        specsTypeService.deleteBySpecsTypeId(pkId, loginUser);
        return AjaxResult.success();
    }

    /**
     * 根据id 查询详情
     *
     * @param specsTypeId
     * @return
     */
    @GetMapping("detail")
    public AjaxResult detail(Long specsTypeId) {
        BdSpecsType specsType = specsTypeService.getById(specsTypeId);
        SpecsTypeVo specsTypeVo = BeanUtil.copyProperties(specsType, SpecsTypeVo.class);
        QueryWrapper<BdSpecs> query = new QueryWrapper<>();
        query.eq("PK_SPECS_TYPE", specsType.getPkId());
        specsTypeVo.setSpecsList(specsService.list(query));
        return AjaxResult.success(specsTypeVo);
    }

    /**
     * 修改规格分类状态
     *
     * @return
     */
    @PostMapping("/updateEnable/{pkId}/{enable}")
    public AjaxResult updateEnable(@PathVariable Integer pkId, @PathVariable Integer enable) {
        BdSpecsType specsType = new BdSpecsType();
        specsType.setEnableState(enable);
        specsType.setPkId(pkId);
        specsType.setPkModified(SecurityUtils.getUserId());
        specsType.setModifiedTime(new Date());
        return toAjax(specsTypeService.updateById(specsType));
    }

    /**
     * 查询
     *
     * @param specsType
     * @return
     */
    @GetMapping("find-all")
    @Log(module = EOperationModule.SPECS_TYPE_LIST, method = EOperationMethod.SELECT)
    public AjaxResult findAll(BdSpecsType specsType) {
        QueryWrapper<BdSpecsType> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("PK_ID");
        queryWrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        List<BdSpecsType> list = specsTypeService.list(queryWrapper);
        return AjaxResult.success(list);
    }

    /**
     * 产品分类导出
     *
     * @param response
     * @param specsType
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response,
                       BdSpecsType specsType) {
        QueryWrapper<BdSpecsType> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(specsType.getTypeName())) {
            queryWrapper.eq("TYPE_NAME", specsType.getTypeName());
        }
        List<BdSpecsType> list = specsTypeService.list(queryWrapper);
        ExcelUtil<BdSpecsType> util = new ExcelUtil<>(BdSpecsType.class);
        util.exportExcel(response, list, "产品分类导出");
    }

}
