package com.jwipc.contract.logic.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.jwipc.api.ShareCallBackLogic;
import com.jwipc.api.constant.RestCode;
import com.jwipc.api.constant.ShareContractStatus;
import com.jwipc.api.constant.ShareStatus;
import com.jwipc.api.dto.ApiResult;
import com.jwipc.log.dto.ShareCallBackDTO;
import com.jwipc.constant.ShareProcessType;
import com.jwipc.contract.constant.ContractConst;
import com.jwipc.contract.entity.Contract;
import com.jwipc.contract.entity.ContractDetail;
import com.jwipc.contract.service.IContractService;
import com.jwipc.exception.DaoException;
import com.jwipc.inquiry.client.InquiryClient;
import com.jwipc.supplier.client.TenderClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 功能描述:资产合同回调
 *
 * @Author: 邓京术
 * @Date: 2025/12/05 0021 16:18
 */
@RequiredArgsConstructor
@Service("ContractShareCallBack")
@Slf4j
public class ContractShareCallBackImpl implements ShareCallBackLogic {

    @Autowired
    IContractService contractService;
    @Autowired
    TenderClient tenderClient;
    @Autowired
    InquiryClient inquiryClient;


    @Override
    public ApiResult processor(String workflowId, ShareStatus status, String remark,
                               String processCode, String data1, String jsonData, String data,String data2)
    {
        //1、0 | 暂存
        //2、1 | 待提交
        //3、2 | 审批中
        //4、3 | 通过
        //5、4 | 驳回
        //6、7 | 终止
        //6、8 | 终止驳回
        // 合同终止的情况
        Contract contract = contractService.getOne(
                new LambdaQueryWrapper<Contract>().eq(Contract::getOaProcessId, workflowId));
        if (Objects.isNull(contract)) {
            return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("未找到匹配流程!").build();
        }
        contract.setContractState(status.getStatus());
        if (status.getStatus() == ShareContractStatus.PASS.getStatus()) {
            // 通过
            contract.setUpdateTime(new Date().toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDateTime());
            if(StringUtils.isEmpty(data2)){
                return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("数据不完整!").build();
            }
            ShareCallBackDTO.ItData itData = JSONObject.parseObject(data2, ShareCallBackDTO.ItData.class);
            JSONObject jsonObj = itData.getExtension();
            Object dataSourcesNo = jsonObj.get("extension1");
            if(ObjectUtil.isEmpty(dataSourcesNo)){
                return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("共享合同评审单号不能为空!").build();
            }
            Object isRaise = jsonObj.get("extension2");
            if(ObjectUtil.isEmpty(isRaise)){
                return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("是否使用募集资金不能为空!").build();
            }
            Object department = jsonObj.get("extension3");
            if(ObjectUtil.isEmpty(department)){
                return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("申请部门不能为空!").build();
            }
            contract.setIsRaise((int)isRaise);
            contract.setOaCode((String)dataSourcesNo);
            contract.setContractDemandUserDept((String)department);

        }

        contractService.updateById(contract);
        // 1、”发起终止“审批通过后，如果被终止的合同有变更合同，那么，对应的变更合同的合同状态也需要更新为“终止”；
        if (StringUtils.equals("08", contract.getContractType()) && status.getStatus() == ShareContractStatus.PASS.getStatus()) {
            // 找到被终止合同
            List<Contract> targetContractList = contractService.list(new LambdaQueryWrapper<Contract>()
                    .eq(Contract::getContractCode, contract.getAssociationContract()));
            if (CollectionUtils.isNotEmpty(targetContractList)) {
                List<Contract> updateSubContractList = Lists.newArrayList();
                Contract targetContract = targetContractList.get(0);
                // 被终止合同状态为终止
                updateSubContractList.add(targetContract);
                // 判断合同类型
                if (!StringUtils.equals(targetContract.getContractType(), "07")) {
                    // 如果是主合同，找到所有变更合同
                    List<Contract> changeContractList = contractService.list(new LambdaQueryWrapper<Contract>()
                            .eq(Contract::getAssociationContract, targetContract.getContractCode())
                            .eq(Contract::getContractType, "07")
                            .eq(Contract::getDeleteFlag, "0"));
                    if (CollectionUtils.isNotEmpty(changeContractList)) {
                        updateSubContractList.addAll(changeContractList);
                    }
                }
                for (Contract subContract : updateSubContractList) {
                    // 全部为终止
                    subContract.setContractState(7);
                }
                contractService.saveOrUpdateBatch(updateSubContractList);
            }
        }

        //如果合同被废弃，则须把之前的转合同数量置为初始状态 2024-10-29 邓京术
        //根据合同是 0 自建 ， 1 招标  ， 2 询价  3 批量询价生成的合同
        //为了不影响之前的操作，Try catch 包起来
        try {
            if (status.getStatus() == ShareStatus.DISCARDED.getStatus()) {
                switch (contract.getDataSources()) {
                    case 0:
                        if (contract.getDataSourcesId() != null && StringUtils.isNotEmpty(contract.getDataSourcesNo())) {
                            if (contract.getDataSourcesNo().contains("RFQ")) {
                                inquiryClient.updateConStateByNos(contract.getDataSourcesNo(), contract.getContractSupplierCode(),0);
                            } else {
                                tenderClient.updateConState(contract.getDataSourcesId(), 0);
                            }
                        }
                        break;
                    case 1:
                        tenderClient.updateConState(contract.getDataSourcesId(), 0);
                        break;
                    case 2:
                        inquiryClient.updateConState(contract.getDataSourcesId(), 0);
                        break;
                    case 3:
                        inquiryClient.updateConStateByNos(contract.getDataSourcesNo(), contract.getContractSupplierCode(),0);
                        break;
                    default:
                        break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("{}", "SupplierChangeCallback");
        log.info("{}", workflowId);
        return ApiResult.builder().code(RestCode.SAP_SUCCESS.getCode()).build();
    }

    @Override
    public ShareProcessType getProcessType() {
        return ShareProcessType.CONTRACT_MRO;
    }

}
