package com.ruoyi.benyun.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.ruoyi.benyun.entity.vo.BrandEvolveVo;
import com.ruoyi.benyun.entity.vo.BrandOpcloseVo;
import com.ruoyi.benyun.entity.vo.ListQueryBody;
import com.ruoyi.benyun.service.BrandService;
import com.ruoyi.benyun.utils.CategoryUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.benyun.entity.*;
import com.ruoyi.benyun.entity.bo.*;
import com.ruoyi.benyun.mapper.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

@Service
public class BrandServiceImpl implements BrandService {
    @Autowired
    BrandMapper brandMapper;
    @Autowired
    BrandStatisticsMapper brandStatisticsMapper;
    @Autowired
    BrandProvinceMapper brandProvinceMapper;
    @Autowired
    BrandCityMapper brandCityMapper;
    @Autowired
    BrandZoneMapper brandZoneMapper;
    @Autowired
    EnterpriseMapper enterpriseMapper;
    @Autowired
    AttentionPoolDao attentionPoolDao;
    @Autowired
    CategoryMapper categoryMapper;
    @Autowired
    StoreWdDao storeWdDao;
    @Autowired
    WdTopologicalInfoDao wdTopologicalInfoDao;
    @Autowired
    TypeByDao typeByDao;
    @Autowired
    WdInfoServiceImpl wdInfoService;
    @Autowired
    BrandStoreOpcloseDao storeOpcloseDao;
    @Autowired
    CategoryUtil categoryUtil;
    @Autowired
    BrandEvolveDao brandEvolveDao;

    @Override
    public List<BrandSearch> searchByLikeName(String text) {
        List<Brand> list = brandMapper.searchList(text);
        List<BrandSearch> sList = new ArrayList<>();
        for (Brand brand : list){
            Enterprise enterprise = enterpriseMapper.searchByUsci(brand.getEnterpriseUsci());
            BrandSearch bs = new BrandSearch();
            bs.setBrandId(brand.getBrandId());
            bs.setBrandName(brand.getBrandName());
            if (enterprise != null)
                bs.setEnterpriseName(enterprise.getEnterpriseName());
            bs.setUpdateTime(brand.getUpdateTime());
            sList.add(bs);
        }
        return sList;
    }

    @Override
    public BrandInfo searchByBrandId(String brandId, String userId) {
        Brand brand = brandMapper.searchById(brandId);
        BrandInfo info = new BrandInfo();
        if (brand != null){
            Enterprise enterprise = enterpriseMapper.searchByUsci(brand.getEnterpriseUsci());
            info.setBrandId(brandId);
            info.setBrandName(brand.getBrandName());
            info.setBrandImg(brand.getBrandImg());
//            info.setIndexScore(brand.getIndexScore());
            if (enterprise != null){
                info.setEnterpriseUsci(enterprise.getEnterpriseUsci());
                info.setEnterpriseName(enterprise.getEnterpriseName());
                info.setAddrCode(enterprise.getAddrCode());
                info.setAddrInfo(enterprise.getAddrInfo());
            }
            info.setUpdateTime(brand.getUpdateTime());
            QueryWrapper<AttentionPool> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("brand_id",brandId);
            queryWrapper.eq("wd_id","");
            AttentionPool pool = attentionPoolDao.selectOne(queryWrapper);
            if (pool == null)
                info.setAttention(0);
            else
                info.setAttention(1);
        }else return null;
        return info;
    }

