package com.yida.data.school.transaction.service.impl;


import com.yida.data.common.core.entity.apply.EduApplyProductOrder;
import com.yida.data.common.core.entity.apply.EduProduct;
import com.yida.data.common.core.entity.constant.CachePrefixConstant;
import com.yida.data.common.core.entity.constant.LockPrefixConstant;
import com.yida.data.common.core.entity.system.EduPayWxConfig;
import com.yida.data.common.core.enums.PayWay;
import com.yida.data.common.core.utils.WxPayUtil;
import com.yida.data.common.service.CommonService;
import com.yida.data.school.transaction.mapper.EduApplyProductOrderMapper;
import com.yida.data.school.transaction.mapper.EduApplyProductOrderStudentMapper;
import com.yida.data.school.transaction.mapper.EduApplyProductRefundMapper;
import com.yida.data.school.transaction.mapper.EduProductMapper;
import com.yida.data.school.transaction.service.EduProductOrderService;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

import cc.mrbird.febs.common.redis.service.RedisService;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@AllArgsConstructor
@Component
@Slf4j
public class Scheduler {
    private final EduApplyProductOrderMapper eduApplyProductOrderMapper;
    private final EduApplyProductOrderStudentMapper eduApplyProductOrderStudentMapper;
    private final EduProductMapper eduProductMapper;
    private final RedisService redisService;
    private final EduApplyProductRefundMapper eduApplyProductRefundMapper;
    private final EduProductOrderService eduProductOrderService;
    private final CommonService commonService;

    /**
     * 订单超时变更状态，每5s检测一次
     */
    @Scheduled(fixedDelay = 5000)
    public void updateOrderStatus() {
        List<EduApplyProductOrder> expireOrder = eduApplyProductOrderMapper.selectExpireOrder(LocalDateTime.now());
        if (CollUtil.isNotEmpty(expireOrder)) {
            for (EduApplyProductOrder order : expireOrder) {
                if (PayWay.WEI_XIN.getValue().equals(order.getPayWay())) {
                    EduPayWxConfig config = commonService.getPayWxConfigBySchool(order.getSchoolId());
                    // 主动查询是否已经支付了
                    try {
                        JSONObject resJson =
                                JSONUtil.parseObj(WxPayUtil.queryOrder(config, order.getOrderCode()));
                        log.info("resJson:[{}]", resJson);
                        if (resJson.containsKey("code") && "ORDER_NOT_EXIST".equals(resJson.getStr("code"))) {
                            // 订单不存在  取消订单
                            order.setOrderStatus("4");
                            order.setPayStatus("3");
                        } else {
                            String tradeState = resJson.getStr("trade_state");
                            switch (tradeState) {
                                // 支付成功情况
                                case "SUCCESS":
                                case "ACCEPT":
                                    eduProductOrderService.paySuccessUpdate(order.getOrderCode(), DateUtil.parseLocalDateTime(resJson.getStr("success_time"), "yyyy-MM" +
                                            "-dd'T" +
                                            "'HH:mm" +
                                            ":ssXXX"));
                                    continue;
                                    // 未完成支付还需要关闭订单
                                case "NOTPAY":
                                    WxPayUtil.closeOrder(config, order.getOrderCode());
                                    // 未完成支付，订单作废
                                case "CLOSED":
                                case "REVOKED":
                                case "PAYERROR":
                                    order.setOrderStatus("4");
                                    order.setPayStatus("3");
                                    break;
                            }
                        }
                        if ("4".equals(order.getOrderStatus())) {
                            eduApplyProductOrderMapper.updateById(order);
                            EduProduct product = (EduProduct) redisService.hget(CachePrefixConstant.PRODUCT,
                                    order.getProductId().toString());
                            // 获取锁
                            redisService.lock(LockPrefixConstant.PRODUCT_STOCK_EDIT_LOCK + product.getProductId());
                            // 获取库存
                            product.setStock(product.getStock() + order.getOrderStudentList().size());
                            redisService.hset(CachePrefixConstant.PRODUCT, order.getProductId().toString(), product);
                            redisService.unlock(LockPrefixConstant.PRODUCT_STOCK_EDIT_LOCK + product.getProductId());
                            redisService.del(CachePrefixConstant.ORDER + order.getOrderCode());
                        }
                    } catch (Exception e) {
                        log.error("update status fail:[{}],[{}]", e.getMessage(), e.getStackTrace());
                    }
                }
            }
        }
    }

}
