package com.xxfc.platform.order.biz;


import cn.hutool.core.lang.Snowflake;
import com.github.wxiaoqi.security.admin.constant.WithDrawStatusEnum;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import com.xxfc.platform.order.contant.enumerate.CompanyWalletITypeEnum;
import com.xxfc.platform.order.entity.*;
import com.xxfc.platform.order.mapper.CompanyWalletCathMapper;
import com.xxfc.platform.order.pojo.dto.WalletCathApplyDTO;
import com.xxfc.platform.order.pojo.dto.WalletCathDTO;
import com.xxfc.platform.order.pojo.vo.CompanyWalletCathVo;
import com.xxfc.platform.order.pojo.vo.CompanyWalletDetailVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Instant;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;


@Service
@Slf4j
public class CompanyWalletCathBiz extends BaseBiz<CompanyWalletCathMapper, CompanyWalletCath> implements InitializingBean {

    @Autowired
    CompanyWalletBiz companyWalletBiz;


    @Autowired
    CompanyWalletDetailBiz walletDetailBiz;


    @Autowired
    BranchCompanyBiz branchCompanyBiz;


    private Snowflake snowflake;

    private DateTimeFormatter dateTimeFormatter;




    public List<CompanyWalletCathVo> getList(WalletCathDTO walletCathDTO){
        return  mapper.selectList(walletCathDTO);
    }


    public PageDataVO<CompanyWalletDetailVo> selectList(WalletCathDTO walletCathDTO) {
        return PageDataVO.pageInfo(walletCathDTO.getPage(), walletCathDTO.getLimit(), () -> getList(walletCathDTO));
    }


    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void applyCathList(WalletCathApplyDTO walletCathApplyDTO){
        if (walletCathApplyDTO == null) {
            throw  new BaseException("参数不能为空",ResultCode.NULL_CODE);
        }
        List<Integer> companyIds = walletCathApplyDTO.getCompanyIds();
        for (Integer companyId:companyIds){
            CompanyWalletCath walletCathDTO=new CompanyWalletCath();
            BeanUtils.copyProperties(walletCathApplyDTO,walletCathDTO);
            walletCathDTO.setCompanyId(companyId);
            applyCath(walletCathDTO);
        }
    }


    //提现申请
    public void applyCath(CompanyWalletCath walletCathDTO) {
        if (walletCathDTO == null) {
            throw  new BaseException("参数不能为空",ResultCode.NULL_CODE);
        }
        Integer companyId = walletCathDTO.getCompanyId();
        BigDecimal amount = walletCathDTO.getAmount();

        //检查是否可以提现
        BigDecimal cathAmount=mapper.sunAmountByStatus(companyId);
        cathAmount=cathAmount.add(amount);
        CompanyWallet companyWallet=companyWalletBiz.checkAmount(companyId, cathAmount);

        CompanyWalletCath walletCath = new CompanyWalletCath();
        BeanUtils.copyProperties(walletCathDTO,walletCath);

        BigDecimal commission =BigDecimal.ZERO;
        BigDecimal balnece = companyWallet.getBalance();
        //到账金额
        BigDecimal realAmount = amount.subtract(commission).setScale(2, RoundingMode.HALF_UP);

        //提现单号
        String orderNo = snowflake.nextIdStr();
        orderNo = String.format("%s%s", dateTimeFormatter.format(LocalDate.now()), orderNo);
        log.info("-----提现申请-----orderNo===" + orderNo + "----companyId====" + companyId + "---realAmount===" + realAmount);
        walletCath.setCrtTime(Instant.now().toEpochMilli());
        walletCath.setOrderNo(orderNo);
        walletCath.setStauts(WithDrawStatusEnum.AUDIT.getCode());
        walletCath.setBalance(balnece);
        walletCath.setRealAmount(realAmount);
        walletCath.setCommission(commission);
        walletCath.setWithdrawWay(2);
        insertSelective(walletCath);
    }


    public void withDrawProcess(CompanyWalletCath companyWalletCath) {
        WalletCathDTO walletCathDTO=new WalletCathDTO();
        walletCathDTO.setOrderNo(companyWalletCath.getOrderNo());
        List<CompanyWalletCathVo> list = getList(walletCathDTO);
        if (list == null || list.size() == 0) {
            throw new BaseException("提现记录不存在",ResultCode.FAILED_CODE);
        }
        CompanyWalletCathVo walletCathVo=list.get(0);

        if (walletCathVo.getStauts() == WithDrawStatusEnum.SUCCESS.getCode()) {
            throw new BaseException("已审核",ResultCode.FAILED_CODE);
        }
        CompanyWallet companyWallet=companyWalletBiz.selectById(walletCathVo.getCompanyId());
        if (companyWallet == null) {
            throw new BaseException("钱包不存在", ResultCode.FAILED_CODE);
        }
        companyWalletCath.setFinishTime(Instant.now().toEpochMilli());
        companyWalletCath.setId(walletCathVo.getId());
        updateSelectiveById(companyWalletCath);
        if (companyWalletCath.getStauts() == WithDrawStatusEnum.SUCCESS.getCode()) {
            BigDecimal sAmount=companyWallet.getBalance().subtract(walletCathVo.getAmount()).setScale(2, RoundingMode.HALF_UP);
            CompanyWalletDetail detail = new CompanyWalletDetail();
            detail.setCono(walletCathVo.getOrderNo());
            detail.setSAmount(sAmount);
            detail.setAmount(walletCathVo.getAmount());
            detail.setItype(CompanyWalletITypeEnum.CATH.getCode());
            //设置提现单号
            detail.setCompanyId(walletCathVo.getCompanyId());
            detail.setBranchId(walletCathVo.getBranchId());
            walletDetailBiz.insertSelective(detail);

            //更新钱包
            BigDecimal withdrawals = companyWallet.getWithdrawals().add(walletCathVo.getAmount()).setScale(2, RoundingMode.HALF_UP);
            companyWallet.setBalance(sAmount);
            companyWallet.setWithdrawals(withdrawals);
            companyWalletBiz.updCompanyWallet(companyWallet);
        }
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        snowflake = new Snowflake(2, 2, false);
        dateTimeFormatter = DateTimeFormatter.ofPattern("YYYYMMdd");
    }












}
