package shop.alien.store.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import shop.alien.entity.store.ExpertImg;
import shop.alien.entity.store.LifeNotice;
import shop.alien.entity.store.LifeUser;
import shop.alien.entity.store.LifeUserExpert;
import shop.alien.entity.store.vo.LifeUserExpertVo;
import shop.alien.mapper.ExpertImgMapper;
import shop.alien.mapper.LifeNoticeMapper;
import shop.alien.mapper.LifeUserExpertMapper;
import shop.alien.mapper.LifeUserMapper;
import shop.alien.store.service.StoreUserExpertService;
import shop.alien.util.type.LifeNoticeUtil;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 商户达人表 服务实现类
 * </p>
 *
 * @author fcw
 * @since 2025-02-28
 */
@Service
@RequiredArgsConstructor
public class StoreUserExpertServiceImpl extends ServiceImpl<LifeUserExpertMapper, LifeUserExpert> implements StoreUserExpertService {

    private final LifeUserExpertMapper lifeUserExpertMapper;

    private final ExpertImgMapper expertImgMapper;

    private final LifeNoticeMapper lifeNoticeMapper;

    private final LifeNoticeUtil lifeNoticeUtil;

    private final LifeUserMapper lifeUserMapper;

    @Override
    public List<LifeUserExpertVo> getRankList() {
        return lifeUserExpertMapper.getRankList();
    }

    @Override
    public List<Map<String, LifeUserExpertVo>> getExpertDetails(Integer expertId) {
        // 达人信息
        List<LifeUserExpertVo> expertDetails = lifeUserExpertMapper.getExpertDetails(expertId);
        List<Map<String, LifeUserExpertVo>> result = new ArrayList<>();
        for (LifeUserExpertVo expertVo : expertDetails) {
            // 获取粉丝画像
            LifeUserExpertVo fanPortrait = getFanPortrait(expertVo.getId());

            Map<String, LifeUserExpertVo> map = new HashMap<>();
            map.put("expertDetails", expertVo);
            map.put("fanPortrait", fanPortrait);
            result.add(map);
        }

        return result;

    }

    @Override
    public List<LifeUserExpertVo> ifExpert(String id) {
        return lifeUserExpertMapper.ifExpert(id);
    }


    private LifeUserExpertVo getFanPortrait(Integer id) {
        List<LifeUserExpertVo> expertInfoList = lifeUserExpertMapper.getFanPortrait(id);

        // 省---------------------------------------------------------------------------------------------------------------------------------------------
        List<Map<String, String>> provincePercentage = new ArrayList<>();
        List<LifeUserExpertVo> provinceList = expertInfoList.stream().filter(item -> StringUtils.isNotEmpty(item.getProvince())).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(provinceList)) {
            Map<String, Double> provincePercentageMap = provinceList.stream()
                    .collect(Collectors.groupingBy(LifeUserExpertVo::getProvince, Collectors.collectingAndThen(
                            Collectors.counting(), // 统计每个省份的数量
                            count -> (double) count / provinceList.size() * 100 // 计算占比
                    )));

            // 按占比排序
            List<Map.Entry<String, Double>> provincePercentageList = provincePercentageMap.entrySet().stream()
                    .sorted(Map.Entry.<String, Double>comparingByValue().reversed()) // 按占比降序排序
                    .collect(Collectors.toList());

            // 转化为map
            provincePercentage = provincePercentageList.stream()
                    .map(entry -> {
                        Map<String, String> map = new HashMap<>();
                        map.put("province", entry.getKey());
                        map.put("percentage", String.valueOf(entry.getValue()));
                        return map;
                    })
                    .collect(Collectors.toList());
        }
        // 省---------------------------------------------------------------------------------------------------------------------------------------------

