package com.fjhx.sale.flow;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.fjhx.area.utils.CustomizeAreaUtil;
import com.fjhx.common.constant.SourceConstant;
import com.fjhx.common.enums.CodingRuleEnum;
import com.fjhx.common.enums.FlowStatusEnum1;
import com.fjhx.common.service.coding.CodingRuleService;
import com.fjhx.common.utils.Assert;
import com.fjhx.common.utils.ExchangeRateUtil;
import com.fjhx.file.utils.ObsFileUtil;
import com.fjhx.flow.core.FlowDelegate;
import com.fjhx.flow.core.FlowThreadLocalUtil;
import com.fjhx.flow.enums.FlowStatusEnum;
import com.fjhx.flow.enums.HandleTypeEnum;
import com.fjhx.sale.entity.contract.dto.ContractDto;
import com.fjhx.sale.entity.contract.po.Contract;
import com.fjhx.sale.entity.contract.po.ContractProduct;
import com.fjhx.sale.entity.contract.po.ContractProject;
import com.fjhx.sale.entity.contract.po.ContractShipment;
import com.fjhx.sale.service.contract.ContractProductService;
import com.fjhx.sale.service.contract.ContractProjectService;
import com.fjhx.sale.service.contract.ContractService;
import com.fjhx.sale.service.contract.ContractShipmentService;
import com.ruoyi.common.core.domain.BasePo;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 外销合同流程
 *
 * @Author:caozj
 * @DATE:2023/4/3 17:38
 */
@Component
public class ContractFlow extends FlowDelegate {

    @Autowired
    private CodingRuleService codingRuleService;

    @Autowired
    private ContractService contractService;

    @Autowired
    private ContractProductService contractProductService;

    @Autowired
    private ContractProjectService contractProjectService;

    @Autowired
    private ContractShipmentService contractShipmentService;

    @Override
    public String getFlowKey() {
        return "contract_flow";
    }

    /**
     * 发起流程
     *
     * @param flowId     流程ID
     * @param submitData 采购付款数据
     * @return 业务id
     */
    @Override
    public Long start(Long flowId, JSONObject submitData) {
        ContractDto contract = submitData.toJavaObject(ContractDto.class);

        contract.setIssue("1");//默认直接下发到交接单

        contract.setFlowId(flowId);

        if (StringUtils.isEmpty(contract.getCurrency())) {
            throw new ServiceException("币种不能为空");
        }
        if (ObjectUtil.isEmpty(contract.getBuyCorporationId())) {
            throw new ServiceException("客户不能为空");
        }

        //赋值合同号
        contract.setCode(codingRuleService.createCode(CodingRuleEnum.CONTRACT.getKey(), contract.getBuyCorporationId()));

        // 保存合同产品
        List<ContractProduct> contractProductList = contract.getContractProductList();

        // 赋值待处理数量
        if (CollectionUtils.isNotEmpty(contractProductList)) {
            contractProductList.forEach(item -> item.setExpendQuantity(item.getQuantity()));
        }

        contract = commStart(contract, 0);
        return contract.getId();
    }

    /**
     * 结束流程
     *
     * @param flowId     流程ID
     * @param businessId 业务ID
     * @param submitData 数据
     */
    @Override
    public void end(Long flowId, Long businessId, JSONObject submitData) {

        // 通过业务ID查询合同数据
        Contract contract = contractService.getById(businessId);

        if (ObjectUtils.isEmpty(contract)) {
            throw new ServiceException("合同不存在");
        }

        // 修改采购状态为审批通过
        contract.setStatus(FlowStatusEnum1.PASS.getKey());
        contract.setApprovedDate(new Date());
        contractService.updateById(contract);
    }

    @Override
    public void relaunch(Long flowId, Long businessId, FlowStatusEnum flowStatus, JSONObject submitData) {
        super.relaunch(flowId, businessId, flowStatus, submitData);
        reStart();
    }

    @Override
    public void reject(Long flowId, Long businessId, FlowStatusEnum flowStatus) {
        super.reject(flowId, businessId, flowStatus);
        reject();
    }

    @Override
    public void cancellation(Long flowId, Long businessId, FlowStatusEnum flowStatus) {
        super.cancellation(flowId, businessId, flowStatus);
        contractService.update(q -> q
                .eq(Contract::getId, businessId)
                .set(Contract::getStatus, FlowStatusEnum1.CANCELLATION.getKey())
                .set(BasePo::getUpdateTime, new Date())
                .set(BasePo::getUpdateUser, SecurityUtils.getUserId())
        );
    }

