package com.ruoyi.benyun.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.benyun.entity.ManageType;
import com.ruoyi.benyun.entity.StoreWd;
import com.ruoyi.benyun.entity.bo.StoreWdCategoryCount;
import com.ruoyi.benyun.entity.bo.StoreWdCategoryCountBody;
import com.ruoyi.benyun.entity.vo.ChannelAnalyseAceeptVo;
import com.ruoyi.benyun.entity.vo.ChannelMapAceeptVo;
import com.ruoyi.benyun.entity.vo.TagAnalyse;
import com.ruoyi.benyun.mapper.StoreWdDao;
import com.ruoyi.benyun.mapper.WdInfoDao;
import com.ruoyi.benyun.service.ChannelAnalyseService;
import com.ruoyi.benyun.entity.Brand;
import com.ruoyi.benyun.entity.WdInfo;
import com.ruoyi.benyun.mapper.BrandMapper;
import com.ruoyi.benyun.mapper.WdTopologicalInfoDao;
import com.ruoyi.benyun.utils.InitMapUtil;
import com.ruoyi.benyun.utils.WdRedisStoreage;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ChannelAnalyseServiceImpl implements ChannelAnalyseService {

    @Autowired
    WdInfoDao wdInfoDao;

    @Autowired
    InitMapUtil initMapUtil;

    @Autowired
    BrandMapper brandMapper;

    @Autowired
    WdTopologicalInfoDao wdTopologicalInfoDao;

    @Autowired
    private WdRedisStoreage wdRedisStoreage;


    @Autowired
    private StoreWdDao storeWdDao;


    @Override
    public HashMap cityTier(ChannelMapAceeptVo channelMapAceeptVo) {
        //1.统计结果
        HashMap<String, Long> result = new HashMap<>();
        result.put("一线", 0L);
        result.put("新一线", 0L);
        result.put("二线", 0L);
        result.put("三线", 0L);
        result.put("四线", 0L);
        result.put("五线", 0L);
        result.put("其他", 0L);


        //1.获取所有符合条件的网点信息
        QueryWrapper<WdInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("addr_code","count(*) as audit");
        assembleQueryWrapper(queryWrapper,channelMapAceeptVo);
        queryWrapper.groupBy("addr_code");
        List<WdInfo> wdInfos = wdInfoDao.selectList(queryWrapper);

        for (WdInfo wdInfo : wdInfos) {
            String initCityTierMap = initMapUtil.getInitCityTierMap(wdInfo.getAddrCode());
            if (initCityTierMap != null) {
                result.put(initCityTierMap, result.get(initCityTierMap) + wdInfo.getAudit());
            } else
                result.put("其他", result.get("其他") + wdInfo.getAudit());
        }


        return result;
    }

    @Override
    public PageInfo<Brand> brandList(ChannelAnalyseAceeptVo channelAnalyseAceeptVo) {
        String text = "";
        if (channelAnalyseAceeptVo.getSearchText() != null)
            text = channelAnalyseAceeptVo.getSearchText();
        PageHelper.startPage(channelAnalyseAceeptVo.getPageNum(), channelAnalyseAceeptVo.getPageSize());
        List<Brand> brands = brandMapper.searchList(text);
        PageInfo<Brand> pageInfo = new PageInfo<>(brands);
        return pageInfo;
    }


    @Override
    public HashMap<String, Object> tagAnalyse(ChannelMapAceeptVo channelMapAceeptVo) {
        //1.根据条件的到位网点信息
        QueryWrapper<WdInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("wd_id");
        assembleQueryWrapper(queryWrapper,channelMapAceeptVo);
        List<WdInfo> queryWd = wdInfoDao.selectList(queryWrapper);
        if (!queryWd.isEmpty()) {
            List<String> wdIds = queryWd.stream().map(item -> {
                return item.getWdId();
            }).collect(Collectors.toList());
            queryWd.clear();


            //分批统计
            int pageSizePoint = 20;
            int p = 0;
            int q = pageSizePoint;
            int total = 0;
            HashMap<String,Integer> hashMap = new HashMap<>();
            while(p < queryWd.size()){
                if(q >= queryWd.size())
                    q = queryWd.size();

                //统计
                total+=tagAnalyseItem(hashMap,wdIds.subList(p,q));
                p=q;
                q+=pageSizePoint;
            }

            //3.封装统计值
            HashMap<String, Object> result = new HashMap<>();
            List<TagAnalyse> list = new ArrayList<>();
            for (String s : hashMap.keySet()) {
                TagAnalyse tagAnalyse = new TagAnalyse();
                tagAnalyse.setName(s);
                tagAnalyse.setCount(hashMap.get(s));
                BigDecimal bigDecimal = new BigDecimal((double) tagAnalyse.getCount() / total);
                double v = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                tagAnalyse.setRadio(v);
                list.add(tagAnalyse);
            }

            //4.对结果集进行排序
            Collections.sort(list, new Comparator<TagAnalyse>() {
                @Override
                public int compare(TagAnalyse o1, TagAnalyse o2) {
                    return o2.getCount() - o1.getCount();
                }
            });

            //5.分页返回结果集
            int i = 1;
            int start = 0,end = 6;
            while(start<list.size()){
                if(end>=list.size())
                    end = list.size();
                result.put(""+i++,new ArrayList(list.subList(start,end)));
                start=end;
                end+=6;
            }
            result.put("pages",i-1);
            result.put("total",total);
            return result;
        }
        return new HashMap<>();
    }

    public int tagAnalyseItem(HashMap<String,Integer> hashMap,List<String> keys){
        //2.获取网点周边标签，并进行统计
        int total = 0;
        List<List<String>> wdTagList = wdRedisStoreage.getWdTagList(keys);
        for (List<String> list : wdTagList) {
            if (list == null || list.size() == 0)
                continue;
            for (String s : list) {
                Integer integer = hashMap.get(s);
                if (integer == null)
                    hashMap.put(s,1);
                else
                    hashMap.put(s,integer+1);
            }
            total++;
        }
        return total;
    }

    @Override
    public List<StoreWdCategoryCount> category(ChannelMapAceeptVo channelMapAceeptVo) {

        //2.组装条件构造器找到网点信息网点
        QueryWrapper<WdInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("wd_id");
        assembleQueryWrapper(queryWrapper,channelMapAceeptVo);

        //门店
        queryWrapper.and(queryWrapper1 -> {
            queryWrapper1.eq("wd_type_code","1");
        });
        List<WdInfo> wdInfos = wdInfoDao.selectList(queryWrapper);


        List<String> collect = wdInfos.stream().map(wdInfo -> {
            return wdInfo.getWdId();
        }).collect(Collectors.toList());
        QueryWrapper<StoreWd> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.select("manage_type_code","count(*) as comment_count")
            .in("wd_id",collect)
            .groupBy("manage_type_code");

        //5.查询周边网点结果，并统计
        List<StoreWd> storeWds = storeWdDao.selectList(queryWrapper1);
        HashMap<String,StoreWdCategoryCount> hashMap = new HashMap<>();
        for (StoreWd wdInfo : storeWds) {
            if(wdInfo.getManageTypeCode() == null || wdInfo.getManageTypeCode().equals(""))
                continue;

            String s = wdInfo.getManageTypeCode().substring(0, 4) + "00";
            StoreWdCategoryCount storeWdCategoryCount = hashMap.get(s);

            ManageType initManageType = initMapUtil.getInitManageType(wdInfo.getManageTypeCode());
            if (storeWdCategoryCount == null){
                StoreWdCategoryCountBody storeWdCategoryCountBody = new StoreWdCategoryCountBody();
                if(initManageType.getSubCategory() != null && !initManageType.getSubCategory().equals("")){
                    storeWdCategoryCountBody.setName(initManageType.getSubCategory());
                }else if(initManageType.getMidCategory() != null && !initManageType.getMidCategory().equals("")){
                    storeWdCategoryCountBody.setName(initManageType.getMidCategory());
                }else if (initManageType.getBigCategory() != null && !initManageType.getBigCategory().equals("")){
                    storeWdCategoryCountBody.setName(initManageType.getBigCategory());
                }
                storeWdCategoryCountBody.setManageTypeCode(wdInfo.getManageTypeCode());
                storeWdCategoryCountBody.setCount(wdInfo.getCommentCount());

                StoreWdCategoryCount storeWdCategoryCount1 = new StoreWdCategoryCount();
                storeWdCategoryCount1.setManageTypeCode(s);
                storeWdCategoryCount1.setName(initMapUtil.getInitManageType(s).getMidCategory());
                storeWdCategoryCount1.setCount(wdInfo.getCommentCount());
                ArrayList<StoreWdCategoryCountBody> list = new ArrayList<>();
                list.add(storeWdCategoryCountBody);
                storeWdCategoryCount1.setStoreWdCategoryCountBodyList(list);
                hashMap.put(s,storeWdCategoryCount1);
            }else {
                StoreWdCategoryCountBody storeWdCategoryCountBody = new StoreWdCategoryCountBody();
                if(initManageType.getSubCategory() != null && !initManageType.getSubCategory().equals("")){
                    storeWdCategoryCountBody.setName(initManageType.getSubCategory());
                }else if(initManageType.getMidCategory() != null && !initManageType.getMidCategory().equals("")){
                    storeWdCategoryCountBody.setName(initManageType.getMidCategory());
                }else if (initManageType.getBigCategory() != null && !initManageType.getBigCategory().equals("")){
                    storeWdCategoryCountBody.setName(initManageType.getBigCategory());
                }
                storeWdCategoryCountBody.setManageTypeCode(wdInfo.getManageTypeCode());
                storeWdCategoryCountBody.setCount(wdInfo.getCommentCount());

                storeWdCategoryCount.getStoreWdCategoryCountBodyList().add(storeWdCategoryCountBody);
                storeWdCategoryCount.setCount(storeWdCategoryCountBody.getCount()+storeWdCategoryCount.getCount());
                //hashMap.put(s,storeWdCategoryCount);
            }
        }

        //6.组装结果集
        List<StoreWdCategoryCount> storeWdCategoryCounts = new ArrayList<>();
        for (String s : hashMap.keySet()) {
            storeWdCategoryCounts.add(hashMap.get(s));
        }

        return storeWdCategoryCounts;
    }

    public void assembleQueryWrapper(QueryWrapper<WdInfo> queryWrapper,ChannelMapAceeptVo channelMapAceeptVo){
        //1.根据不同级别得到需要查询的 地区码
        List<String> addrCodeList = new ArrayList<>();
        if ("province".equals(channelMapAceeptVo.getRankType())) {
            //省码
            for (String s : channelMapAceeptVo.getAddrCode()) {
                String substring = s.substring(0, 2);
                addrCodeList.add(substring);
            }
        } else if ("city".equals(channelMapAceeptVo.getRankType())) {
            //省的所有市
            for (String s : channelMapAceeptVo.getAddrCode()) {
                String substring = s.substring(0, 2);
                addrCodeList.add(substring);
            }
        } else if ("zone".equals(channelMapAceeptVo.getRankType())) {
            //市的所有区
            for (String s : channelMapAceeptVo.getAddrCode()) {
                String substring = s.substring(0, 4);
                addrCodeList.add(substring);
            }
        } else if ("district".equals(channelMapAceeptVo.getRankType())){
            //区的所有街道
            for (String s : channelMapAceeptVo.getAddrCode()) {
                String substring = s.substring(0, 6);
                addrCodeList.add(substring);
            }
        }

        queryWrapper.in("wd_type_code", channelMapAceeptVo.getChannel()).and(originWdInfoQueryWrapper -> {
            for (String s : addrCodeList) {
                originWdInfoQueryWrapper.likeRight("addr_code", s).or();
            }
        });

        //搜索字段
        if (channelMapAceeptVo.getSearchText() != null && !channelMapAceeptVo.getSearchText() .trim().equals("")) {
            queryWrapper.and(originWdInfoQueryWrapper -> {
                originWdInfoQueryWrapper.like("wd_name", channelMapAceeptVo.getSearchText() );
            });
        }

        //城市等级分类
        if(channelMapAceeptVo.getCityTier() != null && channelMapAceeptVo.getCityTier().length > 0){
            List<String> tierCode = new ArrayList<>();
            for (String s : channelMapAceeptVo.getCityTier()) {
                List<String> list = initMapUtil.getInitCityTierListMap(s);
                if (list != null){
                    tierCode.addAll(list);
                }
            }
            queryWrapper.and(wdInfoQueryWrapper -> {
                for (String s : tierCode) {
                    wdInfoQueryWrapper.likeRight("addr_code", s).or();
                }
            });
        }

        //排序字段查询
        if (channelMapAceeptVo.getOrderby() != null && !channelMapAceeptVo.getOrderby().trim().equals("")) {
            PageHelper.orderBy(channelMapAceeptVo.getOrderby());
        }

    }

}