    @Override
    public BrandProperty searchPropertyByBrandId(String brandId) {
        BrandStatistics brandStatistics = brandStatisticsMapper.searchByBrandId(brandId);
        Brand brand = brandMapper.searchById(brandId);
        BrandProperty bp = new BrandProperty();
        if (brand != null){
            bp.setIndustryCode(brand.getIndustryCode());
            if (brand.getIndustryCode() == null || brand.getIndustryCode().equals(""))
                bp.setIndustryName("");
            else{
                Category category = categoryMapper.searchSubIndustryByCode(brand.getIndustryCode());
                bp.setIndustryName(category.getName());
            }
//            bp.setPerCapitaConsumption(brand.getPerCapitaConsumption());
//            bp.setCommentCount(brand.getCommentCount());
//            bp.setScore(brand.getScore());
        }else {
            bp.setIndustryName("****");
            bp.setPerCapitaConsumption(null);
            bp.setCommentCount(null);
            bp.setScore(null);
        }
        if (brandStatistics != null){
            float activeRatio = (float) brandStatistics.getBusinessCount()/brandStatistics.getTotal();
            bp.setActiveRatio((int)(activeRatio*100)+"%");
        }else {
            bp.setActiveRatio("****");
        }
        return bp;
    }

    @Override
    public List<BrandSimilar> searchSimilarByBrandId(String brandId) {
        return null;
    }

    @Override
    public List<BrandStatus> searchStatusByBrandId(String brandId) {
        return null;
    }

    @Override
    public BrandDistribution searchDistributionByBrandId(String brandId) {
        return null;
    }

    @Override
    public List<BrandProvinceBo> searchProvinceByBrandId(String brandId) {
        return null;
    }

    @Override
    public BrandDisCloud searchDisCloudByBrandId(String brandId) {
        return null;
    }

    @Override
    public PageInfo<List<BrandSearch>> searchListByMulti(ListQueryBody body, String userId) {
        return null;
    }

    @Override
    public List<BrandTotal> searchTotal(Integer pageSize) {
        return null;
    }

    @Override
    public List<BrandGeoLabelBo> searchGeoLabel(String brandId) {
        return null;
    }

    @Override
    public List<BrandOpcloseVo> searchOpenByMulti(List<String> typeCodes, LocalDateTime startTime, LocalDateTime endTime) {
        return null;
    }

    @Override
    public List<BrandOpcloseVo> searchCloseByMulti(List<String> typeCodes, LocalDateTime startTime, LocalDateTime endTime) {
        return null;
    }

