package com.hfkj.schedule;

import com.alibaba.fastjson.JSONObject;
import com.hfkj.channel.tianque.service.TianQueFundManageService;
import com.hfkj.common.utils.DateUtil;
import com.hfkj.entity.*;
import com.hfkj.service.BsMerService;
import com.hfkj.service.BsTradeOrderService;
import com.hfkj.service.BsTransferAccountsService;
import com.hfkj.service.rebate.BsRebateTransferCycleService;
import com.hfkj.sysenum.TransferAccountsStatus;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * @className: TransferSchedule
 * @author: HuRui
 * @date: 2023/10/26
 **/
@Configuration
public class TransferSchedule {

    private static final Logger log = LoggerFactory.getLogger(TransferSchedule.class);

    @Resource
    private BsTransferAccountsService transferAccountsService;

    @Resource
    private BsRebateTransferCycleService rebateTransferCycleService;

    @Resource
    private TianQueFundManageService tianQueFundManageService;

    @Resource
    private BsTradeOrderService tradeOrderService;

    @Resource
    private BsMerService merService;

    /**
     * 转账结果更新
     */
    @Scheduled(cron="0 0/1 * * * ?")   //每1分钟执行
    public void transferResult() {
        Map<String,Object> param = new HashMap<>();
        param.put("status", TransferAccountsStatus.status1.getNumber());
        List<BsTransferAccounts> list = transferAccountsService.getList(param);
        for (BsTransferAccounts transferAccounts : list) {
            try {
                // 转账结果查询
                JSONObject transferInfo = tianQueFundManageService.getTransferInfo(transferAccounts.getOrderNo());
                if (StringUtils.isNotBlank(transferInfo.getString("rate"))) {
                    transferAccounts.setShdFeeAmt(new BigDecimal(transferInfo.getString("rate")));
                }
                // 转账状态，枚举值
                // 00:成功
                // 01:失败
                // 02:异常
                if (transferInfo.getString("tranStatus").equals("00")) {
                    transferAccounts.setStatus(TransferAccountsStatus.status2.getNumber());
                } else if (transferInfo.getString("tranStatus").equals("01")) {
                    transferAccounts.setStatus(TransferAccountsStatus.status3.getNumber());
                } else if (transferInfo.getString("tranStatus").equals("02")) {
                    transferAccounts.setStatus(TransferAccountsStatus.status4.getNumber());
                }
                transferAccountsService.editData(transferAccounts);
            } catch (Exception e) {
                System.out.println("转账结果查询失败");
            }
        }
    }

    /**
     * 用户优惠券 - 转账商户
     */
    @Scheduled(cron = "0 0 1 * * ?")   // 每日凌晨1点执行
    public void tradeUserDiscount() {
        Calendar startTime = Calendar.getInstance();
        startTime.setTime(new Date());
        startTime.add(Calendar.DAY_OF_MONTH, -1);
        startTime.set(Calendar.HOUR_OF_DAY, 00);
        startTime.set(Calendar.MINUTE, 00);
        startTime.set(Calendar.SECOND, 00);

        Calendar endTime = Calendar.getInstance();
        endTime.add(Calendar.DAY_OF_MONTH, -1);
        endTime.setTime(new Date());
        endTime.set(Calendar.HOUR_OF_DAY, 00);
        endTime.set(Calendar.MINUTE, 00);
        endTime.set(Calendar.SECOND, 00);

        List<Map<String, Object>> list = tradeOrderService.countMerUserDiscountPrice(startTime.getTime(), endTime.getTime());
        for (Map<String,Object> param : list) {
            try {
                BsMer mer = merService.getMer(MapUtils.getString(param, "merNo"));
                if (mer != null) {
                    BsTransferAccounts transferAccounts = new BsTransferAccounts();
                    transferAccounts.setMerId(mer.getId());
                    transferAccounts.setMerNo(mer.getMerNo());
                    transferAccounts.setMerName(mer.getMerName());
                    transferAccounts.setMerAbbreviate(mer.getMerAbbreviate());
                    transferAccounts.setOrderNo("1000"+System.currentTimeMillis()+"");
                    transferAccounts.setAmount(new BigDecimal(MapUtils.getString(param, "totalPrice")));
                    transferAccounts.setContent(DateUtil.date2String(startTime.getTime(),"yyyy-MM-dd") + "客户优惠券结算");
                    transferAccountsService.transfer(transferAccounts);
                }
            } catch (Exception e) {
                System.out.println("转账失败");
            }
        }
    }

    /**
     * 活动金优惠 - 转账商户
     */
    @Scheduled(cron = "0 0 1 * * ?")   // 每日凌晨1点执行
    public void tradeRebate() {
        Calendar startTime = Calendar.getInstance();
        startTime.setTime(new Date());
        startTime.add(Calendar.DAY_OF_MONTH, -1);
        startTime.set(Calendar.HOUR_OF_DAY, 00);
        startTime.set(Calendar.MINUTE, 00);
        startTime.set(Calendar.SECOND, 00);

        Calendar endTime = Calendar.getInstance();
        endTime.add(Calendar.DAY_OF_MONTH, -1);
        endTime.setTime(new Date());
        endTime.set(Calendar.HOUR_OF_DAY, 00);
        endTime.set(Calendar.MINUTE, 00);
        endTime.set(Calendar.SECOND, 00);

        BsRebateTransferCycle transferCycle = new BsRebateTransferCycle();
        transferCycle.setBatchIdentifier(Long.parseLong(DateUtil.date2String(startTime.getTime(),"yyyyMMdd") + (new Random().nextInt(8999) + 1000)));
        transferCycle.setStartTime(startTime.getTime());
        transferCycle.setEndTime(endTime.getTime());
        rebateTransferCycleService.editData(transferCycle);

        List<Map<String, Object>> list = transferAccountsService.getTradeRebate(startTime.getTime(), endTime.getTime());
        for (Map<String,Object> param : list) {
            try {
                BsMer mer = merService.getMer(MapUtils.getString(param, "merNo"));
                if (mer != null) {
                    BsTransferAccounts transferAccounts = new BsTransferAccounts();
                    transferAccounts.setMerId(mer.getId());
                    transferAccounts.setMerNo(mer.getMerNo());
                    transferAccounts.setMerName(mer.getMerName());
                    transferAccounts.setMerAbbreviate(mer.getMerAbbreviate());
                    transferAccounts.setOrderNo("1000"+System.currentTimeMillis()+"");
                    transferAccounts.setAmount(new BigDecimal(MapUtils.getString(param, "totalPrice")));
                    transferAccounts.setRebateTransferCycleIdentifier(transferCycle.getBatchIdentifier());
                    transferAccounts.setContent(DateUtil.date2String(startTime.getTime(),"yyyy-MM-dd") + "活动结算");
                    transferAccountsService.transfer(transferAccounts);
                }
            } catch (Exception e) {
                System.out.println("转账失败");
            }
        }
    }
}
