package com.hzs.activity.tourism.provider;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hzs.activity.base.service.IAcBaseConfigService;
import com.hzs.activity.declaration.service.IAcDeclarationGiftConfigService;
import com.hzs.activity.declaration.service.IAcDeclarationGiftRecordService;
import com.hzs.common.domain.activity.declaration.AcDeclarationGiftConfig;
import com.hzs.common.domain.activity.declaration.AcDeclarationGiftRecord;
import com.hzs.activity.tourism.IAcTourismServiceApi;
import com.hzs.activity.tourism.service.IAcTourismDataService;
import com.hzs.common.core.constant.CountryConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.EOrderType;
import com.hzs.common.domain.activity.base.AcBaseConfig;
import com.hzs.common.domain.member.base.CuMember;
import com.hzs.common.domain.sale.order.SaOrder;
import com.hzs.member.base.IMemberServiceApi;
import com.hzs.sale.order.service.ISaOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Description: 旅游活动数据dubbo服务
 * @Author: jiang chao
 * @Time: 2024/2/22 17:32
 * @Classname: AcTourismProviderrApi
 * @PackageName: com.hzs.activity.tourism.provider
 */
@Slf4j
@DubboService
public class AcTourismServiceProvider implements IAcTourismServiceApi {

    @Autowired
    private IAcTourismDataService iAcTourismDataService;

    @Autowired
    private IAcDeclarationGiftConfigService iAcDeclarationGiftConfigService;
    @Autowired
    private IAcDeclarationGiftRecordService iAcDeclarationGiftRecordService;
    @Autowired
    private ISaOrderService iSaOrderService;
    @Autowired
    private IAcBaseConfigService iAcBaseConfigService;
    @Autowired
    private IMemberServiceApi iMemberServiceApi;

