package com.hzs.member.account.provider;

import cn.hutool.core.collection.CollUtil;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.EApprovalBusiness;
import com.hzs.common.core.enums.EApproveOperation;
import com.hzs.common.core.enums.EApproveStatus;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.domain.member.account.*;
import com.hzs.member.account.IMemberAccountAuditServiceApi;
import com.hzs.member.account.dto.BusinessCommissionDTO;
import com.hzs.member.account.dto.MemberAccountAudit;
import com.hzs.member.account.service.*;
import com.hzs.member.account.vo.CuMemberBusinessLicenseVO;
import com.hzs.system.sys.dto.ApprovalBusinessResultDTO;
import com.hzs.system.sys.dto.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @Description: 会员钱包审核Doubbo服务
 * @Author: ljc
 * @Time: 2022/9/24 13:53
 * @Classname: IMemberAccountAuditServiceProvider
 * @Package_name: com.hzs.member.account.provider
 */
@Slf4j
@DubboService
public class IMemberAccountAuditServiceProvider implements IMemberAccountAuditServiceApi {


    @Autowired
    ICuMemberRechargeService cuMemberRechargeService;

    @Autowired
    ICuMemberWithdrawService cuMemberWithdrawService;

    @Autowired
    ICuMemberTradeService cuMemberTradeService;

    @Autowired
    ICuMemberBaseService cuMemberBaseService;

    @Autowired
    ICuMemberAccountLogService cuMemberAccountLogService;

    @Autowired
    ICuMemberAccountService cuMemberAccountService;

    @Autowired
    ICuMemberBusinessLicenseService cuMemberBusinessLicenseService;

    @Override
    public R auditProcess(ApprovalBusinessResultDTO approvalBusinessResultDTO) {
        //审核状态(1=待提交,2=待审批,3=审批中,4=已驳回,5=已完成,6=已归档)
        EApproveStatus eApproveStatus = approvalBusinessResultDTO.getEApproveStatus();
        //通过/驳回（EApproveOperation）
        Integer approveOperation = approvalBusinessResultDTO.getApproveOperation();
        EApprovalBusiness eApprovalBusiness = approvalBusinessResultDTO.getEApprovalBusiness();
        String businessCode = approvalBusinessResultDTO.getBusinessCode();

        if (StringUtils.isEmpty(businessCode) || null == approveOperation || null == eApprovalBusiness) {
            return R.fail("提交审核缺少参数！");
        }
        int module = eApprovalBusiness.getValue();
        try {
            //财务审批
            if (module == EApprovalBusiness.RECHARGE.getValue()) {
                List<CuMemberRecharge> cuMemberRecharges = cuMemberRechargeService.selectRechargeByBatch(businessCode);
                if (CollUtil.isEmpty(cuMemberRecharges)) {
                    return R.fail("审批记录不存在！");
                }
                //充值审批
                memberRechargeApprove(approveOperation, approvalBusinessResultDTO, cuMemberRecharges, businessCode);
                //审核接口返回下级审核人的角色ID、名称、审核人、审核状态
                MemberAccountAudit memberAccountAudit = dtoToParam(approvalBusinessResultDTO, approveOperation + 1, module, businessCode);
                return R.ok(cuMemberRechargeService.submitAuditMemberRecharge(memberAccountAudit));
            } else if (module == EApprovalBusiness.WITHDRAWAL.getValue()) {
                //提现审批
                List<CuMemberWithdraw> memberWithdrawList = cuMemberWithdrawService.selectWithdrawByBatch(businessCode);
                if (CollUtil.isEmpty(memberWithdrawList)) {
                    return R.fail("审核记录不存在！");
                }
                //提现审批
                memberWithdrawApprove(approveOperation, approvalBusinessResultDTO, memberWithdrawList, businessCode);
                MemberAccountAudit memberAccountAudit = dtoToParam(approvalBusinessResultDTO, eApproveStatus.getValue(), module, businessCode);
                return R.ok(cuMemberWithdrawService.updateWithdrawByCode(memberAccountAudit));
                //营业执照审批
            } else if (module == EApprovalBusiness.BUSINESS_LICENSE.getValue()) {
                //营业执照审批
                CuMemberBusinessLicense cuMemberBusinessLicense = cuMemberBusinessLicenseService.selectLicenseByBusinessNo(businessCode);
                if (null == cuMemberBusinessLicense) {
                    return R.fail("审核记录不存在！");
                }
                return R.ok(businessLicenseApprove(approvalBusinessResultDTO));
            }else if (module == EApprovalBusiness.BUSINESS_LICENSE_RESETTING.getValue()) {
                //重置营业执照审批
                CuMemberBusinessLicense cuMemberBusinessLicense = cuMemberBusinessLicenseService.selectLicenseByBusinessNo(businessCode);
                if (null == cuMemberBusinessLicense) {
                    return R.fail("审核记录不存在！");
                }
                return R.ok(resetBusinessLicenseApprove(approvalBusinessResultDTO));
            } else {
                //财务冻结审批
                CuMemberAccountLog cuMemberAccountLog = cuMemberAccountLogService.queryCuMemberAccountLogByBusinessCode(businessCode);
                if (null == cuMemberAccountLog) {
                    return R.fail("审核记录不存在！");
                }
                //审批通过更新账户信息
                if (approveOperation == (EApproveOperation.AGREE.getValue())) {
                    cuMemberAccountService.approvalPass(cuMemberAccountLog.getLockAccountData());
                }
                MemberAccountAudit memberAccountAudit = dtoToParam(approvalBusinessResultDTO, approveOperation + 1, module, businessCode);
                return R.ok(cuMemberAccountLogService.updateMemberAccountLogByCode(memberAccountAudit));
            }
        } catch (Exception e) {
            //钱包业务发生异常时，提醒审批流程事务回滚
            log.error("审核状态为： {} 的审核出错", approveOperation, e);
            return R.fail("审批钱包业务流程出错！");
        }
    }

