package com.hzs.retail.member.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.common.core.constant.*;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.exception.ServiceException;
import com.hzs.common.core.service.RedisService;
import com.hzs.common.domain.retail.member.CuMemberRetailRegion;
import com.hzs.common.domain.retail.member.ext.CuMemberRetailRegionExt;
import com.hzs.common.domain.system.base.BdArea;
import com.hzs.retail.member.mapper.CuMemberRetailRegionMapper;
import com.hzs.retail.member.param.RetailMemberRegionParam;
import com.hzs.retail.member.service.ICuMemberRetailAchieveService;
import com.hzs.retail.member.service.ICuMemberRetailRegionService;
import com.hzs.retail.member.vo.UnboundAreaVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 新零售会员区域配置 服务实现类
 */
@Slf4j
@Service
public class CuMemberRetailRegionServiceImpl extends ServiceImpl<CuMemberRetailRegionMapper, CuMemberRetailRegion> implements ICuMemberRetailRegionService {

    @Autowired
    private ICuMemberRetailAchieveService iCuMemberRetailAchieveService;

    @Autowired
    private RedisService redisService;

    @Override
    public CuMemberRetailRegionExt getRegionByMember(Long pkMember, Integer gradeValue, Integer systemType) {
        return baseMapper.getRegionByMember(pkMember, gradeValue, systemType);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String setRegion(RetailMemberRegionParam param) {
        String redisKey = String.format(CacheConstants.RETAIL_REGION, param.getProvince(), param.getCity(), param.getCounty());
        try {
            // 按省、市、区上锁
            if (!redisService.lockKeyMany(redisKey)) {
                return "收益区域绑定失败，请重试";
            }

            if (null != param.getPkId()) {
                // 之前存在数据，将旧数据取消
                this.update(Wrappers.<CuMemberRetailRegion>lambdaUpdate()
                        .eq(CuMemberRetailRegion::getPkMember, param.getPkMember())
                        .eq(CuMemberRetailRegion::getEffective, EYesNo.YES.getIntValue())
                        .eq(CuMemberRetailRegion::getSystemType, param.getSystemType())
                        .set(CuMemberRetailRegion::getEffective, EYesNo.NO.getIntValue())
                        .set(CuMemberRetailRegion::getPkModified, param.getPkMember())
                        .set(CuMemberRetailRegion::getModifiedTime, new Date())
                );
            }
            // 新増数据
            CuMemberRetailRegion retailRegion = CuMemberRetailRegion.builder()
                    .pkMember(param.getPkMember())
                    .province(param.getProvince())
                    .city(param.getCity())
                    .county(param.getCounty())
                    // 数据来源会员端
                    .source(param.getSource())
                    .systemType(param.getSystemType())
                    .build();
            retailRegion.setPkCreator(param.getPkMember());
            if (baseMapper.insertData(retailRegion) == 0) {
                throw new ServiceException("选择区域失败，请刷新后重试");
            }
        } finally {
            redisService.unlock(redisKey);
        }
        return null;
    }

    @Override
    public List<BdArea> listChooseRegion(Integer systemType) {
        return baseMapper.listChooseRegion(systemType);
    }

    @Override
    public List<UnboundAreaVO> unboundAreaList(Integer pkCountry, Integer systemType) {
        return baseMapper.unboundAreaList(pkCountry, systemType);
    }

    @Override
    public List<CuMemberRetailRegionExt> memberretailRegList(CuMemberRetailRegionExt mrrExt) {
        return baseMapper.memberretailRegList(mrrExt);
    }

    @Override
    public void batchUpdateRetailRegion() {
        baseMapper.batchUpdateRetailRegion();
    }

    @Override
    public void checkRegion() {
        // 需要处理的会员列表
        List<CuMemberRetailRegionExt> memberList = baseMapper.listCheckRegionMember();

        if (CollectionUtil.isNotEmpty(memberList)) {
            memberList.parallelStream().forEach(tmpMember -> {
                if (ENoticeWebsiteType.ADMIN.getValue() == tmpMember.getSource()) {
                    log.info("定时任务区域有效， 会员 {} 后台配置，不取消收益区域", tmpMember.getPkId());
                    return;
                }

                // 当前时间
                Date nowDate = new Date();

                if (tmpMember.getGradeValue() < EGrade.S_VIP.getValue()) {
                    // 会员等级不足V5，需要关掉收益区域
                    log.info("定时任务区域有效， 会员 {} 等级 {} 不足取消收益区域", tmpMember.getPkId(), tmpMember.getGradeValue());
                    this.update(Wrappers.<CuMemberRetailRegion>lambdaUpdate()
                            .eq(CuMemberRetailRegion::getPkMember, tmpMember.getPkId())
                            .eq(CuMemberRetailRegion::getEffective, EYesNo.YES.getIntValue())
                            .set(CuMemberRetailRegion::getEffective, EYesNo.NO.getIntValue())
                            .set(CuMemberRetailRegion::getPkModified, tmpMember.getPkId())
                            .set(CuMemberRetailRegion::getModifiedTime, nowDate)
                    );
                } else {
//                    // 获取小市场业绩
//                    CuMemberRetailAchieveVO retailAchieve = iCuMemberRetailAchieveService.selectMemberSumAchieve(tmpMember.getPkId(), CountryConstants.CHINA_COUNTRY, tmpMember.getSystemType());
//                    if (retailAchieve.getSmallAreaPv().compareTo(BigDecimal.ZERO) <= 0) {
//                        // 正常有区域业绩肯定达标，由2万突然变0基本不可能，此处暂时不处理
//                        log.info("定时任务区域有效， 会员 {} 小市场业绩归0，暂时不取消收益区域", tmpMember.getPkId());
//                        return;
//                    }
//                    // 2025.02.07 确认需求，如果是历史已经升上去的，还是走老逻辑只校验小市场
//                    String checkDate = "2025-02-10 00:00:00";
//                    if (EEnv.TEST.getValue().equals(HzsConfig.getEnv())) {
//                        checkDate = "2025-02-07 00:00:00";
//                    }
//                    if (tmpMember.getCreationTime().compareTo(DateUtils.parseDateOne(checkDate, DateUtils.YYYY_MM_DD_HH_MM_SS)) > 0) {
//                        if (retailAchieve.getSmallAreaPv().multiply(new BigDecimal("10000")).compareTo(SysConstants.SMALL_AREA_PV) < 0
//                                || retailAchieve.getBigArealPv().multiply(new BigDecimal("10000")).compareTo(SysConstants.SMALL_AREA_PV) < 0
//                        ) {
//                            // 大市场、小市场业绩小于2万，需要取消收益区域
//                            log.info("2.定时任务区域有效， 会员 {} 小市场业绩 {} 取消收益区域", tmpMember.getPkId(), retailAchieve.getSmallAreaPv());
//                            if (EEnv.TEST.getValue().equals(HzsConfig.getEnv())) {
//                                this.update(Wrappers.<CuMemberRetailRegion>lambdaUpdate()
//                                        .eq(CuMemberRetailRegion::getPkMember, tmpMember.getPkId())
//                                        .eq(CuMemberRetailRegion::getEffective, EYesNo.YES.getIntValue())
//                                        .set(CuMemberRetailRegion::getEffective, EYesNo.NO.getIntValue())
//                                        .set(CuMemberRetailRegion::getPkModified, tmpMember.getPkId())
//                                        .set(CuMemberRetailRegion::getModifiedTime, nowDate)
//                                );
//                            }
//                        }
//                    } else {
//                        if (retailAchieve.getSmallAreaPv().multiply(new BigDecimal("10000")).compareTo(SysConstants.SMALL_AREA_PV) < 0) {
//                            // 小市场业绩小于2万，需要取消收益区域
//                            log.info("1.定时任务区域有效， 会员 {} 小市场业绩 {} 取消收益区域", tmpMember.getPkId(), retailAchieve.getSmallAreaPv());
//                            if (EEnv.TEST.getValue().equals(HzsConfig.getEnv())) {
//                                this.update(Wrappers.<CuMemberRetailRegion>lambdaUpdate()
//                                        .eq(CuMemberRetailRegion::getPkMember, tmpMember.getPkId())
//                                        .eq(CuMemberRetailRegion::getEffective, EYesNo.YES.getIntValue())
//                                        .set(CuMemberRetailRegion::getEffective, EYesNo.NO.getIntValue())
//                                        .set(CuMemberRetailRegion::getPkModified, tmpMember.getPkId())
//                                        .set(CuMemberRetailRegion::getModifiedTime, nowDate)
//                                );
//                            }
//                        }
//                    }
                }
            });
        }
    }

    @Override
    public void cancelRegion(List<Long> pkIdList) {
        this.update(Wrappers.<CuMemberRetailRegion>lambdaUpdate()
                .in(CuMemberRetailRegion::getPkId, pkIdList)
                .eq(CuMemberRetailRegion::getEffective, EYesNo.YES.getIntValue())
                .set(CuMemberRetailRegion::getEffective, EYesNo.NO.getIntValue())
                .set(CuMemberRetailRegion::getPkModified, MagicNumberConstants.PK_ADMIN)
                .set(CuMemberRetailRegion::getModifiedTime, new Date())
        );
    }

    @Override
    public int getOrderCount(Long pkMember, Integer systemType, List<String> waresCodeList) {
        return baseMapper.getOrderCount(pkMember, systemType, waresCodeList);
    }

    @Override
    public void handleRepeatRegion() {
        for (ESystemType eSystemType : ESystemType.getEnableList()) {
            List<CuMemberRetailRegion> retailRegionList = baseMapper.listRepeatData(eSystemType.getValue());
            if (CollectionUtil.isNotEmpty(retailRegionList)) {
                retailRegionList.parallelStream().forEach(retailRegion -> {
                    baseMapper.updateRepeatDate(retailRegion.getProvince(), retailRegion.getCity(), retailRegion.getCounty(), eSystemType.getValue());
                });
            }
        }
    }

}
