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

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.msg.ProductMsgConstants;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.utils.DateUtils;
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.product.BdProductBas;
import com.hzs.common.domain.sale.product.BdProductBasSpecs;
import com.hzs.common.domain.sale.product.ext.BdProductBasExt;
import com.hzs.common.domain.scm.th.ThProduct;
import com.hzs.common.domain.scm.th.ThProductExtend;
import com.hzs.common.domain.scm.th.ThProductSpecs;
import com.hzs.common.security.service.UserTokenService;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.util.TransactionUtils;
import com.hzs.ground.product.param.ProductBasParams;
import com.hzs.ground.product.service.*;
import com.hzs.ground.product.vo.ProductBasVo;
import com.hzs.sale.product.IProductServiceApi;
import com.hzs.sale.product.dto.ProductParamDTO;
import com.hzs.system.sys.dto.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @BelongsProject: hzs_cloud
 * @BelongsPackage: com.hzs.scm.product.controller
 * @Author: yh
 * @CreateTime: 2023-11-27  09:29
 * @Description: TODO
 * @Version: 1.0
 */
@Slf4j
@RestController
@RequestMapping("/manage/product-bas")
public class BdProductBasController extends BaseController {

    @Autowired
    private UserTokenService userTokenService;
    @Autowired
    private IThProductExtendService productExtendService;
    @Autowired
    private IThProductService thProductService;
    @Autowired
    private IThProductSpecsService productSpecsService;
    @Autowired
    private IBdProductBasService productBasService;
    @Autowired
    private IBdProductBasSpecsService productBasSpecsService;

    @DubboReference
    IProductServiceApi productServiceApi;

