package com.fjhx.sale.service.contract.impl;

import cn.hutool.http.HttpRequest;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fjhx.common.constant.SourceConstant;
import com.fjhx.common.enums.FlowStatusEnum;
import com.fjhx.common.service.corporation.CorporationService;
import com.fjhx.customer.service.customer.CustomerService;
import com.fjhx.item.service.product.ProductClassifyService;
import com.fjhx.item.service.product.ProductInfoService;
import com.fjhx.kd100.entity.company.po.CompanyInfo;
import com.fjhx.purchase.entity.purchase.po.Purchase;
import com.fjhx.purchase.entity.purchase.vo.PurchaseDetailVo;
import com.fjhx.purchase.service.purchase.PurchaseDetailService;
import com.fjhx.sale.entity.contract.po.Contract;
import com.fjhx.sale.entity.contract.po.ContractProduct;
import com.fjhx.sale.entity.quality.po.EhsdQuality;
import com.fjhx.sale.mapper.contract.ContractProductMapper;
import com.fjhx.sale.service.contract.ContractProductService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.sale.service.quality.EhsdQualityService;
import com.fjhx.supply.service.supplier.SupplierInfoService;
import com.obs.services.internal.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.wrapper.SqlField;
import com.ruoyi.framework.web.service.TokenService;
import jdk.nashorn.internal.parser.Token;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fjhx.sale.entity.contract.vo.ContractProductVo;
import com.fjhx.sale.entity.contract.dto.ContractProductSelectDto;
import com.ruoyi.common.utils.wrapper.IWrapper;
import com.fjhx.sale.entity.contract.dto.ContractProductDto;
import cn.hutool.core.bean.BeanUtil;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
 * 外销合同-产品 服务实现类
 * </p>
 *
 * @author
 * @since 2023-04-17
 */
@Service
public class ContractProductServiceImpl extends ServiceImpl<ContractProductMapper, ContractProduct> implements ContractProductService {

    @Autowired
    private ProductInfoService productInfoService;

    @Autowired
    private ProductClassifyService productClassifyService;

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private SupplierInfoService supplierInfoService;

    @Autowired
    private EhsdQualityService ehsdQualityService;

    @Autowired
    private CorporationService corporationService;

    /**
     * 分页
     * @param dto
     * @return
     */
    @Override
    public Page<ContractProductVo> getPage(ContractProductSelectDto dto) {
        IWrapper<ContractProduct> wrapper = getWrapper();
        wrapper.orderByDesc("t1", ContractProduct::getCreateTime);
        wrapper.between("t2", Contract::getStatus, FlowStatusEnum.PASS.getKey(),FlowStatusEnum.CANCELLATION.getKey()-1);
        wrapper.gt("t1",ContractProduct::getExpendQuantity,BigDecimal.ZERO);
        if(StringUtils.isNotEmpty(dto.getKeyword())){
            wrapper.keyword(dto.getKeyword(),new SqlField("t2.`code`"),new SqlField("t2.`user_name`"));
        }
        Page<ContractProductVo> page = this.baseMapper.getPage(dto.getPage(), wrapper);
        List<ContractProductVo> list = page.getRecords();
        if(CollectionUtils.isNotEmpty(list)){
            // 赋值产品属性
            productInfoService.attributeAssign(list, ContractProductVo::getProductId, (item, product) -> {
                item.setProductCode(product.getCode());
                item.setProductUnit(product.getUnit());
                item.setProductType(product.getType());
                item.setProductName(product.getName());
                item.setProductSpec(product.getSpec());
                item.setProductCategoryId(product.getProductClassifyId());
            });
            // 赋值产品分类名称
            productClassifyService.attributeAssign(list, ContractProductVo::getProductCategoryId, (item, productClassify) -> {
                item.setProductCategory(productClassify.getName());
            });
        }
        return page;
    }

    /**
     * 根据合同ID和客户ID查询未包装的产品
     * @param customerId
     * @return
     */
    @Override
    public List<ContractProductVo> getNoPackContractProductById(String customerId,String contractIds) {
        List<ContractProductVo> list = baseMapper.getNoPackContractProductById(customerId, Arrays.asList(contractIds.split(",")));
        // 赋值产品属性
        productInfoService.attributeAssign(list, ContractProductVo::getProductId, (item, product) -> {
            item.setProductCode(product.getCode());
            item.setProductUnit(product.getUnit());
            item.setProductType(product.getType());
            item.setProductName(product.getName());
            item.setProductSpec(product.getSpec());
            item.setProductCategoryId(product.getProductClassifyId());
        });
        // 赋值产品分类名称
        productClassifyService.attributeAssign(list, ContractProductVo::getProductCategoryId, (item, productClassify) -> {
            item.setProductCategory(productClassify.getName());
        });
        return list;
    }

