package com.jwipc.tender.logic.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.jwipc.api.OaCallBackLogic;
import com.jwipc.api.constant.OaStatus;
import com.jwipc.api.constant.RestCode;
import com.jwipc.api.dto.ApiResult;
import com.jwipc.constant.FlagConst;
import com.jwipc.constant.OaProcessType;
import com.jwipc.inquiry.client.PriceInfoClient;
import com.jwipc.inquiry.dto.CreatePriceInfoDTO;
import com.jwipc.sys.client.SequenceClient;
import com.jwipc.tender.constant.TenderStatus;
import com.jwipc.tender.convert.TenderConvert;
import com.jwipc.tender.entity.QuotaManagement;
import com.jwipc.tender.entity.Tender;
import com.jwipc.tender.logic.QuotaManagementLogic;
import com.jwipc.tender.logic.TenderLogic;
import com.jwipc.tender.model.po.TenderCreatePriceInfoPO;
import com.jwipc.tender.service.ITenderService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p> </p>
 *
 * @author ZhangJie
 * @version 1.0
 * @since JDK 1.8
 */
@Service("TenderPriceCallBack")
@RequiredArgsConstructor
public class TenderPriceCallBack implements OaCallBackLogic {
    private final ITenderService tenderService;
    private final PriceInfoClient priceInfoClient;
    private final QuotaManagementLogic quotaManagementLogic;
    private final SequenceClient sequenceClient;
    private final TenderConvert tenderConvert;
    private final TenderLogic tenderLogic;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApiResult processor(String workflowId, OaStatus status, String remark, String processCode, String data1,
                               String data2)
    {
        final Tender tender = tenderService.getOne(
                new LambdaQueryWrapper<Tender>().eq(Tender::getOaWorkId, workflowId));
        if (Objects.isNull(tender)) {
            return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("未找到匹配的流程数据!").build();
        }
        if (tender.getStatus() == TenderStatus.RATED.getStatus()) {
            return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("该流程数据已处理，不可重复提交!")
                    .build();
        }
        RestCode code = RestCode.SAP_SUCCESS;
        String mesg = "";
        try {
            if (status.equals(OaStatus.REFUSE)) {
                //根据定标的不同状态 ，更新标的驳回状态 2025-04-11 邓京术 如果是定标审批中的驳回，则状态改为定标驳回状态
                //定标驳回的状态类同，截止状态的操作。
                if (tender.getStatus().equals(TenderStatus.BIDING_APPR.getStatus())) {
                    tender.setStatus(TenderStatus.BIDING_APPR_REJECT.getStatus());
                } else {
                    tender.setStatus(TenderStatus.REJECT.getStatus());
                }
            } else if (status.equals(OaStatus.PASS)) {
                tender.setStatus(TenderStatus.RATED.getStatus());
                //根据询价id组装价格信息记录数据
                List<TenderCreatePriceInfoPO> createPriceInfoPOS = tenderService.getByTenderId(tender.getId());
                List<CreatePriceInfoDTO> createPriceInfoDTOS = tenderConvert.po2DtoList(createPriceInfoPOS);
                createPriceInfoDTOS.forEach(createPriceInfoDTO -> {
                    createPriceInfoDTO.setId(createPriceInfoDTO.getJoinQuoteFlag() ==
                            0 ? createPriceInfoDTO.getPriceInfoId() : IdWorker.getId());
                    //取询报价，投标发起人的 id 2024-10-21 邓京术
                    createPriceInfoDTO.setCreateUser(tender.getCreateId());
                });
                //只取参与报价的供应商
                priceInfoClient.createPriceInfo(createPriceInfoDTOS);
                tender.setGenPriceInfo(FlagConst.Y.getCode());
                //保存配额
                saveQuota(createPriceInfoDTOS);
            } else if (status.equals(OaStatus.DISCARDED)) {
                //废弃
                tenderLogic.toVoid(tender.getId());
            } else if (status.equals(OaStatus.RUNNING)) {
                tender.setStatus(TenderStatus.BIDING_APPR.getStatus());
            }
            tenderService.updateById(tender);
        } 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) {
        //根据物料编码分组
        Map<String, List<CreatePriceInfoDTO>> skuMap = createPriceInfoDTOS.stream()
                .collect(Collectors.groupingBy(CreatePriceInfoDTO::getMaterialCode));
        for (Map.Entry<String, List<CreatePriceInfoDTO>> in : skuMap.entrySet()) {
            //根据物料编码删除配额
            quotaManagementLogic.deleteByMaterialCode(in.getKey());
//            String code = sequenceClient.createSequenceNo("quota_seq");
            String code = sequenceClient.getCodeSequenceNo("quota_seq", 3);
            final List<CreatePriceInfoDTO> list = in.getValue();
            final List<QuotaManagement> quotaList = new ArrayList<>();
            for (CreatePriceInfoDTO createPriceInfoDTO : list) {
                QuotaManagement quota = new QuotaManagement();
                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());
                //生成配额，应该取报价招投的（采购）发起人
                quota.setCreater(createPriceInfoDTO.getCreateUser()==null?1l:createPriceInfoDTO.getCreateUser());
                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);
            }
            quotaManagementLogic.saveQuota(quotaList);
        }
    }

    @Override
    public OaProcessType getProcessType() {
        return OaProcessType.TENDER_PRICE;
    }
}
