package com.jwipc.contract.logic.impl;

import cn.hutool.core.util.StrUtil;
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.OaCallBackLogic;
import com.jwipc.api.constant.OaStatus;
import com.jwipc.api.constant.RestCode;
import com.jwipc.api.dto.ApiResult;
import com.jwipc.constant.OaProcessType;
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.log.annotation.ApiOperateLog;
import com.jwipc.log.constant.ApiDirection;
import com.jwipc.log.constant.ThirdSysType;
import com.jwipc.supplier.client.TenderClient;
import com.jwipc.tender.client.dto.TenderDetailByIdDetailDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 功能描述:
 *
 * @Author: zx
 * @Date: 2024/3/21 0021 16:18
 */
@RequiredArgsConstructor
@Service("ContractCallBack")
@Slf4j
public class ContractCallBackImpl implements OaCallBackLogic {

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


    @Override
//    @ApiOperateLog(code = "contractManageCallBack", name = "合同推送审批结果回传", direction = ApiDirection.OTHER_TO_SRM,
//            thirdSysType = ThirdSysType.OA)
    public ApiResult processor(String workflowId, OaStatus status, String remark, String processCode, String data1,
                               String data2)
    {
        //0：同意 1：拒绝  2:审批中  3:废弃
        Contract contract = contractService.getOne(
                new LambdaQueryWrapper<Contract>().eq(Contract::getOaProcessId, workflowId));
        if (Objects.isNull(contract)) {
            throw new DaoException("未找到匹配流程!");
        }
        if (status.getStatus() == OaStatus.PASS.getStatus()) {
            contract.setContractState(3);
            contract.setOrderCode(data1);
            //需要json转换
            final JSONArray jsonArray = JSON.parseArray(data2);
            List<ContractDetail> updateLists = Lists.newArrayList();
            for (Object o : jsonArray) {
                JSONObject jsonObject = (JSONObject) o;
                if (Objects.nonNull(jsonObject) &&
                        Objects.nonNull(jsonObject.get("AssetSerialNumber")) &&
                        Objects.nonNull(jsonObject.get("AssetNumber"))) {
                    final String id = jsonObject.getString("AssetSerialNumber");
                    final String assetNumber = jsonObject.getString("AssetNumber");
                    ContractDetail contractDetail = new ContractDetail();
                    contractDetail.setId(Long.parseLong(id));
                    contractDetail.setCardNumber(assetNumber);
                    updateLists.add(contractDetail);
                }
            }

        }
        if (status.getStatus() == OaStatus.RUNNING.getStatus()) {
            //需要json转换
            final JSONArray jsonArray = JSON.parseArray(data2);
            for (Object o : jsonArray) {
                JSONObject jsonObject = (JSONObject) o;
                if (Objects.nonNull(jsonObject.get("upFlag"))){
                    final String upFlag = jsonObject.getString("upFlag");
                    if ("1".equals(upFlag)){
                        contract.setContractSignFileStatue(ContractConst.MANUALING);
                    }
                }
            }

        }
        if (status.getStatus() == OaStatus.REFUSE.getStatus()) {
            contract.setContractState(4);
        }
        if (status.getStatus() == OaStatus.DISCARDED.getStatus()) {
            contract.setContractState(6);
        }
        contractService.updateById(contract);

        //如果合同被废弃，则须把之前的转合同数量置为初始状态 2024-10-29 邓京术
        //根据合同是 0 自建 ， 1 招标  ， 2 询价  3 批量询价生成的合同
        //为了不影响之前的操作，Try catch 包起来
        try {
            if (status.getStatus() == OaStatus.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 OaProcessType getProcessType() {
        return OaProcessType.CONTRACT_CHANGE;
    }

}
