package com.fjhx.account.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.ObjectUtils;
import com.fjhx.account.entity.account.dto.AccountPaymentDto;
import com.fjhx.account.entity.account.dto.AccountRequestFundsDto;
import com.fjhx.account.entity.account.enums.AccountRequestFundsStatusEnum;
import com.fjhx.account.entity.account.enums.PaymentStatusEnum;
import com.fjhx.account.entity.account.po.AccountRequestFunds;
import com.fjhx.account.entity.account.po.AccountRequestFundsDetail;
import com.fjhx.account.service.account.AccountPaymentService;
import com.fjhx.account.service.account.AccountRequestFundsDetailService;
import com.fjhx.account.service.account.AccountRequestFundsService;
import com.fjhx.common.constant.SourceConstant;
import com.fjhx.common.enums.FlowStatusEnum1;
import com.fjhx.common.utils.Assert;
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.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.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 请款流程
 *
 * @Author:caozj
 * @DATE:2023/4/3 17:38
 */
@DS(SourceConstant.ACCOUNT)
@Component
public class AccountRequestFundsFlow extends FlowDelegate {

    @Autowired
    private AccountPaymentService accountPaymentService;

    @Autowired
    private AccountRequestFundsService accountRequestFundsService;

    @Autowired
    private AccountRequestFundsDetailService accountRequestFundsDetailService;

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


    /**
     * 发起流程
     *
     * @param flowId     流程ID
     * @param submitData 请款表信息
     * @return
     */
    @Override
    public Long start(Long flowId, JSONObject submitData) {
//
//        // 获取提交数据
//        AccountRequestFundsDto accountRequestFundsDto = submitData.toJavaObject(AccountRequestFundsDto.class);
//
//        // 添加请款表的信息
//        accountRequestFundsDto.setStatus(AccountRequestFundsStatusEnum.UNDER_REVIEW.getKey());
//        accountRequestFundsService.save(accountRequestFundsDto);
//
//        // 添加请款详情表的信息
//        List<AccountRequestFundsDetail> accountRequestFundsDetailList = accountRequestFundsDto.getAccountRequestFundsDetailList();
//        if (CollectionUtils.isNotEmpty(accountRequestFundsDetailList)) {
//            accountRequestFundsDetailList.forEach(item -> item.setAccountRequestFundsId(accountRequestFundsDto.getId()));
//            accountRequestFundsDetailService.saveBatch(accountRequestFundsDetailList);
//        }
//
//        // 添加附件信息
//        ObsFileUtil.saveFile(accountRequestFundsDto.getFileList(), accountRequestFundsDto.getId());
//
//        return accountRequestFundsDto.getId();

        // 获取提交数据
        AccountRequestFundsDto accountRequestFundsDto = submitData.toJavaObject(AccountRequestFundsDto.class);

        accountRequestFundsDto = commStart(accountRequestFundsDto, 0);

        return accountRequestFundsDto.getId();
    }

    /**
     * 结束流程
     *
     * @param flowId     流程ID
     * @param businessId 业务ID
     * @param submitData 请款表信息
     */
    @Override
    public void end(Long flowId, Long businessId, JSONObject submitData) {
        // 通过业务ID查询请款数据
        AccountRequestFunds accountRequestFunds = accountRequestFundsService.getById(businessId);
        if (ObjectUtils.isEmpty(accountRequestFunds)) {
            throw new ServiceException("请款表的数据不存在");
        }

        // 修改请款状态为审批通过
        accountRequestFunds.setStatus(AccountRequestFundsStatusEnum.PASS.getKey());

        // 修改核销状态以及预支单核销状态为已核销
        if ("3".equals(accountRequestFunds.getType())) {
            accountRequestFunds.setWriteOffStatus(1);
            // 修改预支单核销状态
            AccountRequestFunds advance = accountRequestFundsService.getById(accountRequestFunds.getAdvanceId());
            Assert.notEmpty(advance, "查询不到关联预支单信息");
            advance.setWriteOffStatus(1);
            accountRequestFundsService.updateById(advance);
        }

        accountRequestFundsService.updateById(accountRequestFunds);

        // 添加打款的数据
        addPayment(accountRequestFunds);

    }

