package com.fjhx.sale.flow;

import cn.hutool.extra.spring.SpringUtil;
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.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.file.utils.ObsFileUtil;
import com.fjhx.flow.core.FlowDelegate;
import com.fjhx.flow.enums.FlowStatusEnum;
import com.fjhx.sale.entity.serviceContract.dto.ServiceContractDto;
import com.fjhx.sale.entity.serviceContract.po.ServiceContract;
import com.fjhx.sale.entity.serviceContract.po.ServiceContractPay;
import com.fjhx.sale.entity.serviceContract.po.ServiceContractProduct;
import com.fjhx.sale.enums.ServiceContractEnum;
import com.fjhx.sale.service.serviceContract.ServiceContractPayService;
import com.fjhx.sale.service.serviceContract.ServiceContractProductService;
import com.fjhx.sale.service.serviceContract.ServiceContractService;
import com.ruoyi.common.core.domain.BasePo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 * 服务合同流程
 */
@DS(SourceConstant.SALE)
@Component
public class ServiceContractFlow extends FlowDelegate {

    @Autowired
    private CodingRuleService codingRuleService;

    @Autowired
    private ServiceContractService serviceContractService = SpringUtil.getBean(ServiceContractService.class);
    @Autowired
    private ServiceContractPayService serviceContractPayService = SpringUtil.getBean(ServiceContractPayService.class);
    @Autowired
    private ServiceContractProductService serviceContractProductService = SpringUtil.getBean(ServiceContractProductService.class);

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

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

        //添加服务合同编码
        contract.setCode(codingRuleService.createCode(CodingRuleEnum.SERVICE_CONTRACT.getKey(), contract.getBuyCorporationId()));
        //调用公共代码
        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) {
        ServiceContractService contractService = SpringUtil.getBean(ServiceContractService.class);
        //通过业务ID查询合同数据
        ServiceContract contract = contractService.getById(businessId);
        if (ObjectUtils.isEmpty(contract)) {
            throw new ServiceException("服务合同不存在");
        }
        //修改采购状态为审批通过
        contract.setStatus(ServiceContractEnum.PASS.getKey());
        contractService.updateById(contract);
    }

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

        ServiceContractDto contract = submitData.toJavaObject(ServiceContractDto.class);
        commStart(contract, 1);
    }

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

        serviceContractService.update(q -> q
                .eq(ServiceContract::getId, businessId)
                .set(ServiceContract::getStatus, FlowStatusEnum1.REJECT.getKey())
                .set(BasePo::getUpdateTime, new Date())
                .set(BasePo::getUpdateUser, SecurityUtils.getUserId())
        );
    }

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

    /**
     * 开始公共代码抽取
     *
     * @param opType 操作类型 0直接发起 1重新发起
     */
    private ServiceContractDto commStart(ServiceContractDto contract, Integer opType) {
        if (opType == 1) {
            Assert.notEmpty(contract.getId(), "服务合同id不能为空");
        }
        //赋值城市省份信息
        CustomizeAreaUtil.setAreaId(contract);

        contract.setBuyCityId(contract.getCityId());
        contract.setBuyCountryId(contract.getCountryId());
        contract.setBuyProvinceId(contract.getProvinceId());

        //添加服务合同状态
        contract.setStatus(ServiceContractEnum.UNDER_REVIEW.getKey());
        //添加服务合同信息
        serviceContractService.saveOrUpdate(contract);
        List<ServiceContractProduct> serviceContractProductList = contract.getServiceContractProductList();
        if (CollectionUtils.isNotEmpty(serviceContractProductList)) {//保存报价产品信息
            if (opType == 1) {
                //先处理被删除的数据
                serviceContractProductService.editLinked(serviceContractProductList, ServiceContractProduct::getServiceContractId, contract.getId());
            }

            serviceContractProductList.forEach(serviceContractProduct -> serviceContractProduct.setServiceContractId(contract.getId()));
            serviceContractProductService.saveOrUpdateBatch(serviceContractProductList);
        }
        List<ServiceContractPay> serviceContractPayList = contract.getServiceContractPayList();
        if (CollectionUtils.isNotEmpty(serviceContractPayList)) {//保存报价项目信息
            if (opType == 1) {
                //先处理被删除的数据
                serviceContractPayService.editLinked(serviceContractPayList, ServiceContractPay::getServiceContractId, contract.getId());
            }

            serviceContractPayList.forEach(contractPay -> contractPay.setServiceContractId(contract.getId()));
            serviceContractPayService.saveOrUpdateBatch(serviceContractPayList);
        }
        if (opType == 1) {
            //重新发起编辑
            // 交接单附件列表
            ObsFileUtil.editFile(contract.getFileList(), contract.getId(), 1);
        } else {
            //普通提交新增
            // 交接单附件列表
            ObsFileUtil.saveFile(contract.getFileList(), contract.getId(), 1);
        }

        return contract;
    }

}