        // 市---------------------------------------------------------------------------------------------------------------------------------------------
        List<Map<String, String>> cityPercentage = new ArrayList<>();
        List<LifeUserExpertVo> cityList = expertInfoList.stream().filter(item -> StringUtils.isNotEmpty(item.getCity())).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(cityList)) {
            Map<String, Double> cityPercentageMap = cityList.stream()
                    .collect(Collectors.groupingBy(LifeUserExpertVo::getCity, Collectors.collectingAndThen(
                            Collectors.counting(), // 统计每个市的数量
                            count -> (double) count / cityList.size() * 100 // 计算占比
                    )));

            // 按占比排序
            List<Map.Entry<String, Double>> cityPercentageList = cityPercentageMap.entrySet().stream()
                    .sorted(Map.Entry.<String, Double>comparingByValue().reversed()) // 按占比降序排序
                    .collect(Collectors.toList());

            // 转化为map
            cityPercentage = cityPercentageList.stream()
                    .map(entry -> {
                        Map<String, String> map = new HashMap<>();
                        map.put("city", entry.getKey());
                        map.put("percentage", String.valueOf(entry.getValue()));
                        return map;
                    })
                    .collect(Collectors.toList());
        }
        // 市---------------------------------------------------------------------------------------------------------------------------------------------

        // 年龄--------------------------------------------------------------------------------------------------------------------------------------------
        Map<String, Double> agePercentageMap = new HashMap<>();
        List<LifeUserExpertVo> ageInfoList = expertInfoList.stream().filter(item -> null != item.getUserBrithday()).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(ageInfoList)) {
            List<String> ageList = ageInfoList.stream().map(item -> {
                LocalDate brithDay = item.getUserBrithday().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                Period period = Period.between(brithDay, LocalDate.now());
                String flag = "";
                if (period.getYears() < 12) {
                    flag = "12以下";
                } else if (period.getYears() < 23) {
                    flag = "12-22";
                } else if (period.getYears() < 33) {
                    flag = "23-32";
                } else if (period.getYears() < 43) {
                    flag = "33-42";
                } else if (period.getYears() < 53) {
                    flag = "43-52";
                } else {
                    flag = "53以上";
                }
                return flag;
            }).collect(Collectors.toList());

            agePercentageMap = ageList.stream()
                    .collect(Collectors.groupingBy(String::toString, Collectors.collectingAndThen(
                            Collectors.counting(),
                            count -> (double) count / ageList.size() * 100 // 计算占比
                    )));
        }

        // 转化为map
        List<String> ageFlagList = Arrays.asList("12以下", "12-22", "23-32", "33-42", "43-52", "53以上");
        List<Map<String, String>> agePercentage = new ArrayList<>();
        for (String flag : ageFlagList) {
            Map<String, String> map = new HashMap<>();
            map.put("age", flag);
            map.put("percentage", String.valueOf(agePercentageMap.getOrDefault(flag, 0.0)));
            agePercentage.add(map);
        }
        // 年龄--------------------------------------------------------------------------------------------------------------------------------------------

        // 性别--------------------------------------------------------------------------------------------------------------------------------------------
        double manPercentage = 0;
        List<LifeUserExpertVo> sexList = expertInfoList.stream().filter(item -> StringUtils.isNotEmpty(item.getUserSex())).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(sexList)) {
            double manCount = (double) sexList.stream().filter(item -> "男".equals(item.getUserSex())).count();
            manPercentage = manCount / sexList.size() * 100; // 计算占比
        }

        List<Map<String, String>> sexPercentage = new ArrayList<>();
        Map<String, String> manMap = new HashMap<>();
        manMap.put("sex", "男");
        manMap.put("percentage", String.valueOf(manPercentage));
        sexPercentage.add(manMap);
        Map<String, String> womanMap = new HashMap<>();
        womanMap.put("sex", "女");
        womanMap.put("percentage", CollectionUtils.isNotEmpty(sexList) ? String.valueOf(100 - manPercentage) : "0");
        sexPercentage.add(womanMap);
        // 性别--------------------------------------------------------------------------------------------------------------------------------------------

        LifeUserExpertVo expertVo = new LifeUserExpertVo();
        expertVo.setProvincePercentageList(provincePercentage);
        expertVo.setCityPercentageList(cityPercentage);
        expertVo.setAgePercentageList(agePercentage);
        expertVo.setSexPercentageList(sexPercentage);
        return expertVo;
    }

    @Override
    public Map<String, String> getapplyExpert(ExpertImg expertImgs) {
        Map<String, String> result = new HashMap<>();
        //先对expertImgs进行判断若为空直接返回若不为空则进行保存操作
        if (expertImgs == null) {
            result.put("参数异常", "false");
            return result;
        }
        LifeUserExpert expert = new LifeUserExpert();
        expert.setUserId(expertImgs.getUserId());
        expert.setDeleteFlag(0);
        expert.setCreatedTime(new Date());
        expert.setUpdatedTime(new Date());
        expert.setExpertStatus(1);
        expert.setAddExplanation(expertImgs.getAddExplanation());
        lifeUserExpertMapper.insert(expert);
        Integer insertedId = expert.getId();
        for (String imgUrl : expertImgs.getImgUrl().split(",")) {
            ExpertImg expertImg = new ExpertImg();
            expertImg.setImgUrl(imgUrl);
            expertImg.setDeleteFlag(0);
            expertImg.setCreatedTime(new Date());
            expertImg.setUpdatedTime(new Date());
            expertImg.setExpertId(insertedId);
            expertImg.setImgType(0);
            expertImg.setUserId(expertImgs.getUserId());
            expertImg.setPromoteType(expertImgs.getPromoteType());
            expertImgMapper.insert(expertImg);
        }
        //发送消息
        LifeUser lifeUser = lifeUserMapper.selectById(expertImgs.getUserId());
        LifeNotice lifeMessage = new LifeNotice();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDate = LocalDateTime.now().format(formatter);
        String text = "您在"+formattedDate+"申请成为达人，信息已提交至平台审核，1-3个工作日会将审核结果发送到您应用内的消息-通知中，请注意查收";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message", text);
        lifeMessage.setReceiverId("user_"+lifeUser.getUserPhone());
        lifeMessage.setTitle("申请达人通知");
        lifeMessage.setContext(jsonObject.toJSONString());
        lifeMessage.setNoticeType(1);
        lifeMessage.setIsRead(0);
        lifeMessage.setDeleteFlag(0);
        lifeMessage.setSenderId("system");
        lifeNoticeUtil.fillUserTypeAndRefId(lifeMessage);
        lifeNoticeMapper.insert(lifeMessage);
        return result;
    }


}
