郑永安
2023-06-19 59e91a4e9ddaf23cebb12993c774aa899ab22d16
src/main/java/com/gk/firework/Controller/ProductController.java
对比新文件
@@ -0,0 +1,879 @@
package com.gk.firework.Controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gk.firework.Controller.Base.BaseController;
import com.gk.firework.Domain.*;
import com.gk.firework.Domain.Enum.Element;
import com.gk.firework.Domain.Enum.EnterpriseSafetySupervision;
import com.gk.firework.Domain.Enum.ErrorCode;
import com.gk.firework.Domain.Utils.*;
import com.gk.firework.Domain.Vo.DirectionDetail;
import com.gk.firework.Domain.Vo.FireworkDeal;
import com.gk.firework.Domain.Vo.ProductThresholdVo;
import com.gk.firework.Domain.Vo.ProductVo;
import com.gk.firework.Service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
/**
 * @author jingjy
 */
@Api(tags = "产品信息接口")
@RequestMapping("/product")
@RestController
public class ProductController extends BaseController {
    @Value("${productPath}")
    private String productPath; //配置文件配置的物理保存地址
    private ProductService productService;
    private StockService stockService;
    private UserService userService;
    private EnterpriseService enterpriseService;
    private ProductThresholdService productThresholdService;
    private ProductCategoryService productCategoryService;
    private ProductPriceService productPriceService;
    private ExcelExportService excelExportService;
    private static final Byte ADD_OPTION = 1;
    private static final Byte EDIT_OPTION = 2;
    private static final Byte DEL_OPTION = 3;
    @Autowired
    public ProductController(ProductService productService,StockService stockService, UserService userService,
                             EnterpriseService enterpriseService,ProductThresholdService productThresholdService,
                             ProductCategoryService productCategoryService,ProductPriceService productPriceService,
                             ExcelExportService excelExportService ) {
        this.productService = productService;
        this.stockService = stockService;
        this.userService = userService;
        this.enterpriseService = enterpriseService;
        this.productThresholdService = productThresholdService;
        this.productCategoryService = productCategoryService;
        this.productPriceService = productPriceService;
        this.excelExportService = excelExportService;
    }
    /**
     * 查询全部的产品信息
     *
     * @param name          产品名;
     * @param directionCode :流向码(十位);
     * @param manufacturer  :生产厂家
     * @return List<ProductInfo> 产品信息的集合
     */
    @GetMapping("/info")
    public Msg getProductInfo(@RequestParam(value = "name", required = false) String name,
                              @RequestParam(value = "directionCode", required = false) String directionCode,
                              @RequestParam(value = "manufacturer", required = false) String manufacturer,
                              @RequestParam(value = "type", required = false) String type,
                              @RequestParam(value = "secondaryType", required = false) String secondaryType,
                              @RequestParam(value = "isOld", required = false) String isOld,
                              @RequestParam(defaultValue = "0") Integer pageIndex,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              String sort, String order) {
        Msg msg = new Msg(true);
        PageInfo pageInfo = new PageInfo(pageIndex, pageSize,sort,order);
        Map<String, Object> condition = new HashMap<>(4);
        if (StringUtils.isNotBlank(name)) {
            condition.put("name", name);
        }
        if (StringUtils.isNotBlank(directionCode)) {
            condition.put("directionCode", directionCode);
        }
        if (StringUtils.isNotBlank(manufacturer)) {
            condition.put("manufacturer", manufacturer);
        }
        if (StringUtils.isNotBlank(type)) {
            condition.put("type", type);
        }
        if (StringUtils.isNotBlank(secondaryType)) {
            condition.put("secondaryType", secondaryType);
        }
        if (StringUtils.isNotBlank(isOld)) {
            condition.put("isOld", isOld);
        }
        UserInfo userInfo = userService.getById(getUser().getId());
        if (userInfo.getCompanyid() != null){
            Enterprise enterprise = enterpriseService.getById(userInfo.getCompanyid());
            if (enterprise.getSafetysupervision().equals(EnterpriseSafetySupervision.PRODUCE.getMsg())){
                condition.put("manufacturer", enterprise.getEnterprisename());
            }else {
                condition.put("companynumber", enterprise.getEnterprisenumber());
            }
        }
        pageInfo.setCondition(condition);
        productService.selectDataGrid(pageInfo);
        msg.setResult(pageInfo);
        return msg;
    }
    /**
     * 查询全部的产品信息编码
     *
     * @return List<String> 产品编码的集合
     */
    @GetMapping("/codes")
    public Msg getProductCodes(){
        List<String>list = productService.getAllProductCodes();
        return success(list);
    }
    /**
     * 查询全部的产品信息
     *
     * @param name          产品名;
     * @param directionCode :流向码(十位);
     * @param manufacturer  :生产厂家
     * @return List<ProductInfo> 产品信息的集合
     */
    @GetMapping("/exportInfo")
    public Msg exportProduct(@RequestParam(value = "name", required = false) String name,
                              @RequestParam(value = "directionCode", required = false) String directionCode,
                              @RequestParam(value = "manufacturer", required = false) String manufacturer,
                              @RequestParam(value = "type", required = false) String type,
                              @RequestParam(value = "secondaryType", required = false) String secondaryType) {
        Msg msg = new Msg(true);
        Map<String, Object> condition = new HashMap<>(4);
        if (StringUtils.isNotBlank(name)) {
            condition.put("name", name);
        }
        if (StringUtils.isNotBlank(directionCode)) {
            condition.put("directionCode", directionCode);
        }
        if (StringUtils.isNotBlank(manufacturer)) {
            condition.put("manufacturer", manufacturer);
        }
        if (StringUtils.isNotBlank(type)) {
            condition.put("type", type);
        }
        if (StringUtils.isNotBlank(secondaryType)) {
            condition.put("secondaryType", secondaryType);
        }
        UserInfo userInfo = userService.getById(getUser().getId());
        if (userInfo.getCompanyid() != null){
            Enterprise enterprise = enterpriseService.getById(userInfo.getCompanyid());
            if (enterprise.getSafetysupervision().equals(EnterpriseSafetySupervision.PRODUCE.getMsg())){
                condition.put("manufacturer", enterprise.getEnterprisename());
            }else {
                condition.put("companynumber", enterprise.getEnterprisenumber());
            }
        }
        List<ProductInfo> productInfos = productService.selectProductInfo(condition);
        msg.setResult(productInfos);
        return msg;
    }
    @PostMapping("/updatePrice")
    public Msg updatePrice( @RequestBody ProductInfo productInfo) {
        Msg msg = new Msg(true);
        if (productInfo == null || StringUtils.isBlank(productInfo.getDirectionCode())
                || productInfo.getDirectionCode().length() < FireworkDeal.DIRECTION_ITEM){
            msg.setCode("999");
            msg.setMessage("流向码异常,修改失败");
            return msg;
        }
        ProductInfo productInfoExist = productService.selectByDirection(productInfo.getDirectionCode());
        if (productInfoExist == null) {
            msg.setCode("999");
            msg.setMessage("产品信息流向码不存在,修改失败!");
            return msg;
        }
        String companynumber = "";
        UserInfo userInfo = userService.getById(getUser().getId());
        if (userInfo.getCompanyid() != null){
            Enterprise enterprise = enterpriseService.getById(userInfo.getCompanyid());
            if (!enterprise.getSafetysupervision().equals(EnterpriseSafetySupervision.PRODUCE.getMsg())){
                companynumber = enterprise.getEnterprisenumber();
            }
        }
        if (StringUtils.isBlank(companynumber)){
            msg.setCode("999");
            msg.setMessage("非经营企业无法修改价格!");
            return msg;
        }
        ProductPriceInfo productPriceInfo = productPriceService.selectByCode(companynumber,productInfo.getDirectionCode());
        if (productPriceInfo != null){
            productPriceInfo.setPrice(productInfo.getSalePrice());
            productPriceInfo.setUpdated(new Date());
            productPriceInfo.setUpdator(userInfo.getUsername());
            productPriceService.updateById(productPriceInfo);
        }else {
            ProductPriceInfo productPrice = new ProductPriceInfo();
            productPrice.setCompanynumber(companynumber);
            productPrice.setItemcode(productInfo.getDirectionCode());
            productPrice.setPrice(productInfo.getSalePrice());
            productPrice.setUpdated(new Date());
            productPrice.setUpdator(userInfo.getUsername());
            productPriceService.save(productPrice);
        }
        return msg;
    }
    @PostMapping("/importEditPrice")
    @ApiOperation(value = "导入修改价格",response = Msg.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file",value = "文件",required = true),
    })
    public Msg addSelfCheckList(MultipartFile file){
        Msg msg = new Msg();
        msg.setCode("200");
        msg.setMessage("success");
        String filesave ="";
        try {
            SimpleDateFormat sdf = new SimpleDateFormat( "yyyyMMddHHmmssSSS" );
            if (file == null)
            {
                msg.setCode("404");
                msg.setMessage("未找到上传文件");
                return msg;
            }
            long size = file.getSize();
            if(0 == size)
            {
                msg.setCode("404");
                msg.setMessage("上传文件大小为空");
                return msg;
            }
            if(!FileOptUtils.isDirExists(productPath)){
                msg.setCode("500");
                msg.setMessage("发生错误或不为目录");
                return msg;
            }
            String companynumber = "";
            UserInfo userInfo = userService.getById(getUser().getId());
            if (userInfo.getCompanyid() != null){
                Enterprise enterprise = enterpriseService.getById(userInfo.getCompanyid());
                if (!enterprise.getSafetysupervision().equals(EnterpriseSafetySupervision.PRODUCE.getMsg())){
                    companynumber = enterprise.getEnterprisenumber();
                }
            }
            if (StringUtils.isBlank(companynumber)){
                msg.setCode("999");
                msg.setMessage("非经营企业无法修改价格!");
                return msg;
            }
            filesave = productPath + getUser().getUsername() + "_" + sdf.format(new Date()) +".xlsx";
            file.transferTo(new File(filesave));
            InputStream in = new FileInputStream(filesave);
            String name = file.getOriginalFilename();
            Boolean isExcel2007 = name.substring(name.lastIndexOf(".") + 1).endsWith("xlsx")? true:false;
            BooleanReason blret = excelExportService.imporEditPriceExcel(in,companynumber,getUser().getUsername(),isExcel2007);
            if(blret.getValue().equals(false))
            {
                msg.setCode("500");
                msg.setMessage(blret.getResultmsg());
                return msg;
            }
        } catch (Exception e) {
            e.printStackTrace();
            msg.setCode("500");
            msg.setMessage("导入发生错误");
            return msg;
        }
        return msg;
    }
    @PostMapping("/add")
    public Msg addProduct(@Validated @RequestBody ProductInfo productInfo, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            StringBuilder stringBuilder = new StringBuilder();
            for (String s : bindingResult.getFieldErrors().stream()
                    .map(FieldError::getDefaultMessage).collect(Collectors.toList())) {
                stringBuilder.append(s).append(",");
            }
            return new Msg(ErrorCode.ERROR_10002,stringBuilder.toString());
        }
        if (StringUtils.isBlank(productInfo.getDirectionCode()) || productInfo.getDirectionCode().length() != 10){
            return new Msg(ErrorCode.ERROR_10004,"流向码格式错误,新增失败!");
        }
        List<ProductInfo> productInfosExist = productService.selectByProduct(productInfo);
        if (productInfosExist != null && productInfosExist.size() != 0) {
            return new Msg(ErrorCode.ERROR_50003,"新增产品信息流向码已存在,无法添加!");
        }
        Enterprise enterprise = enterpriseService.selectEnterpriseByNumber(productInfo.getManufacturer());
        if (enterprise == null || !enterprise.getSafetysupervision().equals(EnterpriseSafetySupervision.PRODUCE.getMsg())){
            return new Msg(ErrorCode.ERROR_50002,"企业信息不存在 或 该企业不为生产企业!");
        }
        Byte isOld = 1;
        productInfo.setCompanyNumber(enterprise.getEnterprisenumber());
        productInfo.setManufacturer(enterprise.getEnterprisename());
        productInfo.setCreatedDate(new Date());
        productInfo.setCreatedBy(getUser().getUsername());
        productInfo.setIsOld(isOld);
        Msg thresholdMsg = isFitThreshold(productInfo);
        if (!thresholdMsg.getCode().equals(ErrorCode.SUCCESS.getCode())){
            return thresholdMsg;
        }
        boolean i = productService.save(productInfo);
        if (!i) {
            return new Msg(ErrorCode.ERROR_40001,"新增失败,请重新新增!");
        }
        return success();
    }
    @PostMapping("/addNew")
    public Msg addNewProduct(@Validated @RequestBody ProductInfo productInfo, BindingResult bindingResult) {
        Msg msg = new Msg(true);
        if (bindingResult.hasErrors()) {
            StringBuilder stringBuilder = new StringBuilder();
            for (String s : bindingResult.getFieldErrors().stream()
                    .map(FieldError::getDefaultMessage).collect(Collectors.toList())) {
                stringBuilder.append(s);
                stringBuilder.append(",");
            }
            msg.setCode("999");
            msg.setMessage(stringBuilder.toString());
            return msg;
        }
        Enterprise enterprise = enterpriseService.selectEnterpriseByNumber(productInfo.getManufacturer());
        if (enterprise == null || !enterprise.getSafetysupervision().equals(EnterpriseSafetySupervision.PRODUCE.getMsg())){
            msg.setCode("999");
            msg.setMessage("企业信息不存在 或 该企业不为生产企业!");
            return msg;
        }
        //生成十位流向码
        String itemCode = "";
        ProductCategory productCategory = productCategoryService.selectCategoryByLevelAndName(productInfo.getLevel(),
                productInfo.getSecondaryType());
        if (productCategory == null || StringUtils.isBlank(productCategory.getBitcode())){
            msg.setCode("999");
            msg.setMessage("产品类别错误,新增失败!");
            return msg;
        }
        int explosiveContent = productInfo.getExplosiveContent().setScale(0,BigDecimal.ROUND_UP).intValue();
        String explosive = "FFF";
        if (explosiveContent <= 4095){
            explosive = String.format("%03x",explosiveContent);
        }
        String randomStr = Element.random(Element.class).getValue().toString()+Element.random(Element.class).getValue().toString()
                +Element.random(Element.class).getValue().toString()+Element.random(Element.class).getValue().toString();
        if (StringUtils.isBlank(enterprise.getTwobitcode())){
            msg.setCode("999");
            msg.setMessage("两位企业编码为空,请联系管理员添加!");
            return msg;
        }
        itemCode = productCategory.getBitcode() + explosive + enterprise.getTwobitcode() + randomStr;
        productInfo.setDirectionCode(itemCode.toUpperCase());
        List<ProductInfo> productInfosExist = productService.selectByProduct(productInfo);
        if (productInfosExist != null && productInfosExist.size() != 0) {
            msg.setCode("999");
            msg.setMessage("新增产品信息流向码已存在,无法添加!");
            return msg;
        }
        BigDecimal totalExplosive = new BigDecimal(productInfo.getSpecification()).
                multiply(productInfo.getExplosiveContent());
        Msg thresholdMsg = isFitThreshold(productInfo);
        if (!thresholdMsg.getCode().equals(ErrorCode.SUCCESS.getCode())){
            return thresholdMsg;
        }
        productInfo.setExplosiveContent(totalExplosive);
        productInfo.setCompanyNumber(enterprise.getEnterprisenumber());
        productInfo.setManufacturer(enterprise.getEnterprisename());
        productInfo.setCreatedDate(new Date());
        productInfo.setCreatedBy(getUser().getUsername());
        boolean i = productService.save(productInfo);
        if (!i) {
            msg.setCode("999");
            msg.setMessage("新增失败,请重新新增!");
            return msg;
        }
        return msg;
    }
    @PostMapping("/update")
    public Msg updateProduct( @RequestBody ProductInfo productInfo) {
        Msg msg = new Msg(true);
        if (productInfo == null || StringUtils.isBlank(productInfo.getDirectionCode())
                || productInfo.getDirectionCode().length() < FireworkDeal.DIRECTION_ITEM){
            msg.setCode("999");
            msg.setMessage("流向码异常,删除失败");
            return msg;
        }
        ProductInfo productInfoExist = productService.selectByDirection(productInfo.getDirectionCode());
        if (productInfoExist == null) {
            msg.setCode("999");
            msg.setMessage("产品信息流向码不存在,修改失败!");
            return msg;
        }
        ProductInfo productInfoNew = new ProductInfo();
        productInfoNew.setId(productInfoExist.getId());
        productInfoNew.setPurchasePrice(productInfo.getPurchasePrice());
        productInfoNew.setSalePrice(productInfo.getSalePrice());
        productInfoNew.setModifiedDate(new Date());
        productInfoNew.setModifiedBy(getUser().getUsername());
        boolean i = productService.updateById(productInfoNew);
        if (!i) {
            msg.setCode("999");
            msg.setMessage("修改失败,请重新修改!");
            return msg;
        }
        return msg;
    }
    @PostMapping("/delete")
    public Msg deleteProduct(@RequestBody ProductInfo productInfo) {
        if (productInfo == null || StringUtils.isBlank(productInfo.getDirectionCode())
                || productInfo.getDirectionCode().length() < FireworkDeal.DIRECTION_ITEM){
            return new Msg(ErrorCode.ERROR_10004,"流向码异常,删除失败");
        }
        ProductInfo productInfoExist = productService.selectByDirection(productInfo.getDirectionCode());
        if (productInfoExist == null) {
            return new Msg(ErrorCode.ERROR_50001,"产品信息流向码不存在,删除失败");
        }
        boolean flag = productService.isProductUsed(productInfoExist.getId());
        if (flag){
            return new Msg(ErrorCode.ERROR_999,"当前产品已经签订合同或已经入库,无法删除");
        }
        ProductInfo productInfoNew = new ProductInfo();
        productInfoNew.setId(productInfoExist.getId());
        productInfoNew.setModifiedDate(new Date());
        productInfoNew.setModifiedBy(getUser().getUsername());
        productInfoNew.setIsDel((byte) 1);
        boolean i = productService.updateById(productInfoNew);
        if (!i) {
            return new Msg(ErrorCode.ERROR_40001,"删除失败,请重新删除");
        }
        return success();
    }
    @GetMapping("/get")
    public Msg getProductByCode(@RequestParam(value = "directionCode") String directionCode) {
        Msg msg = new Msg(true);
        if (StringUtils.isBlank(directionCode)) {
            msg.setCode("999");
            msg.setMessage("流向码为空,无法查询相关信息!");
            return msg;
        }
        DirectionDetail directionDetail = FireworkDeal.dealDirectionCode(directionCode);
        if (directionDetail == null) {
            msg.setCode("999");
            msg.setMessage("流向码不符合规则,请重新输入!");
            return msg;
        }
        ProductInfo productInfo = new ProductInfo();
        productInfo.setDirectionCode(directionDetail.getItemCode());
        UserInfo userInfo = userService.getById(getUser().getId());
        if (userInfo.getCompanyid() != null){
            Enterprise enterprise = enterpriseService.getById(userInfo.getCompanyid());
            if (!enterprise.getSafetysupervision().equals(EnterpriseSafetySupervision.PRODUCE.getMsg())){
                productInfo.setCompanyNumber(enterprise.getEnterprisenumber());
            }
        }
        List<ProductInfo> productInfos = productService.selectByProduct(productInfo);
        if (productInfos == null || productInfos.size() == 0) {
            msg.setCode("999");
            msg.setMessage("未找到相应的产品信息!");
            return msg;
        }
        if (productInfos.size() > 1) {
            msg.setCode("999");
            msg.setMessage("错误:存在多个对应的产品信息!");
            return msg;
        }
        ProductVo productVo = BeanUtils.copy(productInfos.get(0), ProductVo.class);
        productVo.setDirectionCode(directionCode);
        productVo.setItemCode(directionDetail.getItemCode());
        productVo.setDateCode(directionDetail.getDateCode());
        productVo.setSerialNo(directionDetail.getSerialNo());
        List<ProductVo> productVos = new ArrayList<>();
        if (directionDetail.getBoxNo() != null) {
            productVo.setBoxNo(directionDetail.getBoxNo());
            FireworkDeal.getProductVos(directionCode, directionDetail, directionDetail, productVos, productVo);
        } else {
            productVos.add(productVo);
        }
        msg.setResult(productVos);
        return msg;
    }
    @GetMapping("/gets")
    public Msg getProductsByCodes(@RequestParam String directionCode,@RequestParam String endCode){
        Msg msg = new Msg(true);
        if (StringUtils.isBlank(directionCode)|| StringUtils.isBlank(endCode)) {
            msg.setCode("999");
            msg.setMessage("流向码为空,无法查询相关信息!");
            return msg;
        }
        if (directionCode.length()!= 19 || endCode.length() != 5) {
            msg.setCode("999");
            msg.setMessage("流向码不符合规则,请重新输入!");
            return msg;
        }
        /*DirectionDetail directionDetail = FireworkDeal.dealDirectionCode(directionCode);
        DirectionDetail directionDetail2 = FireworkDeal.dealDirectionCode(directionCode.substring(0,14)+endCode);*/
        List<ProductVo>productVos = new ArrayList<>();
        ProductVo productVo = productService.selectVoByDirection(directionCode);
        try {
            Integer first = Integer.parseInt(directionCode.substring(14,19));
            Integer last = Integer.parseInt(endCode);
            if (first > last){
                Integer temp = first;
                first = last;
                last = temp;
            }
            for (int i = first; i <= last; i++){
                ProductVo productVoCopy = BeanUtils.copy(productVo, ProductVo.class);
                productVoCopy.setDirectionCode(directionCode.substring(0, 14) + String.format("%05d", i));
                productVos.add(productVoCopy);
            }
        }catch (Exception e){
            msg.setCode("999");
            msg.setMessage("流向码不符合规则,请重新输入!");
            return msg;
        }
        return success(productVos);
    }
    @GetMapping("/getSingle")
    public Msg getSingleProductByCode(@RequestParam(value = "directionCode") String directionCode) {
        Msg msg = new Msg(true);
        if (StringUtils.isBlank(directionCode)) {
            msg.setCode("999");
            msg.setMessage("流向码为空,无法查询相关信息!");
            return msg;
        }
        DirectionDetail directionDetail = FireworkDeal.dealDirectionCode(directionCode);
        if (directionDetail == null) {
            msg.setCode("999");
            msg.setMessage("流向码不符合规则,请重新输入!");
            return msg;
        }
        ProductInfo productInfo = new ProductInfo();
        productInfo.setDirectionCode(directionDetail.getItemCode());
        List<ProductInfo> productInfos = productService.selectByProduct(productInfo);
        if (productInfos == null || productInfos.size() == 0) {
            msg.setCode("999");
            msg.setMessage("未找到相应的产品信息!");
            return msg;
        }
        if (productInfos.size() > 1) {
            msg.setCode("999");
            msg.setMessage("错误:存在多个对应的产品信息!");
            return msg;
        }
        ProductVo productVo = BeanUtils.copy(productInfos.get(0), ProductVo.class);
        productVo.setDirectionCode(directionCode);
        productVo.setItemCode(directionDetail.getItemCode());
        productVo.setDateCode(directionDetail.getDateCode());
        productVo.setSerialNo(directionDetail.getSerialNo());
        msg.setResult(productVo);
        return msg;
    }
    @PostMapping("/explain")
    public Msg getProductListByCodes(@RequestBody JSONObject object) {
        Msg msg = new Msg(true);
        JSONArray jsonArray = object.getJSONArray("data");
        String userName = object.getString("userName");
        List<ProductVo>productVos = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            // 遍历 jsonArray 数组,把每一个对象转成 json 对象
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String directionCode = jsonObject.getString("directionCode");
            DirectionDetail directionDetail = FireworkDeal.dealDirectionCode(directionCode);
            if (FireworkDeal.is22Characters(directionCode)){
                ProductVo productVo = productService.selectVoByDirection(directionCode);
                FireworkDeal.getProductVos(directionCode, directionDetail, directionDetail, productVos,productVo);
            }else if (FireworkDeal.is19Characters(directionCode)){
                ProductVo productVo = productService.selectVoByDirection(directionCode);
                productVos.add(productVo);
            }
        }
        UserInfo userInfo = userService.selectByUser(userName);
        if (userInfo == null){
            msg.setCode("999");
            msg.setMessage("未找到用户信息!");
            return msg;
        }
        //移除重复元素
        List<ProductVo> productVoList = ProductVo.removeListDuplicateObject(productVos);
        stockService.setProductEntryStatus(productVoList,userInfo);
        msg.setResult(productVoList);
        return msg;
    }
    @PostMapping("/removeDuplicate")
    public Msg removeDuplicateListElement(@RequestBody JSONArray array) {
        Msg msg = new Msg(true);
        List<ProductVo>productVos = new ArrayList<>();
        for (int i = 0; i < array.size(); i++) {
            // 遍历 jsonArray 数组,把每一个对象转成 json 对象
            JSONObject jsonObject = array.getJSONObject(i);
            String directionCode = jsonObject.getString("directionCode");
            DirectionDetail directionDetail = FireworkDeal.dealDirectionCode(directionCode);
            if (FireworkDeal.is22Characters(directionCode)){
                ProductVo productVo = productService.selectVoByDirection(directionCode);
                FireworkDeal.getProductVos(directionCode, directionDetail, directionDetail, productVos,productVo);
            }else if (FireworkDeal.is19Characters(directionCode)){
                ProductVo productVo = productService.selectVoByDirection(directionCode);
                productVos.add(productVo);
            }
        }
        //移除重复元素
        List<ProductVo> productVoList = ProductVo.removeListDuplicateObject(productVos);
        msg.setResult(productVoList);
        return msg;
    }
    @GetMapping(value = "getThreshold")
    public Msg getProductThreshold(){
        Msg msg = new Msg(true);
        ProductThresholdInfo productThresholdInfo = productThresholdService.getOne(new LambdaQueryWrapper<>());
        if (productThresholdInfo == null){
            msg.setCode(ErrorCode.ERROR_999.getCode());
            msg.setMessage("未找到产品阈值设置");
            return msg;
        }
        String levels = productThresholdInfo.getLevel();
        List<String>list = StringUtils.toList(levels);
        ProductThresholdVo productThresholdVo = BeanUtils.copy(productThresholdInfo, ProductThresholdVo.class);
        productThresholdVo.setLevels(list);
        msg.setResult(productThresholdVo);
        return msg;
    }
    @PostMapping(value = "setThreshold")
    public Msg setProductThreshold(@RequestBody JSONObject jsonObject){
        Msg msg = new Msg(true);
        ProductThresholdInfo productThresholdInfo = productThresholdService.getOne(new LambdaQueryWrapper<>());
        String explosiveContent = jsonObject.getString("explosiveContent") == null?"1000":jsonObject.getString("explosiveContent");
        String boxNumber = jsonObject.getString("boxNumber") == null?"999":jsonObject.getString("boxNumber");
        String levels = jsonObject.getString("levels") == null?"":jsonObject.getString("levels");
        productThresholdInfo.setExplosivecontent(new BigDecimal(explosiveContent));
        productThresholdInfo.setBoxnumber(Integer.parseInt(boxNumber));
        productThresholdInfo.setLevel(levels);
        boolean i = productThresholdService.updateById(productThresholdInfo);
        return msg;
    }
    @GetMapping("/categorise")
    public Msg getProductCategories(@RequestParam("name")String name){
        Msg msg = new Msg(true);
        List<ProductCategory> categories = productCategoryService.selectAllOrByName(name);
        msg.setResult(categories);
        return msg;
    }
    @PostMapping("/addCategory")
    public Msg addCategory(@RequestBody ProductCategory category){
        Msg msg = new Msg(true);
        Msg checkMsg = checkCategory(category,ADD_OPTION);
        if(!checkMsg.getCode().equals(ErrorCode.SUCCESS.getCode())){
            return checkMsg;
        }
        productCategoryService.save(category);
        return msg;
    }
    @PostMapping("/editCategory")
    public Msg editCategory(@RequestBody ProductCategory category){
        Msg msg = new Msg(true);
        Msg checkMsg = checkCategory(category,EDIT_OPTION);
        if(!checkMsg.getCode().equals(ErrorCode.SUCCESS.getCode())){
            return checkMsg;
        }
        productCategoryService.updateById(category);
        return msg;
    }
    @PostMapping("/delCategory")
    public Msg deleteCategory(@RequestBody ProductCategory category){
        Msg msg = new Msg(true);
        Msg checkMsg = checkCategory(category,DEL_OPTION);
        if(!checkMsg.getCode().equals(ErrorCode.SUCCESS.getCode())){
            return checkMsg;
        }
        productCategoryService.removeById(category.getId());
        return msg;
    }
    @GetMapping("/majorTree")
    public List<Tree> majorTree(){
        List<Tree> trees = new ArrayList<>();
        byte type = 1;
        List<ProductCategory> categories = productCategoryService.selectCategoryByType(type);
        for (ProductCategory category :categories) {
            Tree tree = new Tree();
            tree.setText(category != null ? category.getName() : null);
            tree.setAttributes(category != null ? category.getName() : null);
            trees.add(tree);
        }
        return trees;
    }
    @GetMapping("/secondaryTree")
    public List<Tree> secondaryTree(@RequestParam("major")String major){
        List<Tree> trees = new ArrayList<>();
        if (StringUtils.isBlank(major)){
            return trees;
        }
        List<ProductCategory> categories = productCategoryService.selectCategoryByMajorType(major);
        for (ProductCategory category :categories) {
            Tree tree = new Tree();
            tree.setText(category != null ? category.getName() : null);
            tree.setAttributes(category != null ? category.getName() : null);
            trees.add(tree);
        }
        return trees;
    }
    @GetMapping("/permitLevelTree")
    public List<Tree> permitLevelTree(@RequestParam("secondary")String secondary){
        List<Tree> trees = new ArrayList<>();
        if (StringUtils.isBlank(secondary)){
            return trees;
        }
        ProductCategory productCategory = new ProductCategory();
        productCategory.setType((byte)2);
        productCategory.setName(secondary);
        List<ProductCategory> categories = productCategoryService.selectCategoryByTypeAndName(productCategory);
        if (categories == null ){
            return trees;
        }
        for (ProductCategory category : categories){
            Tree tree = new Tree();
            tree.setText(category.getLevel());
            tree.setAttributes(category.getLevel());
            trees.add(tree);
        }
        return trees;
    }
    private Msg checkCategory(ProductCategory category,Byte option){
        Msg msg = new Msg("999","");
        if (category == null){
            msg.setMessage("操作失败:未找到对应的类别信息");
            return msg;
        }
        if (category.getName() == null){
            msg.setMessage("类别名称不能未空");
            return msg;
        }
        if (category.getType() == null){
            msg.setMessage("类型不能未空");
            return msg;
        }
        if (category.getType() == 2 && StringUtils.isBlank(category.getParentname())){
            msg.setMessage("选择小类对应大类不能未空");
            return msg;
        }
        if (option.equals(ADD_OPTION)){
            List<ProductCategory> categoryExist = productCategoryService.selectCategoryByTypeAndName(category);
            if (categoryExist != null && categoryExist.size()>0){
                msg.setMessage("当前类别名称已存在");
                return msg;
            }
        }else {
            List<ProductCategory> categoryExist = productCategoryService.selectCategoryByTypeAndName(category);
            if (categoryExist == null || categoryExist.size() == 0){
                msg.setMessage("未找到当前类别名称");
                return msg;
            }
        }
        msg.setCode("200");
        return msg;
    }
    private Msg isFitThreshold(ProductInfo productInfo) {
        Msg msg = new Msg(ErrorCode.ERROR_999.getCode(),"");
        ProductThresholdInfo productThresholdInfo = productThresholdService.getOne(new LambdaQueryWrapper<>());
        if (productInfo.getExplosiveContent().compareTo(productThresholdInfo.getExplosivecontent()) > 0){
            msg.setMessage("含药量最大为:"+productThresholdInfo.getExplosivecontent()+",超过限制,录入失败!");
            return msg;
        }
        if (productInfo.getBoxNumber() > productThresholdInfo.getBoxnumber()){
            msg.setMessage("箱数最大为:"+productThresholdInfo.getBoxnumber()+"超过限制,录入失败!");
            return msg;
        }
        if (productThresholdInfo.getLevel().contains(productInfo.getLevel())){
            msg.setMessage("当前产品级别为限制录入级别,录入失败!");
            return msg;
        }
        msg.setCode(ErrorCode.SUCCESS.getCode());
        return msg;
    }
    @PostMapping("/import/old-system")
    public Msg importDataByExcel(MultipartFile file) {
        productService.importDataByExcel(file, getUser());
        return success();
    }
}