package shop.alien.job.store;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import shop.alien.entity.store.StoreAliPayLog;
import shop.alien.entity.store.StoreCashOutRecord;
import shop.alien.entity.store.StoreIncomeDetailsRecord;
import shop.alien.entity.store.StoreUser;
import shop.alien.job.feign.AlienStoreFeign;
import shop.alien.mapper.StoreCashOutRecordMapper;
import shop.alien.mapper.StoreIncomeDetailsRecordMapper;
import shop.alien.mapper.StoreUserMapper;
import shop.alien.util.common.DateUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 我的钱包
 *
 * @author ssk
 * @version 1.0
 * @date 2025/8/6 14:21
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class StoreIncomeDetailsJob {

    private final StoreIncomeDetailsRecordMapper storeIncomeDetailsRecordMapper;

    private final StoreCashOutRecordMapper storeCashOutRecordService;

    private final StoreUserMapper storeUserService;

    private final AlienStoreFeign alienStoreFeign;

    /**
     * 我的钱包已到账期自动转账
     */
    @XxlJob("autoTransferAccounts")
    public void autoTransferAccounts() {
        //获取已到账期
        LambdaQueryWrapper<StoreIncomeDetailsRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.lt(StoreIncomeDetailsRecord::getCreatedTime, DateUtils.calcDays(new Date(), -28)).isNull(StoreIncomeDetailsRecord::getCashOutId);
        List<StoreIncomeDetailsRecord> list = storeIncomeDetailsRecordMapper.selectList(wrapper);
        // 根据 storeId 分组
        Map<Integer, List<StoreIncomeDetailsRecord>> groupedByStoreId = list.stream()
                .collect(Collectors.groupingBy(StoreIncomeDetailsRecord::getStoreId));
        //获取账户余额
        List<Integer> storeIds = new ArrayList<>();
        Map<Integer, Integer> storeMoney = new HashMap<>();
        Map<Integer, Integer> storeCommission = new HashMap<>();
        groupedByStoreId.forEach((storeId, records) -> {
            storeIds.add(storeId);
            // 对每个 storeId 对应的 records 进行处理
            int money = 0;
            int commission = 0;
            for (StoreIncomeDetailsRecord record : records) {
                money += record.getMoney() - record.getCommission();
                commission += record.getCommission();
            }
            storeMoney.put(storeId, money);
            storeCommission.put(storeId, commission);
        });
        List<StoreUser> storeUserList = storeUserService.selectList(new LambdaUpdateWrapper<StoreUser>().in(StoreUser::getStoreId, storeIds));
        //转账
        storeMoney.forEach((storeId, money) -> {
            if (money < 10) {
                log.info("账户已到账期金额小于最小转账金额, 用户id: {},金额: {}", storeId, money);
            } else {
                List<StoreUser> userList = storeUserList.stream()
                        .filter(storeUser -> storeUser.getStoreId().equals(storeId))
                        .collect(Collectors.toList());
                if (!userList.isEmpty()) {
                    StoreUser filteredUsers = userList.get(0);
                    JSONObject pay = alienStoreFeign.aliPay(filteredUsers.getName(), filteredUsers.getIdCard(), filteredUsers.getPhone(), new BigDecimal(money).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).toString());
                    if (null == pay) {
                        log.error("支付宝转账失败, 用户: {},金额: {}", filteredUsers.getPhone(), money);
                    } else {
                        StoreCashOutRecord storeCashOutRecord = new StoreCashOutRecord();
                        //转账记录表
                        StoreAliPayLog storeAliPayLog = JSONObject.parseObject(String.valueOf(pay), StoreAliPayLog.class);
                        storeCashOutRecord.setStoreId(storeId)
                                .setMoney(money)
                                .setCommission(storeCommission.get(storeId))
                                .setCashOutType(1)
                                .setOrderNo(storeAliPayLog.getOutBizNo())
                                .setAliOrderNo(storeAliPayLog.getOrderId())
                                .setIncomeStartTime(groupedByStoreId.get(storeId).get(0).getCreatedTime())
                                .setIncomeEndTime(groupedByStoreId.get(storeId).get(groupedByStoreId.get(storeId).size() - 1).getCreatedTime())
                                .setPaymentDate(new Date());
                        storeCashOutRecordService.insert(storeCashOutRecord);
                        list.forEach(record -> {
                            if (record.getStoreId().equals(storeId)) {
                                record.setCashOutId(storeCashOutRecord.getId());
                            }
                            //增加记录
                            storeIncomeDetailsRecordMapper.insert(record);
                        });
                        //减少金额
                        filteredUsers.setMoney(filteredUsers.getMoney() - money);
                        storeUserService.updateById(filteredUsers);
                    }
                }
            }
        });

    }

}
