package com.fjhx.purchase.flow;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
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.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.enums.FlowStatusEnum;
import com.fjhx.purchase.entity.pay.enums.PayStatusEnum;
import com.fjhx.purchase.entity.pay.po.Pay;
import com.fjhx.purchase.entity.pay.po.PayDetail;
import com.fjhx.purchase.entity.purchase.po.Purchase;
import com.fjhx.purchase.service.pay.PayDetailService;
import com.fjhx.purchase.service.pay.PayService;
import com.fjhx.purchase.service.purchase.PurchaseService;
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 com.ruoyi.common.utils.wrapper.IWrapper;
import com.ruoyi.system.service.ISysUserService;
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 PurchaseService purchaseService;
    @Autowired
    private ISysUserService userService;

    @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);

        //调用公共代码
        pay = commStart(pay, 0);

        return pay.getId();
    }

    /**
     * 开始公共代码抽取
     *
     * @param opType 操作类型 0直接发起 1重新发起
     */
    private Pay commStart(Pay pay, Integer opType) {
        if (opType == 1) {
            Assert.notEmpty(pay.getId(), "采购付款id不能为空");
        }
        pay.setCurrency("CNY");//默认币种人民币
        pay.setRate(new BigDecimal("1"));//默认币种人民币
        pay.setStatus(PayStatusEnum.UNDER_REVIEW.getKey());
        payService.saveOrUpdate(pay);

        List<PayDetail> payDetailList = pay.getPayDetailList();
        if (CollectionUtils.isNotEmpty(payDetailList)) {
            if (opType == 1) {
                //先删除被删除的产品
                payDetailService.editLinked(payDetailList, PayDetail::getPayId, pay.getId());
            }

            payDetailList.forEach(item -> item.setPayId(pay.getId()));
            payDetailService.saveOrUpdateBatch(payDetailList);
        }

        if (opType == 1) {
            ObsFileUtil.editFile(pay.getFileList(), pay.getId());
        } else {
            ObsFileUtil.saveFile(pay.getFileList(), pay.getId());
        }
        return pay;
    }

    /**
     * 结束流程
     *
     * @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(PayStatusEnum.PASS.getKey());
        pay.setApprovedDate(new Date());
        payService.updateById(pay);
        if(!StringUtils.equals(pay.getType(),"3")){

            // 添加一条付款流水
            AccountPayment payment = new AccountPayment();
            payment.setAccountManagementId(pay.getAccountManagementId());
            payment.setBusinessId(pay.getId());
            payment.setCurrency(pay.getCurrency());

            DynamicDataSourceContextHolder.push(SourceConstant.BASE);
            SysUser sysUser = userService.getOne(IWrapper.<SysUser>getWrapper().eq(SysUser::getUserId, pay.getCreateUser()));
            DynamicDataSourceContextHolder.poll();
            if (ObjectUtils.isNotEmpty(sysUser)) {
                payment.setDepartmentId(sysUser.getDeptId());
            }
            // todo 暂时写死人民币
            payment.setPaymentRemark(pay.getRemark());
            payment.setType(PaymentTypeEnum.REJECT.getKey());
            payment.setStatus(PaymentStatusEnum.UNDER_REVIEW.getKey());
            payment.setCorporationId(pay.getCorporationId());
            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.setApplyForTime(pay.getCreateTime());//申请时间
            accountPaymentService.save(payment);
        }
        // 修改合同付款状态
        updatePurchasePayStatus(businessId);
    }

//    @Override
//    public void defaultMethod(Long flowId, Long businessId, FlowStatusEnum flowStatusEnum, JSONObject submitData) {
//
//    }

    @Override
    public void relaunch(Long flowId, Long businessId, FlowStatusEnum flowStatus, JSONObject submitData) {
        super.relaunch(flowId, businessId, flowStatus, submitData);
        Pay pay = submitData.toJavaObject(Pay.class);
        commStart(pay, 1);
    }

    @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())
        );
    }

    /**
     * 修改合同付款状态
     *
     * @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<Purchase> purchaseList = purchaseService.listByIds(purchaseIdList);

        for (Purchase 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);

    }

}