    @Override
    public R<?> handleTourismData() {
        try {
            iAcTourismDataService.handleTourismData();
            return R.ok();
        } catch (Exception e) {
            log.error("旅游活动更新积分异常", e);
        }
        return R.fail();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<?> handleDeclarationData() {
        try {
            R<?> del = saOrderPushDel();
            if (del.isSuccess()) {
                iAcDeclarationGiftConfigService.handleDeclarationData();
            }
            return R.ok();
        } catch (Exception e) {
            log.error("报单赠送更新提货列表异常", e);
        }
        return R.fail();
    }

    private R<?> saOrderPushDel() {
        // 获取所属国家
        Integer pkCountry = CountryConstants.CHINA_COUNTRY;
        // 获取 record 表最后一条数据
        AcDeclarationGiftRecord lastRecord = iAcDeclarationGiftRecordService.selectLastRecord();

        // 默认查 7 天前的数据
        int daysAgo = 7;

        // 如果上次记录不是昨天（表示有漏数据）
        if (lastRecord != null) {
            LocalDate lastDate = lastRecord.getCreationTime().toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDate();

            LocalDate today = LocalDate.now();
            long diff = ChronoUnit.DAYS.between(lastDate, today);

            if (diff > 1) {
                // 有漏跑天数，就加上差值
                daysAgo = (int) (7 + (diff - 1));
                log.info("检测到漏跑 {} 天，将查询 {} 天前的订单", diff - 1, daysAgo);
            }
        }

        // 获取目标日期（SYSDATE - daysAgo）
        Date targetDate = java.sql.Date.valueOf(LocalDate.now().minusDays(7));
        log.info("处理日期: {}", targetDate);

        // 查询订单
        List<SaOrder> orderList = iSaOrderService.list(new LambdaQueryWrapper<SaOrder>()
                .nested(w -> w.in(SaOrder::getOrderType, EOrderType.REGISTER_ORDER.getValue(), EOrderType.UPGRADE_ORDER.getValue())
                        .or()
                        .nested(x -> x.eq(SaOrder::getOrderType, EOrderType.REPURCHASE_ORDER.getValue())
                                .eq(SaOrder::getOrderTypeExtend, 1)))
                .apply("TRUNC(PAY_TIME) BETWEEN TRUNC(SYSDATE - {0}) AND TRUNC(SYSDATE - 7)", daysAgo)
                .eq(SaOrder::getOrderStatus, 1)
                .eq(SaOrder::getDelFlag, 0)
        );
        log.info("{}天无有效订单,处理结束", daysAgo);
        // 获取所有7天前有效的报单赠送活动
        List<AcBaseConfig> acBaseConfigList = iAcBaseConfigService.list(new LambdaQueryWrapper<AcBaseConfig>()
                .le(AcBaseConfig::getActStartDate, targetDate)
                .ge(AcBaseConfig::getActEndDate, targetDate)
                .eq(AcBaseConfig::getActType, 32)
                .eq(AcBaseConfig::getDelFlag, 0));
        if (acBaseConfigList.isEmpty()) {
            log.info("{}天前无有效报单赠送活动,处理结束", daysAgo);
            return R.ok();
        }
        // 报单赠送活动主键集合
        List<Long> declarationBaseIds = acBaseConfigList.stream().map(AcBaseConfig::getPkId).collect(Collectors.toList());
        // 查询所有报单赠送活动数据
        List<AcDeclarationGiftConfig> declarationGiftConfigs = iAcDeclarationGiftConfigService.list(new LambdaQueryWrapper<AcDeclarationGiftConfig>()
                .in(AcDeclarationGiftConfig::getPkBaseId, declarationBaseIds)
                .eq(AcDeclarationGiftConfig::getDelFlag, 0));
        Map<String, AcDeclarationGiftConfig> configMap = declarationGiftConfigs.stream()
                .collect(Collectors.toMap(
                        cfg -> cfg.getRegisterAuthority() + "_" + cfg.getSpecifyLevel(),
                        Function.identity(),
                        (a, b) -> b
                ));

        orderList.forEach(order -> {
            // 查看是否有重复订单
            int count = iAcDeclarationGiftRecordService.count(new LambdaQueryWrapper<AcDeclarationGiftRecord>()
                    .eq(AcDeclarationGiftRecord::getOrderCode, order.getOrderCode())
                    .eq(AcDeclarationGiftRecord::getDelFlag, 0));
            if (count > 0) {
                log.warn("当前订单已同步至报单明细{}", order.getOrderCode());
                return;
            }
            // 查询新会员信息
            R<CuMember> newMemberResult = iMemberServiceApi.getMember(order.getPkMember());
            CuMember newMember = newMemberResult.getData();
            // 查询老会员信息
            R<CuMember> oldMemberResult = iMemberServiceApi.getMember(order.getPkCreator());
            CuMember oldMember = oldMemberResult.getData();
            if (oldMember == null || newMember == null) {
                log.warn("会员信息不存在, 新会员id={},老会员id={}", order.getPkMember(), order.getPkCreator());
                return;
            }

            // 组合 key 匹配活动配置
            String key = oldMember.getRegisterAuthority() + "_" + newMember.getPkSettleGrade();
            AcDeclarationGiftConfig matchedConfig = configMap.get(key);

            if (matchedConfig == null) {
                log.info("未找到匹配的报单赠送配置, 会员id={}, 老会员注册权限={}, 新会员结算等级={}",
                        oldMember.getPkId(), oldMember.getRegisterAuthority(), newMember.getPkSettleGrade());
                return;
            }

            AcDeclarationGiftRecord record = AcDeclarationGiftRecord.builder()
                    .pkRuleId(matchedConfig.getPkId())
                    .pkBaseId(matchedConfig.getPkBaseId())
                    .orderCode(order.getOrderCode())
                    .syncStatus(0)
                    .build();
            record.setCreationTime(new Date());
            record.setDelFlag(0);
            record.setPkCreator(oldMember.getPkId());
            record.setPkCountry(pkCountry);
            // 插入数据库
            iAcDeclarationGiftRecordService.save(record);

            log.info("成功插入报单赠送记录 -> memberId={}, ruleId={}",
                    oldMember.getPkId(), matchedConfig.getPkId());
        });
        return R.ok();
    }

}
