package com.jwipc.inquiry.logic.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Pair;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.jwipc.api.OaCallBackLogic;
import com.jwipc.constant.OaProcessType;
import com.jwipc.api.constant.OaStatus;
import com.jwipc.api.constant.RestCode;
import com.jwipc.api.dto.ApiResult;
import com.jwipc.inquiry.constant.InquiryStatus;
import com.jwipc.inquiry.constant.SequenceConst;
import com.jwipc.inquiry.constant.SysConfigKey;
import com.jwipc.inquiry.convert.PriceInfoConvert;
import com.jwipc.inquiry.dto.CreatePriceInfoDTO;
import com.jwipc.inquiry.entity.Inquiry;
import com.jwipc.inquiry.entity.PriceInfo;
import com.jwipc.inquiry.logic.PriceInfoLogic;
import com.jwipc.inquiry.model.po.CreatePriceInfoPO;
import com.jwipc.inquiry.service.IInquiryService;
import com.jwipc.inquiry.service.IPriceInfoService;
import com.jwipc.supplier.clent.dto.SupplierPurchaseCategoryDTO;
import com.jwipc.supplier.client.QuotaManagementClient;
import com.jwipc.supplier.client.SupplierClient;
import com.jwipc.sys.client.ExchangeRateClient;
import com.jwipc.sys.client.SequenceClient;
import com.jwipc.sys.client.SysConfigClient;
import com.jwipc.tender.client.dto.QuotaManagementParamClientDTO;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author shenyang.ou
 * @date 2024/4/1 14:39
 * @desc 扣款审批回调
 */
@Service("InquiryPriceCallBack")
@RequiredArgsConstructor
public class InquiryPriceCallBack implements OaCallBackLogic {
    private final IInquiryService inquiryService;
    private final IPriceInfoService priceInfoService;
    private final PriceInfoLogic priceInfoLogic;
    private final PriceInfoConvert priceInfoConvert;
    private final ExchangeRateClient exchangeRateClient;
    private final SupplierClient supplierClient;
    private final QuotaManagementClient quotaManagementClient;
    private final SequenceClient sequenceClient;
    private final SysConfigClient sysConfigClient;

    /**
     * oa回调接口
     *
     * @param workflowId  流程id
     * @param status      状态
     * @param remark      审批意见
     * @param processCode 流程编号
     * @param data1       回传的数据1
     * @param data2       回传数据2
     * @return
     */
    @Override
    @Transactional
    public ApiResult processor(String workflowId, OaStatus status, String remark, String processCode, String data1, String data2) {
        final Inquiry inquiry = inquiryService.getOne(
                new LambdaQueryWrapper<Inquiry>().eq(Inquiry::getOaWorkId, workflowId));


        if (Objects.isNull(inquiry)) {
            return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("未找到匹配的流程数据!").build();
        }
        if (inquiry.getStatus()==InquiryStatus.FINISH.getStatus()){
            return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("该流程数据已处理，不可重复提交!").build();
        }
        RestCode code = RestCode.SAP_SUCCESS;
        String mesg = "";
        try {
            if (status.equals(OaStatus.REFUSE)) {
                inquiry.setStatus(InquiryStatus.FIX_OA_REFUSE.getStatus());
            } else if (status.equals(OaStatus.PASS)){
                inquiry.setStatus(InquiryStatus.FINISH.getStatus());
                //根据询价id组装价格信息记录数据
                List<CreatePriceInfoPO> createPriceInfoPOS = priceInfoService.getByInquiryId(inquiry.getId());
                List<CreatePriceInfoDTO> createPriceInfoDTOS = priceInfoConvert.po2DtoList(createPriceInfoPOS);
                //过滤掉价格为0的数据
                createPriceInfoDTOS.removeIf(s -> Objects.isNull(s.getTaxPrice())||s.getTaxPrice().compareTo(BigDecimal.ZERO)==0);
                createPriceInfoDTOS.forEach(createPriceInfoDTO -> {
                    createPriceInfoDTO.setId(createPriceInfoDTO.getJoinQuoteFlag()==0?createPriceInfoDTO.getPriceInfoId():IdWorker.getId());
                    //价格表的创建人要取报价投标发起人（采购），创建人id 2024-10-21 邓京术
                    createPriceInfoDTO.setCreateUser(inquiry.getCreateUser());
//                    //获取税率
//                    BigDecimal exchangeRate = exchangeRateClient.getExchangeRate(createPriceInfoDTO.getCurrencyCode(),"CNY");
//                    createPriceInfoDTO.setExchangeRate(exchangeRate==null?BigDecimal.ONE:exchangeRate);
                });
                //只取参与报价的供应商
                List<CreatePriceInfoDTO> filterCreatePriceInfoDTOS = createPriceInfoDTOS.stream().filter(inquiryMaterialSupplier -> inquiryMaterialSupplier.getJoinQuoteFlag()==1).collect(Collectors.toList());
                priceInfoLogic.createPriceInfo(filterCreatePriceInfoDTOS);
                inquiry.setGenPriceInfo(1);
                //保存配额
                saveQuota(createPriceInfoDTOS,inquiry.getPurchaseOrgCode(), inquiry.getCreateUser());
            }
            else if (status.equals(OaStatus.DISCARDED)){
                inquiry.setStatus(InquiryStatus.FIX_OA_REJECT.getStatus());
            } else if (status.equals(OaStatus.RUNNING)){
                inquiry.setStatus(InquiryStatus.FIX_ING.getStatus());
            }
            inquiryService.updateById(inquiry);
        } catch (Exception e) {
            code = RestCode.SAP_ERROR;
            mesg = e.getMessage();
            e.printStackTrace();
        }
        return ApiResult.builder().code(code.getCode()).message(mesg).build();
    }

