package com.hzs.scm.product.controller.manage;/**
 * @Description:
 * @Author: yuhui
 * @Time: 2023/11/27 9:29
 * @Classname: BdProductBasController
 * @PackageName: com.hzs.scm.product.controller
 */

import cn.hutool.core.bean.BeanUtil;
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.EOperationMethod;
import com.hzs.common.core.enums.EOperationModule;
import com.hzs.common.core.enums.EUnit;
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.constant.msg.ProductMsgConstants;
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.*;
import com.hzs.common.domain.sale.wares.BdWaresDetail;
import com.hzs.common.security.service.UserTokenService;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.core.utils.TransactionUtils;
import com.hzs.scm.product.param.ProductBasParams;
import com.hzs.scm.product.service.IBdProductBasService;
import com.hzs.scm.product.service.IBdProductBasSpecsService;
import com.hzs.scm.product.vo.ProductBasVo;
import com.hzs.system.sys.dto.LoginUser;
import lombok.Data;
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.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.ArrayList;
import java.util.List;

/**
 *@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 IBdProductBasService productBasService;
    @Autowired
    private IBdProductBasSpecsService productBasSpecsService;

    /**
     * 查询列表 (分页)
     * @return
     */
    @GetMapping("list")
    public TableDataInfo list(ProductBasParams productBasParams){
        QueryWrapper<BdProductBas> qw = new QueryWrapper<>();
        // 禅道bug 8329
        //qw.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        if (StringUtils.isNotBlank(productBasParams.getProductCode())){
            qw.like("PRODUCT_CODE", productBasParams.getProductCode());
        }
        if (StringUtils.isNotBlank(productBasParams.getProductName())){
            qw.like("PRODUCT_NAME", productBasParams.getProductName());
        }
        if (productBasParams.getStartCreateDate() != null && productBasParams.getEndCreateDate() != null){
            qw.between("CREATION_TIME", DateUtils.getStartTime(productBasParams.getStartCreateDate()),DateUtils.getEndTime(productBasParams.getEndCreateDate()));
        }
        qw.orderByDesc("CREATION_TIME");
        startPage();
        List<BdProductBas> list = productBasService.list(qw);
        return getDataTable(list);
    }

    /**
     * 导出
     * @param productBasParams
     * @return
     */
    @PostMapping("/export")
    public void export(@RequestBody ProductBasParams productBasParams, HttpServletResponse response){
        QueryWrapper<BdProductBas> qw = new QueryWrapper<>();
        qw.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        if (StringUtils.isNotBlank(productBasParams.getProductCode())){
            qw.like("PRODUCT_CODE", productBasParams.getProductCode());
        }
        if (StringUtils.isNotBlank(productBasParams.getProductName())){
            qw.like("PRODUCT_NAME", productBasParams.getProductName());
        }
        if (productBasParams.getStartCreateDate() != null && productBasParams.getEndCreateDate() != null){
            qw.between("CREATION_TIME", DateUtils.getStartTime(productBasParams.getStartCreateDate()),DateUtils.getEndTime(productBasParams.getEndCreateDate()));
        }
        qw.orderByDesc("CREATION_TIME");
        List<BdProductBas> list = productBasService.list(qw);
        List<ProductBasVo> resultList = list.stream().map(a -> {
            return 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<BdProductBas> list = productBasService.lfindist(qw);
        List<ProductBasVo> resultList = productBasService.queryProductBasList(query,SecurityUtils.getPkCountry(),pkCubasdoc);
    //    List<ProductBasVo> resultList = productBasService.queryProductBasList(query,null);
//        List<ProductBasVo> resultList = list.stream().map(a -> {
//            ProductBasVo productBasVo = BeanUtil.copyProperties(a, ProductBasVo.class);
//            productBasVo.setUnitStr(EUnit.getEnumByValue(a.getUnit()).getLabel());
//            return productBasVo;
//        }).collect(Collectors.toList());
        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);
        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.getShippingChannel() == null) {
//            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.PRODUCT_SHIPPING_CHANNEL_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.getSort() == null) {
//            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.PRODUCT_SORT_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));
        }
        // 新增商品信息
        LoginUser loginUser = userTokenService.getLoginUser();
        // 校验编号重复
        QueryWrapper<BdProductBas> qw = new QueryWrapper<BdProductBas>();
        qw.eq("PRODUCT_CODE",productBasParams.getProductCode());
        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);
        QueryWrapper<BdProductBasSpecs> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PK_PRODUCT_BAS", 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())) {
            QueryWrapper<BdProductBas> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("PRODUCT_CODE", productBasParams.getProductCode());
            int count = productBasService.count(queryWrapper);
            if (count > 0) {
                return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.PRODUCT_NUMBER_ALREADY_EXISTS));
            }
        }
        LoginUser loginUser = userTokenService.getLoginUser();
        // 校验编号重复
        QueryWrapper<BdProductBas> qe = new QueryWrapper<>();
        qe.eq("PRODUCT_CODE",productBasParams.getProductCode());
        qe.notIn("PK_ID",productBasParams.getPkId());
        int productCount = productBasService.count(qe);
        if (productCount > 0){
            return AjaxResult.error(TransactionUtils.getContent(ProductMsgConstants.PRODUCT_NUMBER_ALREADY_EXISTS));
        }
        // 修改商品基本信息
        productBasService.updateProductBas(productBasParams, loginUser);
        //    productService.saveProductModifyRecord(productParams, loginUser,EModifyRecordType.PRODUCT_ADD.getValue());
        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, SecurityUtils.getPkCountry()));
    }

    /**
     * 查询供应商产品
     */
    @GetMapping("get-supplier-product")
    public AjaxResult getSupplierProduct(String query ){
        List<BdProductBas> productBasList = null;
//        if (pkSupplier != null){
//            productBasList = productBasService.selectbypkSupplierList(pkSupplier);
//        }else {
            productBasList = productBasService.selectbyNotSupplierList(query);
      //  }
        return AjaxResult.success(productBasList);
    }

    /**
     * 查询全部
     * @return
     */
    @GetMapping("find-by-bas-all")
    public TableDataInfo findByBasAll(String query){
        startPage();
        //    List<BdProductBas> list = productBasService.lfindist(qw);
        QueryWrapper<BdProductBas> queryWrapper  = new QueryWrapper<>();
        if (StringUtils.isNotBlank(query)){
            queryWrapper.like("PRODUCT_CODE",query).or().like("PRODUCT_NAME",query);
        }
        //  List<BdProductBas> resultList = productBasService.list(queryWrapper);
        List<ProductBasVo> resultList = productBasService.queryProductBasAllList(query,SecurityUtils.getPkCountry());
//        List<ProductBasVo> resultList = list.stream().map(a -> {
//            ProductBasVo productBasVo = BeanUtil.copyProperties(a, ProductBasVo.class);
//            productBasVo.setUnitStr(EUnit.getEnumByValue(a.getUnit()).getLabel());
//            return productBasVo;
//        }).collect(Collectors.toList());
        return getDataTable(resultList);
    }
}