    /**
     * 充值审批
     *
     * @param approveOperation          审批操作
     * @param approvalBusinessResultDTO 业务审批操作DTO
     * @param cuMemberRecharges         充值用户信息
     * @param businessCode              业务代码
     */
    private void memberRechargeApprove(Integer approveOperation, ApprovalBusinessResultDTO approvalBusinessResultDTO,
                                       List<CuMemberRecharge> cuMemberRecharges, String businessCode) {
        //审批通过插入交易明细和余额表
        if (approveOperation == (EApproveOperation.AGREE.getValue())) {
            //查询奖金账户信息
            List<CuMemberAccountRechargeExt> cuMemberAccounts = cuMemberAccountService.selectMemberBonusAccountBySourceCode(businessCode);
            //插入交易明细和余额表
            cuMemberRechargeService.updateMemberTradeAndMemberBalance(approvalBusinessResultDTO, cuMemberRecharges);
            //插入奖金发放明细表
            if (CollUtil.isNotEmpty(cuMemberAccounts)) {
                Integer rechargeMethod = cuMemberRecharges.get(0).getRechargeMethod();
                cuMemberRechargeService.saveMemberTradeDetailAndBonus(cuMemberAccounts, rechargeMethod, businessCode);
            }

        }
        //驳回
        if (approveOperation == (EApproveOperation.REJECT.getValue())) {
            // TODO: 2023/2/17  根据后需求，是否重新发起
            // cuMemberRechargeService.updateDelFlagByRechargeCode(businessCode);
        }
    }

