package com.fjhx.sale.flow;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
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.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.entity.purchase.dto.EhsdPurchaseDto;
import com.fjhx.sale.entity.sample.po.Sample;
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.annotation.LogicIgnore;
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 org.springframework.transaction.annotation.Transactional;

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

/**
 * 外销合同流程
 *
 * @Author:caozj
 * @DATE:2023/4/3 17:38
 */
@Component
@DS(SourceConstant.SALE)
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);
        if(StringUtils.isEmpty(contract.getCurrency())){
            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()));
        }

        return start(contract);
    }

    /**
     * 结束流程
     *
     * @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);
    }

    public Long start(ContractDto contract) {
        // 赋值城市省份信息
        CustomizeAreaUtil.setAreaId(contract);
        SysUser loginUser = SecurityUtils.getLoginUser().getUser();
        contract.setUserName(loginUser.getNickName());
        contract.setBuyCityId(contract.getCityId());
        contract.setBuyCountryId(contract.getCountryId());
        contract.setBuyProvinceId(contract.getProvinceId());
        contract.setStatus(FlowStatusEnum1.UNDER_REVIEW.getKey());
//        contract.setRate(ExchangeRateUtil.getCnyToCodeRate(contract.getCurrency()));
        contractService.saveOrUpdate(contract);

        // 保存合同产品
        List<ContractProduct> contractProductList = contract.getContractProductList();
        if (CollectionUtils.isNotEmpty(contractProductList)) {
            for (ContractProduct c : contractProductList) {
                c.setContractId(contract.getId());
            }
            contractProductService.saveOrUpdateBatch(contractProductList);
        }

        // 保存收费项目
        List<ContractProject> contractProjectList = contract.getContractProjectList();
        if (CollectionUtils.isNotEmpty(contractProjectList)) {
            for (ContractProject c : contractProjectList) {
                c.setContractId(contract.getId());
            }
            contractProjectService.saveOrUpdateBatch(contractProjectList);
        }

        // 保存自定义出货
        List<ContractShipment> contractShipmentList = contract.getContractShipmentList();
        if (CollectionUtils.isNotEmpty(contractShipmentList)) {
            for (ContractShipment c : contractShipmentList) {
                c.setContractId(contract.getId());
            }
            contractShipmentService.saveOrUpdateBatch(contractShipmentList);
        }

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

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

        return contract.getId();
    }

    /**
     * 重新发起
     * @param flowId
     * @param businessId
     * @param flowStatus
     * @param submitData
     */
    @Override
    @LogicIgnore(tableName = {""},alias = {""})
    @Transactional(rollbackFor = Exception.class)
    public void relaunch(Long flowId, Long businessId, FlowStatusEnum flowStatus, JSONObject submitData) {
        //删除采购合同
        ContractDto contractDto = submitData.toJavaObject(ContractDto.class);
        if(ObjectUtils.isEmpty(contractDto)){
            throw new ServiceException("合同数据不能为空");
        }
        start(contractDto);
    }

    /**
     * 驳回
     * @param flowId
     * @param businessId
     * @param flowStatus
     */
    @Override
    public void reject(Long flowId, Long businessId, FlowStatusEnum flowStatus) {
        if (HandleTypeEnum.REJECT.equals(FlowThreadLocalUtil.getHandleTypeEnum())) {
            contractService.update(q -> q
                    .eq(Contract::getId, FlowThreadLocalUtil.getBusinessId())
                    .set(Contract::getStatus, 20)//20为驳回
                    .set(Contract::getUpdateTime, new Date())
                    .set(BasePo::getUpdateUser, SecurityUtils.getUserId())
            );
        }
    }
}