    /**
     * 交接单
     * @param dto
     * @return
     */
    @Override
    public Page<ContractProductVo> getEHSDPage(ContractProductSelectDto dto) {
        IWrapper<ContractProduct> wrapper = getWrapper();
        wrapper.orderByDesc("t1.ct");
        if(StringUtils.isNotEmpty(dto.getKeyword())){
            wrapper.keyword(dto.getKeyword(),new SqlField("t1.`contractCode`"),new SqlField("t1.`userName`"));
        }
        if(StringUtils.isNotEmpty(dto.getIds())){
            wrapper.in("t1.id",Arrays.asList(dto.getIds().split(",")));
        }
        Page<ContractProductVo> page = this.baseMapper.getEHSDPage(dto.getPage(), wrapper);
        List<ContractProductVo> list = page.getRecords();
        if(CollectionUtils.isNotEmpty(list)){
            // 赋值产品属性
            productInfoService.attributeAssign(list, ContractProductVo::getProductId, (item, product) -> {
                item.setProductCode(product.getCode());
                item.setProductUnit(product.getUnit());
                item.setProductType(product.getType());
//                item.setProductName(product.getName());
                item.setProductSpec(product.getSpec());
                item.setProductCategoryId(product.getProductClassifyId());
            });
            // 赋值产品分类名称
            productClassifyService.attributeAssign(list, ContractProductVo::getProductCategoryId, (item, productClassify) -> {
                item.setProductCategory(productClassify.getName());
            });
        }
        return page;
    }

    /**
     * 待质检分页
     * @param dto
     * @return
     */
    @Override
    public Page<ContractProductVo> getEHSDQualityPage(ContractProductSelectDto dto) {
        IWrapper<ContractProduct> wrapper = getWrapper();
        wrapper.orderByDesc("t1.ct");
        if(StringUtils.isNotEmpty(dto.getKeyword())){
            wrapper.keyword(dto.getKeyword(),new SqlField("t1.`contractCode`"),new SqlField("t1.`userName`"));
        }
        if(StringUtils.isNotEmpty(dto.getOrderType())){
            wrapper.eq("t1.orderType",dto.getOrderType());
        }
        if(StringUtils.isNotEmpty(dto.getQualityStatus())){
            wrapper.eq("t1.qualityStatus",dto.getQualityStatus());
        }
        if(StringUtils.isNotEmpty(dto.getSummary())){
            wrapper.eq("t1.summary",dto.getSummary());
        }
        Page<ContractProductVo> page = this.baseMapper.getEHSDPage(dto.getPage(), wrapper);
        List<ContractProductVo> list = page.getRecords();
//        //查出所有质检状态
//        List<Long> contractProductIds = list.stream().map(ContractProductVo::getId).collect(Collectors.toList());
//        List<EhsdQuality> qualityList = ehsdQualityService.list(Wrappers.<EhsdQuality>query().lambda().in(EhsdQuality::getBusinessId,contractProductIds));
//        Map<Long,Integer> qualityMap = qualityList.stream().distinct().collect(Collectors.toMap(EhsdQuality::getBusinessId,EhsdQuality::getStatus));
        if(CollectionUtils.isNotEmpty(list)){
            // 赋值产品属性
            productInfoService.attributeAssign(list, ContractProductVo::getProductId, (item, product) -> {
                item.setProductCode(product.getCode());
                item.setProductUnit(product.getUnit());
                item.setProductType(product.getType());
//                item.setProductName(product.getName());
                item.setProductSpec(product.getSpec());
                item.setProductCategoryId(product.getProductClassifyId());
            });
            // 赋值产品分类名称
            productClassifyService.attributeAssign(list, ContractProductVo::getProductCategoryId, (item, productClassify) -> {
                item.setProductCategory(productClassify.getName());
            });
            // 赋值客户名称
            customerService.attributeAssign(list, ContractProductVo::getBuyCorporationId, (item, customer) -> {
                item.setCustomerName(customer.getName());
            });
            // 供应商名称
            corporationService.attributeAssign(list, ContractProductVo::getSellCorporationId, (item, supplier) -> {
                item.setSupplyName(supplier.getName());
                item.setSupplyId(item.getId());
            });
//            if(CollectionUtils.isNotEmpty(qualityMap)){
//                list.forEach(i -> i.setQualityStatus(qualityMap.getOrDefault(i.getId(),null)));
//            }
        }
        return page;
    }

