package com.jwipc.inquiry.logic.impl;

import cn.hutool.core.bean.BeanUtil;
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.exception.DaoException;
import com.jwipc.inquiry.constant.AuditStatus;
import com.jwipc.inquiry.constant.SequenceConst;
import com.jwipc.inquiry.constant.SysConfigKey;
import com.jwipc.inquiry.convert.PriceInfoConvert;
import com.jwipc.inquiry.entity.PriceInfo;
import com.jwipc.inquiry.entity.PriceInfoAudit;
import com.jwipc.inquiry.model.po.CreatePriceInfoPO;
import com.jwipc.inquiry.service.IPriceInfoAuditService;
import com.jwipc.inquiry.service.IPriceInfoService;
import com.jwipc.sys.client.ExchangeRateClient;
import com.jwipc.sys.client.SequenceClient;
import com.jwipc.sys.client.SysConfigClient;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @author shenyang.ou
 * @date 2024/4/1 14:39
 * @desc 扣款审批回调
 */
@Service("AuditPriceCallBack")
@RequiredArgsConstructor
public class AuditPriceCallBack implements OaCallBackLogic {
    private final IPriceInfoAuditService priceInfoAuditService;
    private final IPriceInfoService priceInfoService;
    private final PriceInfoConvert priceInfoConvert;
    private final SequenceClient sequenceClient;
    private final ExchangeRateClient exchangeRateClient;
    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 PriceInfoAudit priceInfoAudit = priceInfoAuditService.getOne(
                new LambdaQueryWrapper<PriceInfoAudit>().eq(PriceInfoAudit::getProcessId, workflowId));


        if (Objects.isNull(priceInfoAudit)) {
            return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("未找到匹配的流程数据!").build();
        }
        if (priceInfoAudit.getStatus()== AuditStatus.PASS.getStatus()){
            return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("该流程数据已处理，不可重复提交!").build();
        }
        RestCode code = RestCode.SAP_SUCCESS;
        String mesg = "";
        try {
            if (status.equals(OaStatus.REFUSE)) {
                priceInfoAudit.setStatus(AuditStatus.REFUSE.getStatus());
            } else if (status.equals(OaStatus.PASS)){
                priceInfoAudit.setStatus(AuditStatus.PASS.getStatus());
                //生成价格信息记录
                //根据询价id组装价格信息记录数据
                List<CreatePriceInfoPO> createPriceInfoPOS = priceInfoService.getByAuditId(priceInfoAudit.getId());
                createPriceInfoPOS.forEach(createPriceInfoDTO -> {
                    createPriceInfoDTO.setId(null);
                    createPriceInfoDTO.setCreateUser(1L);
                    createPriceInfoDTO.setCreateTime(LocalDateTime.now());
                    //获取税率
                    BigDecimal exchangeRate = exchangeRateClient.getExchangeRate(createPriceInfoDTO.getCurrencyCode(),"CNY");
                    createPriceInfoDTO.setExchangeRate(exchangeRate==null?BigDecimal.ONE:exchangeRate);
                });
                List<PriceInfo> priceInfos = priceInfoConvert.po2EntityList(createPriceInfoPOS);
//                priceInfos.forEach(priceInfo -> {
//                    priceInfo.setPriceCode(sequenceClient.createSequenceNo(SequenceConst.PRICE_INFO_CODE.getCode()));
//                    priceInfo.setCreateTime(LocalDateTime.now());
//                });
                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, ",");
                for (PriceInfo priceInfo : priceInfos){
                    priceInfo.setCreateTime(LocalDateTime.now());
                    priceInfo.setPriceCode(sequenceClient.createSequenceNo(SequenceConst.PRICE_INFO_CODE.getCode()));
                    if (priceInfo.getNoTaxPrice()==null){
                        throw new DaoException("未税价格为空");
                    }
                    if (priceInfo.getExchangeRate()==null){
                        throw new DaoException("汇率为空");
                    }
                    priceInfo.setConversionPrice(priceInfo.getNoTaxPrice().multiply(priceInfo.getExchangeRate()));
                    priceInfo.setCreateTime(LocalDateTime.now());
                    priceInfoService.save(priceInfo);
                    if (pricePurchaseOrg.equals(priceInfo.getPurchaseOrgCode())&& "1000".equals(priceInfo.getFactoryCode())){
                        for (String factoryCode:factoryCodeList){
                            boolean su = priceInfos.stream().anyMatch(f -> priceInfo.getMaterialCode().equals(f.getMaterialCode())
                                    &&priceInfo.getSupplierCode().equals(f.getSupplierCode())
                                    &&pricePurchaseOrg.equals(f.getPurchaseOrgCode())
                                    &&factoryCode.equals(f.getFactoryCode()));
                            if (!su){
                                PriceInfo priceInfo1 = new PriceInfo();
                                BeanUtil.copyProperties(priceInfo,priceInfo1);
                                priceInfo1.setId(IdWorker.getId());
                                priceInfo1.setFactoryCode(factoryCode);
                                priceInfo1.setPriceCode(sequenceClient.createSequenceNo(SequenceConst.PRICE_INFO_CODE.getCode()));
                                priceInfoService.save(priceInfo1);
                            }
                        }
                    }
                }
//                priceInfoService.saveBatch(priceInfos);

            }
            else if (status.equals(OaStatus.DISCARDED)){
                priceInfoAudit.setStatus(AuditStatus.REJECT.getStatus());
            } else if (status.equals(OaStatus.RUNNING)){
                priceInfoAudit.setStatus(AuditStatus.APPROVAL.getStatus());
            }
            priceInfoAuditService.updateById(priceInfoAudit);
        } catch (Exception e) {
            code = RestCode.SAP_ERROR;
            mesg = e.getMessage();
            e.printStackTrace();
        }
        return ApiResult.builder().code(code.getCode()).message(mesg).build();
    }

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