    /**
     * 提现审批
     *
     * @param approveOperation          审批操作
     * @param approvalBusinessResultDTO 业务审批操作DTO
     * @param memberWithdrawList        提现用户信息
     * @param businessCode              业务代码
     */
    private void memberWithdrawApprove(Integer approveOperation, ApprovalBusinessResultDTO approvalBusinessResultDTO,
                                       List<CuMemberWithdraw> memberWithdrawList, String businessCode) {
        //驳回
        if (approveOperation == (EApproveOperation.REJECT.getValue())) {
            CuMemberWithdraw memberWithdraw = memberWithdrawList.get(0);
            Integer pkCountry = memberWithdraw.getPkCountry();
            BusinessCommissionDTO businessCommissionDTO = BusinessCommissionDTO.builder()
                    .tradeCode(businessCode).pkCountry(pkCountry)
                    .tradeType(EApprovalBusiness.WITHDRAWAL.getValue())
                    .pkCreator(approvalBusinessResultDTO.getLoginUser().getUserId()).build();
            cuMemberTradeService.businessCommissionReject(businessCommissionDTO);
        }
    }


    /**
     * TDO转业务参数
     *
     * @param approvalBusinessResultDTO 业务审批操作DTO
     * @param approveState              审核状态
     * @param module                    模块
     * @param businessCode              业务代码
     * @return MemberAccountAudit
     */
    private MemberAccountAudit dtoToParam(ApprovalBusinessResultDTO approvalBusinessResultDTO, Integer approveState, Integer module, String businessCode) {
        return MemberAccountAudit.builder()
                .approver(approvalBusinessResultDTO.getLoginUser().getUserId())
                .pkModified(approvalBusinessResultDTO.getLoginUser().getUserId())
                .approveState(approveState)
                .approveTime(approvalBusinessResultDTO.getOperationTime())
                .businessCode(businessCode).module(module)
                .pkRole(approvalBusinessResultDTO.getSysUser().getUserId())
                .roleName(approvalBusinessResultDTO.getSysUser().getUserName())
                .build();
    }


    /**
     * 营业执照审批
     *
     * @param approvalBusinessResultDTO 业务审批操作DTO
     */
    private Integer businessLicenseApprove(ApprovalBusinessResultDTO approvalBusinessResultDTO) {
        LoginUser loginUser = approvalBusinessResultDTO.getLoginUser();
        EApproveStatus eApproveStatus = approvalBusinessResultDTO.getEApproveStatus();
        CuMemberBusinessLicenseVO cuMemberBusinessLicense = CuMemberBusinessLicenseVO.builder()
                .businessNo(approvalBusinessResultDTO.getBusinessCode()).approveStatus(eApproveStatus.getValue())
                .pkModified(loginUser.getUserId())
                .approveTime(approvalBusinessResultDTO.getOperationTime())
                .build();
        if(eApproveStatus.getValue()==EApproveStatus.REJECTED.getValue()){
            cuMemberBusinessLicense.setRejectMsg("");
        }
        return cuMemberBusinessLicenseService.updateLicenseByBusinessNo(cuMemberBusinessLicense);
    }

    /**
     * @description: 重置营业执照
     * @author: zhang jing
     * @date: 2023/11/20 13:43
     * @param: [approvalBusinessResultDTO]
     * @return: java.lang.Integer
     **/
    private Integer resetBusinessLicenseApprove(ApprovalBusinessResultDTO approvalBusinessResultDTO) {
        LoginUser loginUser = approvalBusinessResultDTO.getLoginUser();
        EApproveStatus eApproveStatus = approvalBusinessResultDTO.getEApproveStatus();
        CuMemberBusinessLicenseVO cuMemberBusinessLicense = CuMemberBusinessLicenseVO.builder()
                .businessNo(approvalBusinessResultDTO.getBusinessCode()).approveStatus(eApproveStatus.getValue())
                .pkModified(loginUser.getUserId())
                .approveTime(approvalBusinessResultDTO.getOperationTime())
                .build();
        if(approvalBusinessResultDTO.getApproveOperation()==EApproveOperation.AGREE.getValue()){
            return cuMemberBusinessLicenseService.deleteLicense(cuMemberBusinessLicense);
        }else{
            return cuMemberBusinessLicenseService.rejectResetLicense(cuMemberBusinessLicense);
        }

    }

}