    /**
     * 开始公共代码抽取
     *
     * @param opType 操作类型 0直接发起 1重新发起
     */
    public ContractDto commStart(ContractDto contract, Integer opType) {
        DynamicDataSourceContextHolder.push(SourceConstant.SALE);

//        long contractId = IdWorker.getId();

        // 赋值城市省份信息
        CustomizeAreaUtil.setAreaId(contract);

//        contract.setId(contractId);
        SysUser user = SecurityUtils.getLoginUser().getUser();
        contract.setUserName(user.getNickName());
        contract.setStatus(FlowStatusEnum1.UNDER_REVIEW.getKey());
        contract.setBuyCityId(contract.getCityId());
        contract.setBuyCountryId(contract.getCountryId());
        contract.setBuyProvinceId(contract.getProvinceId());
        contract.setRate(ExchangeRateUtil.getCnyToCodeRate(contract.getCurrency()));
        contractService.saveOrUpdate(contract);

        // 保存合同产品
        List<ContractProduct> contractProductList = contract.getContractProductList();
        if (CollectionUtils.isNotEmpty(contractProductList)) {

            if (opType == 1) {
                //先删除被删除的产品
                contractProductService.editLinked(contractProductList, ContractProduct::getContractId, contract.getId());
            }
            for (ContractProduct c : contractProductList) {
//                c.setId(IdWorker.getId());
                c.setContractId(contract.getId());
//                ObsFileUtil.saveFile(c.getFileList(), c.getId());
            }
            contractProductService.saveOrUpdateBatch(contractProductList);
        }

        // 保存收费项目
        List<ContractProject> contractProjectList = contract.getContractProjectList();
        if (CollectionUtils.isNotEmpty(contractProjectList)) {
            if (opType == 1) {
                //先删除被删除的产品
                contractProjectService.editLinked(contractProjectList, ContractProject::getContractId, contract.getId());
            }

            for (ContractProject c : contractProjectList) {
//                c.setId(IdWorker.getId());
                c.setContractId(contract.getId());
            }
            contractProjectService.saveOrUpdateBatch(contractProjectList);
        }

        // 保存自定义出货
        List<ContractShipment> contractShipmentList = contract.getContractShipmentList();
        if (CollectionUtils.isNotEmpty(contractShipmentList)) {
            if (opType == 1) {
                //先删除被删除的产品
                contractShipmentService.editLinked(contractShipmentList, ContractShipment::getContractId, contract.getId());
            }
            for (ContractShipment c : contractShipmentList) {
//                c.setId(IdWorker.getId());
                c.setContractId(contract.getId());
            }
            contractShipmentService.saveOrUpdateBatch(contractShipmentList);
        }

        if (opType == 1) {
            //重新发起编辑

            // 交接单附件列表
            ObsFileUtil.editFile(contract.getFileList(), contract.getId(), 1);

            // 包装指示附件列表
            ObsFileUtil.editFile(contract.getPackageFileList(), contract.getId(), 2);
        } else {
            //普通提交新增

            // 交接单附件列表
            ObsFileUtil.saveFile(contract.getFileList(), contract.getId(), 1);

            // 包装指示附件列表
            ObsFileUtil.saveFile(contract.getPackageFileList(), contract.getId(), 2);
        }
        DynamicDataSourceContextHolder.poll();


        return contract;
    }

    /**
     * 重新发起
     */
    public void reStart() {
        JSONObject submitData = FlowThreadLocalUtil.getCurrentData();
        ContractDto contract = submitData.toJavaObject(ContractDto.class);
        reStart1(contract);
    }

    public void reStartUpdate(ContractDto contract) {
        if (StringUtils.isEmpty(contract.getCurrency())) {
            throw new ServiceException("币种不能为空");
        }
        // 保存合同产品
        List<ContractProduct> contractProductList = contract.getContractProductList();

        // 赋值待处理数量
        if (CollectionUtils.isNotEmpty(contractProductList)) {
            contractProductList.forEach(item -> item.setExpendQuantity(item.getQuantity()));
        }

        //调用公共代码
        commStart(contract, 1);
    }

    public void reStart1(ContractDto contract) {
        Long contractId = contract.getId();
        Assert.notEmpty(contractId, "合同id不能为空");

        if (StringUtils.isEmpty(contract.getCurrency())) {
            throw new ServiceException("币种不能为空");
        }
        // 保存合同产品
        List<ContractProduct> contractProductList = contract.getContractProductList();

        // 赋值待处理数量
        if (CollectionUtils.isNotEmpty(contractProductList)) {
            contractProductList.forEach(item -> item.setExpendQuantity(item.getQuantity()));
        }

        //调用公共代码
        commStart(contract, 1);
    }

    /**
     * 驳回方法
     */
    public void reject() {
        if (HandleTypeEnum.REJECT.equals(FlowThreadLocalUtil.getHandleTypeEnum())) {
            contractService.update(q -> q
                    .eq(Contract::getId, FlowThreadLocalUtil.getBusinessId())
                    .set(Contract::getStatus, FlowStatusEnum1.REJECT.getKey())//20为驳回
                    .set(BasePo::getUpdateTime, new Date())
                    .set(BasePo::getUpdateUser, SecurityUtils.getUserId())
            );
        }
    }

}