    /**
     * 保存配额
     */
    public void saveQuota(List<CreatePriceInfoDTO> createPriceInfoDTOS,String purchaseOrgCode, Long creater){
        List<String> supplierCodes = createPriceInfoDTOS.stream()
                .map(CreatePriceInfoDTO::getSupplierCode)
                .filter(code -> code != null) // 过滤掉 null 值
                .collect(Collectors.toList());
        //到供应商信息主表里查询供应商信息
        Map<String, String> supplierMap = priceInfoLogic.getSupplierInfoList(supplierCodes);

        //根据物料编码和工厂分组
        Map<String, List<CreatePriceInfoDTO>> skuMap = createPriceInfoDTOS.stream().collect(Collectors.groupingBy(item ->
                item.getMaterialCode() + "_" + item.getFactoryCode()));
        for (Map.Entry<String, List<CreatePriceInfoDTO>> in : skuMap.entrySet()) {
            //根据物料编码删除配额
            String[] key = in.getKey().split("_");
            quotaManagementClient.deleteByMaterialCodeAndFactoryCode(key[0],key[1]);
//            String code = sequenceClient.createSequenceNo("quota_seq");
            String code = sequenceClient.getCodeSequenceNo("quota_seq", 3);
            final List<CreatePriceInfoDTO> list = in.getValue();
            final List<QuotaManagementParamClientDTO> quotaList = new ArrayList<>();
            final String pricePurchaseOrg = sysConfigClient.getTextConfig(SysConfigKey.PRICE_PURCHASE_ORG.getCode());
            final String pricePurchaseOrgCreateFactoryCode = sysConfigClient.getTextConfig(SysConfigKey.PRICE_PURCHASE_ORG_CREATE_FACTORY_CODE.getCode());
            final String[] factoryCodeList = StringUtils.split(pricePurchaseOrgCreateFactoryCode, ",");
            final List<QuotaManagementParamClientDTO> saveQuotaList = new ArrayList<>();
            final List<QuotaManagementParamClientDTO> saveQuotaListNew = new ArrayList<>();
            Map<String, String> factoryMap = new HashMap<>();
            for (CreatePriceInfoDTO createPriceInfoDTO : list) {
                QuotaManagementParamClientDTO quota = new QuotaManagementParamClientDTO();
                quota.setQuotaCode(code);
                quota.setSyncStatus(2);
                quota.setAuditStatus(0);
                quota.setDeleteFlag(0);
                quota.setValidFlag(0);
                quota.setFactoryCode(createPriceInfoDTO.getFactoryCode());
                quota.setMaterialCode(createPriceInfoDTO.getMaterialCode());
                quota.setMaterialName(createPriceInfoDTO.getMaterialName());
                quota.setSupplierCode(createPriceInfoDTO.getSupplierCode());
                quota.setSupplierName(createPriceInfoDTO.getSupplierName());
                quota.setQuota(createPriceInfoDTO.getQuota());
                quota.setReason(createPriceInfoDTO.getRemark());
                //取报价发起人的ID， 2024-10-24
//                quota.setCreater(1L);
                quota.setCreater(creater);
                quota.setCreateTime(LocalDateTime.now());
                quota.setEffectDate(createPriceInfoDTO.getEffectDate());
                quota.setInvalidDate(createPriceInfoDTO.getInvalidDate());
                quota.setProcurementType(createPriceInfoDTO.getPurchaseType());
                quota.setPriceInfoId(createPriceInfoDTO.getId());
                quota.setAdjustmentQuota(createPriceInfoDTO.getQuota());
                quota.setLeadTime(createPriceInfoDTO.getLeadTime());
                quota.setPaymentMethod(createPriceInfoDTO.getPaymentMethod());
                quotaList.add(quota);
                //判断采购组是否为2开头，并且供应商主数据是否有配置该工厂的物料信息
                if (createPriceInfoDTO.getPurchaseGroupCode().startsWith("2")) {
                    //查询该供应商下的物料配置表是否包含该工厂 2024-11-22 邓京术
                    Pair<String, SupplierPurchaseCategoryDTO> purchaseCategoryDTOPair = supplierClient.getSupplierPurchaseCategory(quota.getSupplierCode(), quota.getFactoryCode());
                    if (ObjectUtil.isNotEmpty(purchaseCategoryDTOPair.getValue()) && purchaseCategoryDTOPair.getValue().getCompanyCode().equals(quota.getFactoryCode())) {
                        saveQuotaList.add(quota);
                        saveQuotaListNew.add(quota);
                    }
                    factoryMap.put(quota.getFactoryCode(),quota.getFactoryCode());
                } else {
                    saveQuotaList.add(quota);
                    saveQuotaListNew.add(quota);
                }
            }
            if (!CollectionUtils.isEmpty(saveQuotaListNew)) {
                //这里做特殊判断，如果是集团内业务伙伴，则需要通过供应商编码后4位进行判断排除后4位工厂价格信息的扩充
                Set<String> factoryCodeSet = new HashSet<>(Arrays.asList(factoryCodeList));
                Iterator<QuotaManagementParamClientDTO> iterator = saveQuotaListNew.iterator();
                while (iterator.hasNext()) {
                    QuotaManagementParamClientDTO dto = iterator.next();
                    String supplierCode = dto.getSupplierCode();

                    if (supplierCode != null && supplierCode.length() > 4) {
                        // 截取最后4位
                        String lastFourDigits = supplierCode.substring(supplierCode.length() - 4);
                        // 检查比较列表中是否包含这4位数字
                        if (factoryCodeSet.contains(lastFourDigits)) {
                            // 如果存在匹配项，则从列表中删除当前DTO
                            iterator.remove();
                        }
                    }
                }
                if(!CollectionUtils.isEmpty(saveQuotaListNew)){
                    quotaManagementClient.saveQuota(saveQuotaListNew);
                }
            }
            if (pricePurchaseOrg.equals(purchaseOrgCode)&& "1000".equals(key[1])){
                for (String factoryCode:factoryCodeList) {
                    if (!factoryCode.equals(key[1])){
                        //代表该工厂，采购组为2开头
                        if (factoryMap.keySet().contains(factoryCode)) {
//                            String code1 = sequenceClient.createSequenceNo("quota_seq");
                            String code1 = sequenceClient.getCodeSequenceNo("quota_seq", 3);
                            List<QuotaManagementParamClientDTO> quotaList1 = new ArrayList<>();
                            quotaList.forEach(quotaManagementParamClientDTO -> {
                                QuotaManagementParamClientDTO expansionClass = new QuotaManagementParamClientDTO();
                                expansionClass = quotaManagementParamClientDTO;
                                //查询该供应商下的物料配置表是否包含该工厂 2024-11-21 邓京术
                                Pair<String, SupplierPurchaseCategoryDTO> purchaseCategoryDTOPair = supplierClient.getSupplierPurchaseCategory(quotaManagementParamClientDTO.getSupplierCode(), factoryCode);
                                if (ObjectUtil.isEmpty(purchaseCategoryDTOPair.getValue()) || !purchaseCategoryDTOPair.getValue().getCompanyCode().equals(factoryCode)) {
                                    String supplierGroup = supplierMap.get(quotaManagementParamClientDTO.getSupplierCode());
                                    if(!"Z001".equals(supplierGroup)){//正常供应商得数据需要保存
                                        expansionClass.setQuotaCode(code1);
                                        expansionClass.setFactoryCode(factoryCode);
                                        expansionClass.setId(null);
                                        expansionClass.setCreater(creater);
                                        quotaList1.add(expansionClass);
                                    }else{//供应商分组等于Z001集团内供应商得，只需要扩充不等于供应商编号后4为得工厂价格配额即可
                                        if(quotaManagementParamClientDTO.getSupplierCode().length() > 4){
                                            String lastFourChars = quotaManagementParamClientDTO.getSupplierCode().substring(quotaManagementParamClientDTO.getSupplierCode().length() - 4);
                                            if(!lastFourChars.equals(factoryCode)){
                                                //获取供应商工厂
                                                expansionClass.setQuotaCode(code1);
                                                expansionClass.setFactoryCode(factoryCode);
                                                expansionClass.setId(null);
                                                expansionClass.setCreater(creater);
                                                quotaList1.add(expansionClass);
                                            }
                                        }
                                    }
                                }
                            });
                            if (!CollectionUtils.isEmpty(quotaList1)) {
                                quotaManagementClient.saveQuota(quotaList1);
                            }
                        //对于采购组不是2开头的且如果工厂是1500，不同步配额信息到1500
                        } else if (!factoryCode.equals("1500")) {
//                            String code1 = sequenceClient.createSequenceNo("quota_seq");
                            String code1 = sequenceClient.getCodeSequenceNo("quota_seq", 3);
                            List<QuotaManagementParamClientDTO> quotaList1 = new ArrayList<>();
                            quotaList.forEach(quotaManagementParamClientDTO -> {
                                QuotaManagementParamClientDTO expansionClass = new QuotaManagementParamClientDTO();
                                expansionClass = quotaManagementParamClientDTO;
                                String supplierGroup = supplierMap.get(quotaManagementParamClientDTO.getSupplierCode());
                                if(!"Z001".equals(supplierGroup)){//正常供应商得数据需要保存
                                    expansionClass.setQuotaCode(code1);
                                    expansionClass.setFactoryCode(factoryCode);
                                    expansionClass.setId(null);
                                    expansionClass.setCreater(creater);
                                    quotaList1.add(expansionClass);
                                }else{//供应商分组等于Z001集团内供应商得，只需要扩充不等于供应商编号后4为得工厂价格配额即可
                                    if(quotaManagementParamClientDTO.getSupplierCode().length() > 4){
                                        String lastFourChars = quotaManagementParamClientDTO.getSupplierCode().substring(quotaManagementParamClientDTO.getSupplierCode().length() - 4);
                                        if(!lastFourChars.equals(factoryCode)){
                                            //获取供应商工厂
                                            expansionClass.setQuotaCode(code1);
                                            expansionClass.setFactoryCode(factoryCode);
                                            expansionClass.setId(null);
                                            expansionClass.setCreater(creater);
                                            quotaList1.add(expansionClass);
                                        }
                                    }
                                }
                            });
                            if (!CollectionUtils.isEmpty(quotaList1)) {
                                quotaManagementClient.saveQuota(quotaList1);
                            }

                        }
                        //不论是否采购组是2开头的还是， 不是2开头的且如果工厂是1500，都要进行集团内业务伙伴Z001判断

                    }
                }
            }
        }
    }


    /**
     * 当前服务是属于哪个oa流程
     *
     * @return
     */
    @Override
    public OaProcessType getProcessType() {
        return OaProcessType.INQUIRY_PRICE;
    }
}
