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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.common.core.constant.CacheConstants;
import com.hzs.common.core.constant.MagicNumberConstants;
import com.hzs.common.core.enums.EGrade;
import com.hzs.common.core.enums.ENoticeWebsiteType;
import com.hzs.common.core.enums.ESystemType;
import com.hzs.common.core.enums.EYesNo;
import com.hzs.common.core.exception.ServiceException;
import com.hzs.common.core.service.RedisService;
import com.hzs.common.domain.member.ext.CuMemberRegionExt;
import com.hzs.common.domain.member.region.CuMemberRegion;
import com.hzs.common.domain.system.base.BdArea;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.member.base.mapper.CuMemberRegionMapper;
import com.hzs.member.base.param.MemberRegionParam;
import com.hzs.member.base.service.ICuMemberRegionService;
import com.hzs.member.base.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.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

/**
 * 新零售会员区域配置 服务实现类
 */
@Slf4j
@Service
public class CuMemberRegionServiceImpl extends ServiceImpl<CuMemberRegionMapper, CuMemberRegion> implements ICuMemberRegionService {


    @Autowired
    private RedisService redisService;

    @Override
    public CuMemberRegionExt getRegionByMember(Long pkMember, Integer type) {
        return baseMapper.getRegionByMember(pkMember, type);
    }

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

            if (null != param.getPkId()) {
                LocalDate previousDay = LocalDate.now().minusDays(1);
                LocalDateTime previousDayEnd = previousDay.atTime(23, 59, 59);
                Date result = Date.from(previousDayEnd.atZone(ZoneId.systemDefault()).toInstant());
                this.update(Wrappers.<CuMemberRegion>lambdaUpdate()
                                        .eq(CuMemberRegion::getPkId, param.getPkId())
//                        .eq(CuMemberRegion::getProvince, param.getProvince())
//                        .eq(CuMemberRegion::getCity, param.getCity())
//                        .eq(CuMemberRegion::getCounty, param.getCounty())
//                        .eq(CuMemberRegion::getPkMember, param.getPkMember())
//                        .eq(CuMemberRegion::getEffective, EYesNo.YES.getIntValue())
//                        .eq(CuMemberRegion::getSystemType, param.getSystemType())
                        .set(CuMemberRegion::getEffective, EYesNo.NO.getIntValue())
                        .set(CuMemberRegion::getPkModified, param.getPkMember())
                        .set(CuMemberRegion::getModifiedTime, new Date())
                        .set(CuMemberRegion::getEffectiveEndDate, result)
                );
            }
            // 新増数据
            CuMemberRegion retailRegion = CuMemberRegion.builder()
                    .pkMember(param.getPkMember())
                    .province(param.getProvince())
                    .city(param.getCity())
                    .county(param.getCounty())
                    // 数据来源会员端
                    .source(param.getSource())
                    .systemType(param.getSystemType())
                    .build();
            retailRegion.setPkCreator(param.getPkMember());
            Long regionVertexPkId = baseMapper.getRegionVertexPkIdByPkMember(retailRegion.getPkMember());
            retailRegion.setRegionVertexPkId(ObjectUtil.isEmpty(regionVertexPkId) ? 0L : regionVertexPkId);
            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, SecurityUtils.getUserId());
    }

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

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

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

    @Override
    public void checkRegion() {
        // 需要处理的会员列表
        List<CuMemberRegionExt> 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.<CuMemberRegion>lambdaUpdate()
                            .eq(CuMemberRegion::getPkMember, tmpMember.getPkId())
                            .eq(CuMemberRegion::getEffective, EYesNo.YES.getIntValue())
                            .set(CuMemberRegion::getEffective, EYesNo.NO.getIntValue())
                            .set(CuMemberRegion::getPkModified, tmpMember.getPkId())
                            .set(CuMemberRegion::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.<CuMemberRegion>lambdaUpdate()
//                                        .eq(CuMemberRegion::getPkMember, tmpMember.getPkId())
//                                        .eq(CuMemberRegion::getEffective, EYesNo.YES.getIntValue())
//                                        .set(CuMemberRegion::getEffective, EYesNo.NO.getIntValue())
//                                        .set(CuMemberRegion::getPkModified, tmpMember.getPkId())
//                                        .set(CuMemberRegion::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.<CuMemberRegion>lambdaUpdate()
//                                        .eq(CuMemberRegion::getPkMember, tmpMember.getPkId())
//                                        .eq(CuMemberRegion::getEffective, EYesNo.YES.getIntValue())
//                                        .set(CuMemberRegion::getEffective, EYesNo.NO.getIntValue())
//                                        .set(CuMemberRegion::getPkModified, tmpMember.getPkId())
//                                        .set(CuMemberRegion::getModifiedTime, nowDate)
//                                );
//                            }
//                        }
//                    }
                }
            });
        }
    }

    @Override
    public void cancelRegion(List<Long> pkIdList) {
        this.update(Wrappers.<CuMemberRegion>lambdaUpdate()
                .in(CuMemberRegion::getPkId, pkIdList)
                .eq(CuMemberRegion::getEffective, EYesNo.YES.getIntValue())
                .set(CuMemberRegion::getEffective, EYesNo.NO.getIntValue())
                .set(CuMemberRegion::getPkModified, MagicNumberConstants.PK_ADMIN)
                .set(CuMemberRegion::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<CuMemberRegion> retailRegionList = baseMapper.listRepeatData(eSystemType.getValue());
            if (CollectionUtil.isNotEmpty(retailRegionList)) {
                retailRegionList.parallelStream().forEach(retailRegion -> {
                    baseMapper.updateRepeatDate(retailRegion.getProvince(), retailRegion.getCity(), retailRegion.getCounty(), eSystemType.getValue());
                });
            }
        }
    }

    @Override
    public int validateBindCount(CuMemberRegionExt mrrExt, Integer yesOrNoValue, Integer systemType, Long pkId) {
        return baseMapper.validateBindCountA(mrrExt, yesOrNoValue, systemType, pkId);
    }

    @Override
    public int validateBindCount(MemberRegionParam mrrExt, Integer yesOrNoValue, Integer systemType, Long pkId) {
        return baseMapper.validateBindCountB(mrrExt, yesOrNoValue, systemType, pkId);
    }

    @Override
    public Long getRegionVertexPkIdByPkMember(Long pkMember) {
        return baseMapper.getRegionVertexPkIdByPkMember(pkMember);
    }

}