    @Override
    public List<BrandEvolveVo> searchEvolveByMulti(List<String> addrCodes, List<String> typeCodes, List<String> brandIds) {
        return null;
    }

//    @Override
//    public List<BrandSimilar> searchSimilarByBrandId(String brandId) {
////        先查询品牌id得到industryCode
//        Brand brand = brandMapper.searchById(brandId);
//        if (brand == null)
//            return new ArrayList<>();
////        再根据industryCode得到其他品牌的信息
//        if (brand.getIndustryCode() == null)
//            return new ArrayList<>();
//        List<Brand> brands = brandMapper.searchByIndustryCodeList(brandId, brand.getIndustryCode());
//        if (brands.isEmpty())
//            return new ArrayList<>();
//        List<BrandSimilar> similarList = new ArrayList<>();
//        for (Brand b : brands){
//            BrandSimilar bs = new BrandSimilar();
//            bs.setBrandId(b.getBrandId());
//            bs.setBrandImg(b.getBrandImg());
//            bs.setBrandName(b.getBrandName());
//            bs.setUpdateTime(b.getUpdateTime());
//            similarList.add(bs);
//        }
//        return similarList;
//    }

//    @Override
//    public List<BrandStatus> searchStatusByBrandId(String brandId) {
////        查询状态后拆分
//        BrandStatistics statistics = brandStatisticsMapper.searchByBrandId(brandId);
//        if (statistics == null)
//            return new ArrayList<>();
//        int businessCount = statistics.getBusinessCount();
//        int pauseBusinessCount = statistics.getPauseBusinessCount();
//        int noBusinessCount = statistics.getNoBusinessCount();
//        List<BrandStatus> statuses = new ArrayList<>();
//        if (businessCount != 0){
//            BrandStatus status = new BrandStatus();
//            status.setBusinessStatus("正常");
//            status.setCount(businessCount);
//            statuses.add(status);
//        }
//        if (pauseBusinessCount != 0){
//            BrandStatus status = new BrandStatus();
//            status.setBusinessStatus("暂停");
//            status.setCount(pauseBusinessCount);
//            statuses.add(status);
//        }
//        if (noBusinessCount != 0){
//            BrandStatus status = new BrandStatus();
//            status.setBusinessStatus("尚未营业");
//            status.setCount(noBusinessCount);
//            statuses.add(status);
//        }
//        return statuses;
//    }

//    @Override
//    public BrandDistribution searchDistributionByBrandId(String brandId) {
////        省份:31
////        城市:342
////        区县:2989
////        查询统计并附加信息
//        int province = 31;
//        int city = 342;
//        int zone = 2989;
//        BrandStatistics statistics = brandStatisticsMapper.searchByBrandId(brandId);
//        if (statistics == null)
//            return null;
//        BrandDistribution bd = new BrandDistribution();
//        int cpc = statistics.getCoverProvinceCount();
//        int ccc = statistics.getCoverCityCount();
//        int czc = statistics.getCoverZoneCount();
//        bd.setTotal(statistics.getTotal());
//        bd.setCoverProvinceCount(cpc);
//        float provinceRatio = (float) cpc/province;
//        bd.setCoverProvinceRatio((int)(provinceRatio*100) + "%");
//        bd.setCoverCityCount(ccc);
//        float cityRatio = (float) ccc/city;
//        bd.setCoverCityRatio((int)(cityRatio*100) + "%");
//        bd.setCoverZoneCount(czc);
//        float zoneRatio = (float) czc/zone;
//        bd.setCoverZoneRatio((int)(zoneRatio*100) + "%");
//        return bd;
//    }

//    @Override
//    public List<BrandProvinceBo> searchProvinceByBrandId(String brandId) {
//        List<BrandProvince> provinces = brandProvinceMapper.searchByBrandId(brandId);
//        BrandStatistics statistics = brandStatisticsMapper.searchByBrandId(brandId);
//        if (provinces.isEmpty() || statistics == null)
//            return new ArrayList<>();
//        int total = statistics.getTotal();
//        List<BrandProvinceBo> bpbs = new ArrayList<>();
//        for (BrandProvince bp : provinces){
//            int disCount = bp.getDisCount();
//            BrandProvinceBo bpb = new BrandProvinceBo();
////            bpb.setBrandId(bp.getBrandId());
//            bpb.setCode(bp.getAddrCode());
//            bpb.setName(bp.getProvince());
//            bpb.setLocation(bp.getLat().toString() + "," + bp.getLng().toString());
//            bpb.setCount(disCount);
//            float ratio = (float) disCount/total;
//            bpb.setRatio((ratio*100) + "%");
//            bpb.setUpdateTime(bp.getUpdateTime());
//            bpbs.add(bpb);
//        }
//        return bpbs;
//    }

//    @Override
//    public BrandDisCloud searchDisCloudByBrandId(String brandId) {
//        List<BrandCity> brandCities = brandCityMapper.searchByBrandId(brandId);
//        List<BrandZone> brandZones = brandZoneMapper.searchByBrandId(brandId);
//        BrandDisCloud disCloud = new BrandDisCloud();
//        List<BrandDisItem> zoneDis = new ArrayList<>();
//        List<BrandDisItem> cityDis = new ArrayList<>();
//        for (BrandZone bz : brandZones){
//            BrandDisItem bdi = new BrandDisItem();
//            bdi.setCode(bz.getAddrCode());
//            bdi.setName(bz.getZone());
//            bdi.setCount(bz.getDisCount());
//            zoneDis.add(bdi);
//        }
//        for (BrandCity bc : brandCities){
//            BrandDisItem bdi = new BrandDisItem();
//            bdi.setCode(bc.getAddrCode());
//            bdi.setName(bc.getCity());
//            bdi.setCount(bc.getDisCount());
//            cityDis.add(bdi);
//        }
//        disCloud.setZoneDistribution(zoneDis);
//        disCloud.setCityDistribution(cityDis);
//        return disCloud;
//    }

//    @Override
//    public PageInfo<List<BrandSearch>> searchListByMulti(ListQueryBody body, String userId) {
//        PageHelper.startPage(body.getPageNum(),body.getPageSize(),true);
//        String text = body.getText();
//        List<String> industryCode = body.getIndustryCode();
//        Integer countDown = null;
//        Integer countUp = null;
//        Integer coverDown = null;
//        Integer coverUp = null;
//        if (body.getWdCount() != null){
//            if (body.getWdCount().size() == 1)
//                countDown = Integer.parseInt(body.getWdCount().get(0));
//            else if (body.getWdCount().size() >= 2){
//                countDown = Integer.parseInt(body.getWdCount().get(0));
//                countUp = Integer.parseInt(body.getWdCount().get(1));
//            }
//        }
//        if (body.getCoverCityCount() != null){
//            if (body.getCoverCityCount().size() == 1){
//                coverDown = Integer.parseInt(body.getCoverCityCount().get(0));
//            }else if (body.getCoverCityCount().size() >= 2){
//                coverDown = Integer.parseInt(body.getCoverCityCount().get(0));
//                coverUp = Integer.parseInt(body.getCoverCityCount().get(1));
//            }
//        }
////        System.out.println(countDown+","+countUp);
////        System.out.println(coverDown+","+coverUp);
//        List<BrandSearch> brandSearches = brandMapper.searchSearchByMulti(text, industryCode, countUp, countDown, coverUp, coverDown);
//        if (userId == null || userId.equals("")){
//            for (BrandSearch search : brandSearches){
//                search.setAttention(0);
//            }
//        }else {
//            List<AttentionPool> pools = attentionPoolDao.searchByMulti(null, userId);
//            Map<String ,String> map = new HashMap<>();
//            for (AttentionPool pool : pools){
//                map.put(pool.getBrandId(),"1");
//            }
//            for (BrandSearch search : brandSearches){
//                if (map.get(search.getBrandId()) == null){
//                    search.setAttention(0);
//                }else {
//                    search.setAttention(1);
//                }
//            }
//        }
//        return new PageInfo(brandSearches);
//    }

//    @Override
//    public List<BrandTotal> searchTotal(Integer pageSize) {
//        List<BrandStatistics> list = brandStatisticsMapper.searchList();
//        if (list.isEmpty())
//            return new ArrayList<>();
//        List<BrandTotal> tList = new ArrayList<>();
//        if (pageSize == null)
//            pageSize = 10;
//        int index = 0;
//        for (BrandStatistics bs : list){
//            if (index >= pageSize)
//                break;
//            BrandTotal bt = new BrandTotal();
//            bt.setBrandId(bs.getBrandId());
//            bt.setBrandName(bs.getBrandName());
//            bt.setTotal(bs.getTotal());
//            bt.setUpdateTime(bs.getUpdateTime());
//            tList.add(bt);
//            index++;
//        }
//        return tList;
//    }

//    @Override
//    public BStoreData searchAvgScoreByBrandId(String brandId) {
//        Brand brand = brandMapper.searchById(brandId);
//        if (brand == null)
//            return null;
//        BStoreData bStoreData = new BStoreData();
//        bStoreData.setBrandName(brand.getBrandName());
//        List<BrandZone> zones = brandZoneMapper.searchByBrandId(brandId);
//        if (zones.isEmpty())
//            return null;
//        List<Info> infos = new ArrayList<>();
//        wdInfoService.setAddrMap();
//        for (BrandZone bz : zones){
//            Info info = new Info();
//            info.setAddrCode(bz.getAddrCode());
//            info.setAddrName(wdInfoService.addrMap.get(bz.getAddrCode()));
//            info.setAvgScore(bz.getAvgScore());
//            infos.add(info);
//        }
//        bStoreData.setInfo(infos);
//        return bStoreData;
//    }

//    @Override
//    public List<BrandAddrDistribution> searchAddrDistribution(List<String> addrCodes) {
//        List<BrandAddrDistribution> list = brandZoneMapper.searchByAddrCodeGroup(addrCodes);
//        wdInfoService.setAddrMap();
//        for (BrandAddrDistribution dis : list){
//            dis.setAddrName(wdInfoService.addrMap.get(dis.getAddrCode()));
//        }
//        return list;
//    }

//    @Override
//    public List<BrandGeoLabelBo> searchGeoLabel(String brandId) {
//        List<BrandGeoLabelBo> bos = new ArrayList<>();
//
//        // 查询门店
//        QueryWrapper<StoreWd> storeWdQueryWrapper = new QueryWrapper<>();
//        storeWdQueryWrapper.eq("brand_id",brandId);
//        List<StoreWd> storeWds = storeWdDao.selectList(storeWdQueryWrapper);
//        if (storeWds.size() == 0)
//            return bos;
//
//        // 查询门店标签
//        int count = storeWds.size(); // 总数，用于做比率
//        QueryWrapper<WdTopologicalInfo> infoQueryWrapper = new QueryWrapper<>();
//        List<String> wdIds = new ArrayList<>();
//        for (StoreWd storeWd : storeWds){
//            wdIds.add(storeWd.getWdId());
//        }
//        infoQueryWrapper.eq("radius",1000).and(info -> {
//            info.in("center_wd_id",wdIds);
//        });
//        List<WdTopologicalInfo> infos = wdTopologicalInfoDao.selectList(infoQueryWrapper);
//        // 统计标签
//        Map<String,Integer> typeMap = new HashMap<>();
//        for (WdTopologicalInfo info : infos){
//            String tag = info.getTag();
//            String[] tags = tag.split(";");
//            for (String t : tags){
//                String[] split = t.split(":");
//                if (split.length < 2)
//                    continue;
//                if (typeMap.get(split[0]) != null){
//                    typeMap.replace(split[0],typeMap.get(split[0])+Integer.parseInt(split[1]));
//                }
//                typeMap.put(split[0],Integer.parseInt(split[1]));
//            }
//        }
//        Set<String> keySet = typeMap.keySet();
//        QueryWrapper<TypeBy> typeByQueryWrapper = new QueryWrapper<>();
//        typeByQueryWrapper.in("type_code_by",keySet).and(typeByQueryWrapper1 -> {
//            typeByQueryWrapper1.ne("mid_category","");
//        }).and(typeByQueryWrapper1 -> {
//            typeByQueryWrapper1.ne("sub_category","");
//        });

