package com.fjhx.sale.flow;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.fjhx.account.entity.account.enums.PaymentStatusEnum;
import com.fjhx.account.entity.account.enums.PaymentTypeEnum;
import com.fjhx.account.entity.account.po.AccountPayment;
import com.fjhx.account.service.account.AccountPaymentService;
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.enums.FlowStatusEnum;
import com.fjhx.purchase.entity.pay.enums.PayStatusEnum1;
import com.fjhx.purchase.entity.pay.po.Pay;
import com.fjhx.purchase.entity.pay.po.PayDetail;
import com.fjhx.purchase.service.pay.PayDetailService;
import com.fjhx.purchase.service.pay.PayService;
import com.fjhx.sale.entity.purchase.po.EhsdPurchase;
import com.fjhx.sale.service.purchase.EhsdPurchaseService;
import com.fjhx.supply.entity.supplier.po.SupplierInfo;
import com.fjhx.supply.service.supplier.SupplierInfoService;
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;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 采购付款流程
 *
 * @Author:caozj
 * @DATE:2023/4/3 17:38
 */
//@DS(SourceConstant.PURCHASE)
@Component
public class PayFlow extends FlowDelegate {

    @Autowired
    private PayService payService;

    @Autowired
    private AccountPaymentService accountPaymentService;

    @Autowired
    private PayDetailService payDetailService;

    @Autowired
    private EhsdPurchaseService purchaseService;

    @Autowired
    private SupplierInfoService supplierInfoService;

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

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

        Long companyId = SecurityUtils.getCompanyId();

        pay.setCompanyId(companyId);

        pay.setCurrency("CNY");
        pay.setStatus(PayStatusEnum1.UNDER_REVIEW.getKey());
        payService.saveOrUpdate(pay);

        List<PayDetail> payDetailList = pay.getPayDetailList();
        if (CollectionUtils.isNotEmpty(payDetailList)) {
            payDetailList.forEach(item -> {
                item.setPayId(pay.getId());
                item.setCompanyId(companyId);
            });
        }
        payDetailService.editLinked(payDetailList, PayDetail::getPayId, pay.getId());

        ObsFileUtil.editFile(pay.getFileList(), pay.getId());

        //供应商名称
        SupplierInfo supplierInfo = supplierInfoService.getById(pay.getSupplyId());
        Assert.notEmpty(supplierInfo, "查询不到供应商信息！");
        submitData.put("supplyName", supplierInfo.getName());

        return pay.getId();
    }

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

        // 通过业务ID查询申购数据
        Pay pay = payService.getById(businessId);
        if (ObjectUtils.isEmpty(pay)) {
            throw new ServiceException("采购付款单不存在");
        }

        // 修改采购状态为审批通过
        pay.setStatus(PayStatusEnum1.PASS.getKey());
        pay.setApprovedDate(new Date());
        payService.updateById(pay);

        // 添加一条付款流水
        AccountPayment payment = new AccountPayment();
        payment.setAccountManagementId(pay.getAccountManagementId());
        payment.setBusinessId(pay.getId());
        payment.setCurrency(pay.getCurrency());
        payment.setPaymentRemark(pay.getRemark());
        payment.setType(PaymentTypeEnum.REJECT.getKey());
        payment.setStatus(PaymentStatusEnum.UNDER_REVIEW.getKey());
        payment.setAmount(BigDecimal.ZERO);
        payment.setIncomeAmount(pay.getAmount());
        payment.setName(pay.getName());
        payment.setDataUser(pay.getCreateUser());
        payment.setBusinessManagementId(pay.getAccountManagementId());
        payment.setOpeningBank(pay.getOpeningBank());
        payment.setBusinessCurrency(pay.getCurrency());
        payment.setAccountOpening(pay.getAccountOpening());
        payment.setInterbankNumber(pay.getInterbankNumber());
        payment.setPaymentMethod(pay.getPayType());
        payment.setCompanyId(pay.getCompanyId());
        payment.setCorporationId(pay.getCompanyId());
        payment.setDepartmentId(SecurityUtils.getDeptId());
        accountPaymentService.save(payment);

        // 修改合同付款状态
        updatePurchasePayStatus(businessId);

    }

    /**
     * 修改合同付款状态
     *
     * @param payId 付款id
     */
    private void updatePurchasePayStatus(Long payId) {

        // 获取支付明细
        List<PayDetail> list = payDetailService.list(q -> q.eq(PayDetail::getPayId, payId));

        // 获取合同id
        List<Long> purchaseIdList = list.stream().map(PayDetail::getPurchaseId).filter(Objects::nonNull).distinct().collect(Collectors.toList());

        if (purchaseIdList.size() == 0) {
            return;
        }

        // 通过合同id获取指定合同所有付款记录
        Map<Long, BigDecimal> map = payDetailService.getPayMoneyCountByPurchaseId(purchaseIdList);

        // 获取合同列表
        List<EhsdPurchase> purchaseList = purchaseService.listByIds(purchaseIdList);

        for (EhsdPurchase purchase : purchaseList) {

            Integer payStatus = purchase.getPayStatus();

            // 已经是已付款，跳过
            if (Objects.equals(20, payStatus)) {
                continue;
            }

            // 获取合同付款金额
            BigDecimal payMoney = map.getOrDefault(purchase.getId(), BigDecimal.ZERO);
            // 获取合同金额
            BigDecimal amount = purchase.getAmount();

            // 合同付款金额大于等于合同金额，已付款
            if (payMoney.compareTo(amount) >= 0) {
                purchase.setPayStatus(20);
            }
            // 否则进行中
            else {
                purchase.setPayStatus(10);
            }

        }

        // 修改合同付款状态
        purchaseService.updateBatchById(purchaseList);

    }

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

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

        payService.update(q -> q
                .eq(Pay::getId, businessId)
                .set(Pay::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);

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

}
