package com.pj.project.tb_business_item;


import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.log.StaticLog;
import com.pj.current.task.Task;
import com.pj.project.tb_account.TbAccount;
import com.pj.project.tb_account.TbAccountService;
import com.pj.project.tb_business.TbBusiness;
import com.pj.project.tb_business.TbBusinessService;
import com.pj.project.tb_business_car.TbBusinessCar;
import com.pj.project.tb_business_car.TbBusinessCarService;
import com.pj.project.tb_costomer.TbCostomer;
import com.pj.project.tb_pay_record.TbPayRecord;
import com.pj.project.tb_pay_record.TbPayRecordService;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

public class PayTask extends Task {

    private String businessId;
    private String customerId;

    public PayTask(String id, long delayInMilliseconds, String customerId) {
        super(id, delayInMilliseconds);
        this.businessId = id;
        this.customerId = customerId;
    }

    @Override
    public void run() {
        StaticLog.info("開始執行扣款任務：{},{}",customerId,businessId);
        TbAccountService tbAccountService = SpringUtil.getBean(TbAccountService.class);
        TbAccount tbAccount = tbAccountService.getByCustomerId(customerId);
        if (tbAccount == null) {
            return;
        }
        String totalMoney = tbAccount.getTotalMoney();
        if (NumberUtil.isNumber(totalMoney)) {
            totalMoney = Base64.encode(totalMoney.getBytes());
        }
        BigDecimal money = new BigDecimal(Base64.decodeStr(totalMoney));
        TbBusinessService tbBusinessService = SpringUtil.getBean(TbBusinessService.class);
        TbBusiness tbBusiness = tbBusinessService.getById(businessId);
        TbBusinessItemService tbBusinessItemService = SpringUtil.getBean(TbBusinessItemService.class);
        List<TbBusinessItem> list = tbBusinessItemService.findByBusinessId(businessId);
        List<TbBusinessItem> allList = list;
        long notConfirmCount = list.stream()
                .filter(tbBusinessItem -> tbBusinessItem.getConfirm() == 0 && !StrUtil.equals(tbBusinessItem.getBusinessType(), "0"))
                .count();
        Date now = new Date();
        if (notConfirmCount == 0) {
            BigDecimal shouldPay = new BigDecimal("0");
            list = allList.stream().filter(tbBusinessItem -> tbBusinessItem.getPayStatus() == 0).collect(Collectors.toList());
            for (TbBusinessItem tbBusinessItem : list) {
                tbBusinessItem.setPayStatus(1).setPayTime(now);
                shouldPay = shouldPay.add(tbBusinessItem.getItemPrice());
            }

            TbBusinessCarService tbBusinessCarService = SpringUtil.getBean(TbBusinessCarService.class);
            List<TbBusinessCar> cars = tbBusinessCarService.findByBusinessId(businessId);
            cars = cars.stream().filter(tbBusinessCar -> tbBusinessCar.getPay() == 0).collect(Collectors.toList());
            for (TbBusinessCar tbBusinessCar : cars) {
                shouldPay = shouldPay.add(tbBusinessCar.getBasePartMoney());
                tbBusinessCar.setPayTime(now).setPay(1);
            }
            if (shouldPay.subtract(money).doubleValue() > 0) {
                StaticLog.error("账户支付余额不足");
                return;
            }
            String no = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + RandomUtil.randomNumbers(4);
            tbBusiness.setPayMoney(tbBusiness.getPayMoney().add(shouldPay)).setPayTime(now)
                    .setPayNo(no);
            tbBusiness.setPayStatus(tbBusiness.getPayMoney().equals(tbBusiness.getTotalMoney()) ? 3 : 4);
            tbBusinessItemService.updateBatchById(list);
            tbBusinessService.updateById(tbBusiness);
            tbBusinessCarService.updateBatchById(cars);
            BigDecimal leftMoney = money.subtract(shouldPay);
            tbAccount.setTotalMoney(Base64.encode(leftMoney.toString()));
            tbAccountService.updateById(tbAccount);
            TbPayRecord payRecord = new TbPayRecord();
            TbPayRecordService tbPayRecordService = SpringUtil.getBean(TbPayRecordService.class);
            payRecord.setCreateTime(now)
                    .setOutTradeNo(no)
                    .setTransactionId(no)
                    .setPayMoney(shouldPay)
                    .setCustomerId(tbBusiness.getCustomerId()).setCustomerName(tbBusiness.getCustomerName());
            tbPayRecordService.save(payRecord);
        }

    }
}