    /**
     * 查询列表 (分页)
     *
     * @return
     */
    @GetMapping("/list")
    public TableDataInfo list(ProductBasParams productBasParams) {
        if (productBasParams.getStartCreateDate() != null) {
            productBasParams.setStartCreateDate(DateUtils.getStartTime(productBasParams.getStartCreateDate()));
        }
        if (productBasParams.getEndCreateDate() != null) {
            productBasParams.setEndCreateDate(DateUtils.getEndTime(productBasParams.getEndCreateDate()));
        }
        productBasParams.setSystemType(SecurityUtils.getSystemType());

        startPage();
        List<BdProductBasExt> list = productBasService.selectByList(productBasParams);
        for (BdProductBasExt productBas : list) {
            Integer pkProduct = productBas.getPkProduct();
            if (pkProduct == null) {
                productBas.setIsShowCreateButton(EYesNo.YES.getIntValue());
            } else {
                productBas.setIsShowCreateButton(EYesNo.NO.getIntValue());
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出
     *
     * @param productBasParams
     * @return
     */
    @PostMapping("/export")
    public void export(ProductBasParams productBasParams, HttpServletResponse response) {
        LambdaQueryWrapper<BdProductBas> qw = new LambdaQueryWrapper<>();
        qw.eq(BdProductBas::getPkCountry, SecurityUtils.getPkCountry());
        qw.eq(BdProductBas::getSystemType, SecurityUtils.getSystemType());
        if (StringUtils.isNotBlank(productBasParams.getProductCode())) {
            qw.like(BdProductBas::getProductCode, productBasParams.getProductCode());
        }
        if (StringUtils.isNotBlank(productBasParams.getProductName())) {
            qw.like(BdProductBas::getProductName, productBasParams.getProductName());
        }
        if (productBasParams.getStartCreateDate() != null && productBasParams.getEndCreateDate() != null) {
            qw.between(BdProductBas::getCreationTime, DateUtils.getStartTime(productBasParams.getStartCreateDate()), DateUtils.getEndTime(productBasParams.getEndCreateDate()));
        }
        qw.orderByDesc(BdProductBas::getCreationTime);
        List<BdProductBas> list = productBasService.list(qw);
        List<ProductBasVo> resultList = list.stream().map(a -> BeanUtil.copyProperties(a, ProductBasVo.class)).collect(Collectors.toList());
        ExcelUtil<ProductBasVo> util = new ExcelUtil<>(ProductBasVo.class);
        util.exportExcel(response, resultList, "产品基本信息导出");
    }

    /**
     * 查询全部
     *
     * @return
     */
    @GetMapping("/find-all")
    public TableDataInfo findAll(String query, Integer pkCubasdoc) {
        startPage();
        List<ProductBasVo> resultList = productBasService.queryProductBasList(query, SecurityUtils.getPkCountry(), pkCubasdoc, SecurityUtils.getSystemType());
        return getDataTable(resultList);
    }

    /**
     * 查询全部
     *
     * @return
     */
    @GetMapping("/find-by-bas-all")
    public TableDataInfo findByBasAll(String query) {
        startPage();
        List<ProductBasVo> resultList = productBasService.queryProductBasAllList(query, SecurityUtils.getPkCountry(), SecurityUtils.getSystemType());
        return getDataTable(resultList);
    }

    /**
     * 查询全部关联商品
     *
     * @param
     * @return
     */
    @GetMapping("/query-product-bas-relevance")
    public TableDataInfo queryProductBasRelevance(String query) {
        startPage();
        Integer pkCountry = SecurityUtils.getPkCountry();
        List<ProductBasVo> resultList = productBasService.queryProductBasRelevanceList(query, pkCountry, SecurityUtils.getSystemType());
        return getDataTable(resultList);
    }

    /**
     * 新增
     *
     * @param productBasParams
     * @return
     */
    @PostMapping("/save")
    public AjaxResult save(@RequestBody ProductBasParams productBasParams) {
        if (StringUtils.isBlank(productBasParams.getProductName())) {
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.PRODUCT_NAME_REQUIRED));
        }
        // 保质期
        if (productBasParams.getShelfLife() == null) {
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.PRODUCT_SHELFLIFE_REQUIRED));
        }
        // 单位
        if (productBasParams.getUnit() == null) {
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.PRODUCT_UNIT_REQUIRED));
        }
        // 重量
        if (productBasParams.getWeight() == null) {
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.PRODUCT_WEIGHT_REQUIRED));
        }
        // 产品分类
        if (productBasParams.getPkClassify() == null) {
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.PRODUCT_CLASSIFY_REQUIRED));
        }
        // 长
        if (productBasParams.getLength() == null) {
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.PRODUCT_LENGTH_REQUIRED));
        }
        // 宽
        if (productBasParams.getWidth() == null) {
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.PRODUCT_WIDTH_REQUIRED));
        }
        // 高
        if (productBasParams.getHeight() == null) {
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.PRODUCT_HEIGHT_REQUIRED));
        }
        // 产品主图
        if (StringUtils.isBlank(productBasParams.getCover())) {
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.PRODUCT_COVER_REQUIRED));
        }
        // 产品相关规格
        if (productBasParams.getPkSpecsType().size() == 0) {
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.PRODUCT_SPECSTYPE_REQUIRED));
        }
        productBasParams.setSystemType(SecurityUtils.getSystemType());
        // 新增商品信息
        LoginUser loginUser = userTokenService.getLoginUser();
        // 校验编号重复
        LambdaQueryWrapper<BdProductBas> qw = new LambdaQueryWrapper<>();
        qw.eq(BdProductBas::getProductCode, productBasParams.getProductCode());
        qw.eq(BdProductBas::getSystemType, SecurityUtils.getSystemType());
        int productCount = productBasService.count(qw);
        if (productCount > 0) {
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.PRODUCT_NUMBER_ALREADY_EXISTS));
        }
        return AjaxResult.success(productBasService.saveProductBas(productBasParams, loginUser));
    }

    /**
     * 查询产品详情
     *
     * @return
     */
    @GetMapping("/detail")
    public AjaxResult detail(Integer productBasId) {
        BdProductBas productBas = productBasService.getById(productBasId);
        if (productBas == null) {
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.PRODUCT_NOT_REQUIRED));
        }
        ProductBasParams productParams = BeanUtil.copyProperties(productBas, ProductBasParams.class);
        LambdaQueryWrapper<BdProductBasSpecs> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BdProductBasSpecs::getPkProductBas, productBasId);
        List<Integer> pkSpecsType = new ArrayList<>();
        List<BdProductBasSpecs> productSpecList = productBasSpecsService.list(queryWrapper);
        for (BdProductBasSpecs productBasSpecs : productSpecList) {
            pkSpecsType.add(productBasSpecs.getPkSpecsType());
        }
        productParams.setPkSpecsType(pkSpecsType);
        return AjaxResult.success(productParams);
    }

    /**
     * 修改
     *
     * @param productBasParams
     * @return
     */
    @PostMapping("/update")
    public AjaxResult update(@RequestBody ProductBasParams productBasParams) {
        // 查询订单编号是否重复
        BdProductBas productBas = productBasService.getById(productBasParams.getPkId());
        if (!productBas.getProductCode().equals(productBasParams.getProductCode())) {
            LambdaQueryWrapper<BdProductBas> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BdProductBas::getProductCode, productBasParams.getProductCode());
            queryWrapper.eq(BdProductBas::getSystemType, SecurityUtils.getSystemType());
            int count = productBasService.count(queryWrapper);
            if (count > 0) {
                return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.PRODUCT_NUMBER_ALREADY_EXISTS));
            }
        }
        LoginUser loginUser = userTokenService.getLoginUser();
        // 校验编号重复
        LambdaQueryWrapper<BdProductBas> qe = new LambdaQueryWrapper<>();
        qe.eq(BdProductBas::getProductCode, productBasParams.getProductCode());
        qe.eq(BdProductBas::getSystemType, SecurityUtils.getSystemType());
        qe.notIn(BdProductBas::getPkId, productBasParams.getPkId());
        int productCount = productBasService.count(qe);
        if (productCount > 0) {
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.PRODUCT_NUMBER_ALREADY_EXISTS));
        }
        // 修改商品基本信息
        productBasService.updateProductBas(productBasParams, loginUser);
        return AjaxResult.success(productBasParams.getProductCode());
    }


    /**
     * 根据商品id 删除数据
     *
     * @param pkId
     * @return
     */
    @Log(module = EOperationModule.PRODUCT_DELETE, method = EOperationMethod.DELETE)
    @DeleteMapping("/{pkId}")
    public AjaxResult delete(@PathVariable Integer pkId) {
        productBasService.removeProductBas(pkId);
        return AjaxResult.success();
    }

    /**
     * 根据产品编号查询产品信息
     *
     * @param productCode
     * @return
     */
    @GetMapping("/get-product-info")
    public AjaxResult getProductInfo(String productCode) {
        return AjaxResult.success(productBasService.getByProductCodeInfo(productCode));
    }

    /**
     * 生成产品
     */
    @GetMapping("/generate-product")
    public AjaxResult generateProduct(Integer pkProductBas) {
        // 生成产品基本信息
        LoginUser loginUser = userTokenService.getLoginUser();
        BdProductBas productBas = productBasService.getById(pkProductBas);
        String productCode = productBas.getProductCode();
        ThProduct product = thProductService.getOne(new LambdaQueryWrapper<ThProduct>().eq(ThProduct::getProductCode, productCode));
        if (product != null) {
            // 商品拓展表
            ThProductExtend productExtend = productExtendService.getOne(new LambdaQueryWrapper<ThProductExtend>().eq(ThProductExtend::getPkProduct, product.getPkId()));
            // 商品规格表
            List<ThProductSpecs> productSpecsList = productSpecsService.list(new LambdaQueryWrapper<ThProductSpecs>().eq(ThProductSpecs::getPkProduct, product.getPkId()));
            // 创建产品
            ProductParamDTO productDTO = new ProductParamDTO();
            productDTO.setProductCode(product.getProductCode());
            productDTO.setProductName(product.getProductName());
            productDTO.setPkClassify(product.getPkClassify());
            productDTO.setShippingChannel(product.getShippingChannel());
            productDTO.setUnit(product.getUnit());
            productDTO.setWeight(product.getWeight());
            productDTO.setWidth(product.getWidth());
            productDTO.setPostageWeight(BigDecimal.ZERO);
            productDTO.setHeight(product.getHeight());
            productDTO.setLength(product.getLength());
            productDTO.setRetailPrice(product.getRetailPrice());
            productDTO.setCover(product.getCover());
            productDTO.setShelfLife(product.getShelfLife());
            productDTO.setCreationTime(DateUtils.currentDateTime());
            productDTO.setPkCreator(SecurityUtils.getUserId());
            productDTO.setPkCountry(SecurityUtils.getPkCountry());
            productDTO.setPkProductBas(productBas.getPkId());
            productDTO.setPkSupplier(product.getPkSupplier());
            List<Integer> pkSpecsType = new ArrayList<>();
            for (ThProductSpecs productSpecs : productSpecsList) {
                pkSpecsType.add(productSpecs.getPkSpecsType());
            }
            productDTO.setPkSpecsType(pkSpecsType);
            productDTO.setIsPickUp(productExtend.getIsPickUp());
            productDTO.setIsBarCode(productExtend.getIsBarCode());
            productDTO.setIsMerge(productExtend.getIsMerge());
            productDTO.setIsGift(productExtend.getIsGift());
            productDTO.setIsLandTrans(productExtend.getIsLandTrans());
            productDTO.setIsAirTrans(productExtend.getIsAirTrans());
            productDTO.setIsOceanTrans(productExtend.getIsOceanTrans());
            productDTO.setSort(productExtend.getSort());
            productDTO.setRepurchaseType(productExtend.getRepurchaseType());
            productDTO.setIsFresh(EYesNo.NO.getIntValue());
            productDTO.setPkCubasdoc(product.getPkCubasdoc());
            productServiceApi.saveProduct(productDTO, loginUser);
        } else {
            List<BdProductBasSpecs> productSpecsList = productBasSpecsService.list(new QueryWrapper<BdProductBasSpecs>().eq("PK_PRODUCT_BAS", productBas.getPkId()));
            // 创建产品
            ProductParamDTO productDTO = new ProductParamDTO();
            productDTO.setProductCode(productBas.getProductCode());
            productDTO.setProductName(productBas.getProductName());
            productDTO.setPkClassify(productBas.getPkClassify());
            productDTO.setShippingChannel(EShippingChannel.A_PIECE.getValue());
            productDTO.setUnit(productBas.getUnit());
            productDTO.setWeight(productBas.getWeight());
            productDTO.setWidth(productBas.getWidth());
            productDTO.setPostageWeight(BigDecimal.ZERO);
            productDTO.setHeight(productBas.getHeight());
            productDTO.setLength(productBas.getLength());
            productDTO.setRetailPrice(BigDecimal.ZERO);
            productDTO.setCover(productBas.getCover());
            productDTO.setShelfLife(productBas.getShelfLife());
            productDTO.setCreationTime(DateUtils.currentDateTime());
            productDTO.setPkCreator(SecurityUtils.getUserId());
            productDTO.setPkCountry(SecurityUtils.getPkCountry());
            productDTO.setPkProductBas(productBas.getPkId());
            List<Integer> pkSpecsType = new ArrayList<>();
            for (BdProductBasSpecs productBasSpecs : productSpecsList) {
                pkSpecsType.add(productBasSpecs.getPkSpecsType());
            }
            productDTO.setPkSpecsType(pkSpecsType);
            productDTO.setIsPickUp(EYesNo.NO.getIntValue());
            productDTO.setIsBarCode(EYesNo.NO.getIntValue());
            productDTO.setIsMerge(EYesNo.NO.getIntValue());
            productDTO.setIsGift(EYesNo.NO.getIntValue());
            productDTO.setIsLandTrans(EYesNo.NO.getIntValue());
            productDTO.setIsAirTrans(EYesNo.NO.getIntValue());
            productDTO.setIsOceanTrans(EYesNo.NO.getIntValue());
            productDTO.setSort(EYesNo.NO.getIntValue());
            productDTO.setRepurchaseType(EYesNo.NO.getIntValue());
            productDTO.setIsFresh(EYesNo.NO.getIntValue());
            productServiceApi.saveProduct(productDTO, loginUser);
        }
        return AjaxResult.success();
    }

    /**
     * 查询供应商产品
     */
    @GetMapping("/get-supplier-product")
    public AjaxResult getSupplierProduct(Integer pkSupplier) {
        List<ProductBasVo> productBasList;
        if (pkSupplier != null) {
            productBasList = productBasService.selectbypkSupplierList(pkSupplier);
        } else {
            productBasList = productBasService.selectbyNotSupplierList();
        }
        for (ProductBasVo productBasVo : productBasList) {
            productBasVo.setUnitStr(EUnit.getEnumByValue(productBasVo.getUnit()).getLabel());
        }
        return AjaxResult.success(productBasList);
    }
}