    /**
     * 合同交接单--分页
     */
    @Override
    public Page<ContractProductVo> contractHandoverPage(ContractProductSelectDto dto) {
        IWrapper<ContractProduct> wrapper = getWrapper();
        wrapper.orderByDesc("t1.create_time");
        if(StringUtils.isNotEmpty(dto.getKeyword())){
            wrapper.keyword(dto.getKeyword(),new SqlField("t1.`contractCode`"),new SqlField("t1.`userName`"));
        }
        wrapper.ge("t2.`status`",30);
        wrapper.lt("t2.`status`",88);
        wrapper.gt("t1.expend_quantity",0);
        //查询合同交接单的数据（只查询有添加交接单的数据）
        Page<ContractProductVo> page = this.baseMapper.contractHandoverPage(dto.getPage(), wrapper);

        List<ContractProductVo> list = page.getRecords();
        if(CollectionUtils.isNotEmpty(list)){
            // 赋值产品属性
            productInfoService.attributeAssign(list, ContractProductVo::getProductId, (item, product) -> {
                item.setProductCode(product.getCode());
                item.setProductUnit(product.getUnit());
                item.setProductType(product.getType());
                item.setProductName(product.getName());
                item.setProductSpec(product.getSpec());
                item.setProductCategoryId(product.getProductClassifyId());
            });
            // 赋值客户名称
            customerService.attributeAssign(list, ContractProductVo::getBuyCorporationId, (item, corporation) -> {
                item.setBuyCorporationName(corporation.getName());
            });
        }
        return page;
    }

    /**
     * 根据合同产品IDS查询合同产品
     * @param ids
     * @return
     */
    @Override
    public List<ContractProductVo> getListDetail(List<Long> ids) {
        if(CollectionUtils.isEmpty(ids)){
            throw new ServiceException("参数异常");
        }
        IWrapper<ContractProduct> wrapper = getWrapper();
        wrapper.in("t1",ContractProduct::getId,ids);
        List<ContractProductVo> list = baseMapper.getListByIds(wrapper);
        if(CollectionUtils.isNotEmpty(list)){
            List<PurchaseDetailVo> vo = purchaseDetailService.getSumCountInDataResourceIds(ids);
            Map<Long,BigDecimal> voMap = vo.stream().collect(Collectors.toMap(PurchaseDetailVo::getDataResourceId,PurchaseDetailVo::getSumCount));
            for(ContractProductVo c:list){
                if(MapUtils.isNotEmpty(voMap)){
                    c.setSumPurchaseCount(voMap.getOrDefault(c.getId(),BigDecimal.ZERO));
                }
            }

            // 赋值产品属性
            productInfoService.attributeAssign(list, ContractProductVo::getProductId, (item, product) -> {
                item.setProductCode(product.getCode());
                item.setProductUnit(product.getUnit());
                item.setProductType(product.getType());
                item.setProductName(product.getName());
                item.setProductSpec(product.getSpec());
                item.setProductCategoryId(product.getProductClassifyId());
            });

            // 赋值产品分类名称
            productClassifyService.attributeAssign(list, ContractProductVo::getProductCategoryId, (item, productClassify) -> {
                item.setProductCategory(productClassify.getName());
            });


        }
        return list;
    }

    @Override
    public ContractProductVo detail(Long id) {
        ContractProduct ContractProduct = this.getById(id);
        ContractProductVo result = BeanUtil.toBean(ContractProduct, ContractProductVo.class);
        return result;
    }

    @Override
    public void add(ContractProductDto contractProductDto) {
        this.save(contractProductDto);
    }

    @Override
    public void edit(ContractProductDto contractProductDto) {
        this.updateById(contractProductDto);
    }

    @Override
    public void delete(Long id) {
        this.removeById(id);
    }

}