        // 排序
//        Map<String,Integer> sortMap = new LinkedHashMap<>();
//        typeMap.entrySet()
//            .stream().sorted(Map.Entry.comparingByValue())
//            .forEachOrdered(x -> sortMap.put(x.getKey(),x.getValue()));
//        List<Map.Entry<String,Integer>> sortMap = new ArrayList<>(typeMap.entrySet());
//        Collections.sort(sortMap, new Comparator<Map.Entry<String, Integer>>() {
//            @Override
//            public int compare(Map.Entry<String, Integer> t1, Map.Entry<String, Integer> t2) {
//                return t2.getValue().compareTo(t1.getValue()); // 降序
//            }
//        });
//        // 获取前10项
//        List<String> searchList = new ArrayList<>();
//        for (int i=0;i<sortMap.size();i++){
//            // System.out.println(sortMap.get(i).getKey()+" "+sortMap.get(i).getValue());
//            searchList.add(sortMap.get(i).getKey());
//            if (searchList.size() >= 10)
//                break;
//        }
//        // 查询标签
//        QueryWrapper<TypeBy> typeByQueryWrapper = new QueryWrapper<>();
//        typeByQueryWrapper.in("type_code_by",searchList);
//        List<TypeBy> typeByList = typeByDao.selectList(typeByQueryWrapper);
//        // 赋值
//        for (TypeBy typeBy : typeByList){
//            BrandGeoLabelBo bo = new BrandGeoLabelBo();
//            bo.setCode(typeBy.getTypeCodeBy());
//            bo.setTotal(typeMap.get(typeBy.getTypeCodeBy()));
//            if (!typeBy.getSubCategory().equals("")){
//                bo.setName(typeBy.getSubCategory());
//            }else if (!typeBy.getMidCategory().equals("")){
//                bo.setName(typeBy.getMidCategory());
//            }else{
//                bo.setName(typeBy.getBigCategory());
//            }
//            float ratio = (float) bo.getTotal()/count;
//            bo.setRatio((ratio*100) + "%");
//            bos.add(bo);
//        }
//        bos.sort(new Comparator<BrandGeoLabelBo>() {
//            @Override
//            public int compare(BrandGeoLabelBo t1, BrandGeoLabelBo t2) {
//                return t2.getTotal().compareTo(t1.getTotal());
//            }
//        });
//        return bos;
//    }

//    @Override
//    public List<BrandOpcloseVo> searchOpenByMulti(List<String> typeCodes, LocalDateTime startTime, LocalDateTime endTime) {
//        List<String> codes = new ArrayList<>();
//        if (typeCodes != null){
//            for (String code : typeCodes){
//                codes.add(code);
//                List<String> otherTypeBy = categoryUtil.getAllOtherTypeBy(code);
//                codes.addAll(otherTypeBy);
//            }
//        }else{
//            codes = null;
//        }
//        List<BrandOpcloseVo> vos = storeOpcloseDao.selectOpenByMulti(codes, startTime, endTime);
//        return vos.subList(0, 9);
//    }

//    @Override
//    public List<BrandOpcloseVo> searchCloseByMulti(List<String> typeCodes, LocalDateTime startTime, LocalDateTime endTime) {
//        List<String> codes = new ArrayList<>();
//        if (typeCodes != null){
//            for (String code : typeCodes){
//                codes.add(code);
//                List<String> otherTypeBy = categoryUtil.getAllOtherTypeBy(code);
//                codes.addAll(otherTypeBy);
//            }
//        }else{
//            codes = null;
//        }
//        List<BrandOpcloseVo> vos = storeOpcloseDao.selectCloseByMulti(codes, startTime, endTime);
//        return vos.subList(0,9);
//    }

//    @Override
//    public List<BrandEvolveVo> searchEvolveByMulti(List<String> addrCodes, List<String> typeCodes, List<String> brandIds) {
//        List<String> addrs = new ArrayList<>();
//        if (addrCodes != null){
//            for (String code : addrCodes){
//                addrs.add(code);
//                List<String> otherAddrCode = categoryUtil.getAllOtherAddrCode(code);
//                addrs.addAll(otherAddrCode);
//            }
//        }else{
//            addrs = null;
//        }
//        List<String> types = new ArrayList<>();
//        if (typeCodes != null){
//            for (String code : typeCodes){
//                types.add(code);
//                List<String> otherTypeBy = categoryUtil.getAllOtherTypeBy(code);
//                types.addAll(otherTypeBy);
//            }
//        }else{
//            types = null;
//        }
//        List<BrandEvolveVo> vos = new ArrayList<>();
//        for (String brandId : brandIds){
//            List<BrandEvolveVo> evolveVos = brandEvolveDao.selectByMulti(addrs, types, brandId);
//            for (int i=0; i<evolveVos.size(); i++){
//                if (i == 0)
//                    continue;
//                evolveVos.get(i).setTotal(evolveVos.get(i-1).getTotal()+evolveVos.get(i).getTotal());
//            }
//            vos.addAll(evolveVos);
//        }
//        return vos;
//    }
}