    /**
     * 重新发起
     */
    @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);
        accountRequestFundsService.update(q -> q
                .eq(AccountRequestFunds::getId, businessId)
                .set(AccountRequestFunds::getStatus, FlowStatusEnum1.REJECT.getKey())//20为驳回
                .set(BasePo::getUpdateTime, new Date())
                .set(BasePo::getUpdateUser, SecurityUtils.getUserId())
        );
    }

    /**
     * 添加打款表的数据
     */
    private void addPayment(AccountRequestFunds accountRequestFunds) {
        AccountPaymentDto accountPayment = new AccountPaymentDto();

        accountPayment.setDepartmentId(accountRequestFunds.getDepartmentId());
        accountPayment.setCorporationId(accountRequestFunds.getCorporationId());
        accountPayment.setBusinessId(accountRequestFunds.getId());
        accountPayment.setPaymentTime(accountRequestFunds.getPaymentTime());
        accountPayment.setCurrency(accountRequestFunds.getCurrency());
        accountPayment.setStatus(PaymentStatusEnum.UNDER_REVIEW.getKey());
        accountPayment.setType(accountRequestFunds.getType());
        accountPayment.setPaymentRemark(accountRequestFunds.getPaymentRemarks());
        accountPayment.setPaymentMethod(accountRequestFunds.getPaymentMethod());
        accountPayment.setIncomeAmount(accountRequestFunds.getTotal());
        accountPayment.setName(accountRequestFunds.getName());
        accountPayment.setBusinessManagementId(accountRequestFunds.getAccountManagementId());
        accountPayment.setOpeningBank(accountRequestFunds.getOpeningBank());
        accountPayment.setAccountOpening(accountRequestFunds.getAccountOpening());
        accountPayment.setInterbankNumber(accountRequestFunds.getInterbankNumber());
        accountPayment.setDataUser(accountRequestFunds.getCreateUser());

        // 如果是核销 核销数据审批通过后，根据“核销总额 - 预支总额”生成“待打款”数据
        if ("3".equals(accountRequestFunds.getType())) {
            BigDecimal subtract = accountRequestFunds.getTotal().subtract(accountRequestFunds.getAdvanceAmounts());
            accountPayment.setAmount(subtract);
            if (subtract.compareTo(BigDecimal.ZERO) <= 0) {//不生成打款数据
                return;
            }
        } else {
            accountPayment.setAmount(accountRequestFunds.getTotal());
        }

        accountPaymentService.save(accountPayment);
    }


    /**
     * 开始公共代码抽取
     *
     * @param opType 操作类型 0直接发起 1重新发起
     */
    private AccountRequestFundsDto commStart(AccountRequestFundsDto accountRequestFundsDto, Integer opType) {
        if (opType == 1) {
            Assert.notEmpty(accountRequestFundsDto.getId(), "请款id不能为空");
        }

        // 添加请款表的信息
        accountRequestFundsDto.setStatus(AccountRequestFundsStatusEnum.UNDER_REVIEW.getKey());
        accountRequestFundsService.saveOrUpdate(accountRequestFundsDto);

        // 添加请款详情表的信息
        List<AccountRequestFundsDetail> accountRequestFundsDetailList = accountRequestFundsDto.getAccountRequestFundsDetailList();
        if (CollectionUtils.isNotEmpty(accountRequestFundsDetailList)) {
            if (opType == 1) {
                //先删除被删除的产品
                accountRequestFundsDetailService.editLinked(accountRequestFundsDetailList, AccountRequestFundsDetail::getContractId, accountRequestFundsDto.getId());
            }

            accountRequestFundsDetailList.forEach(item -> item.setAccountRequestFundsId(accountRequestFundsDto.getId()));
            accountRequestFundsDetailService.saveOrUpdateBatch(accountRequestFundsDetailList);
        }

        if (opType == 1) {
            // 编辑附件信息
            ObsFileUtil.editFile(accountRequestFundsDto.getFileList(), accountRequestFundsDto.getId());
        } else {
            // 添加附件信息
            ObsFileUtil.saveFile(accountRequestFundsDto.getFileList(), accountRequestFundsDto.getId());
        }
        return accountRequestFundsDto;
    }

    /**
     * 重新发起
     */
    public void reStart() {
        JSONObject submitData = FlowThreadLocalUtil.getCurrentData();
        // 获取提交数据
        AccountRequestFundsDto accountRequestFundsDto = submitData.toJavaObject(AccountRequestFundsDto.class);
        commStart(accountRequestFundsDto, 1);
    }

}
