package com.kiisoo.ic.ls.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kiisoo.ic.customer.entity.OpCustomer;
import com.kiisoo.ic.customer.mapper.OpCustomerDOMapper;
import com.kiisoo.ic.customer.service.CustomerViewService;
import com.kiisoo.ic.generalize.entity.PrivilageOrganizational;
import com.kiisoo.ic.generalize.service.RetailCompanyService;
import com.kiisoo.ic.ls.bean.*;
import com.kiisoo.ic.store.entity.PoiStore;
import com.kiisoo.ic.store.mapper.PoiStoreDOMapper;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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


/**
 * @Description: 大屏数据分析service
 * @Auther: yechenhao
 * @Date: 2020/5/11 14:54
 * @Version: v1
 */
@Service
public class LargeScreenAnalysisService {


    static final Long LEVEL_COMPANY_L = 2L;

    @Autowired
    private RetailCompanyService retailCompanyService;

    @Autowired
    private PoiStoreDOMapper poiStoreDOMapper;

    @Autowired
    private CustomerViewService customerViewService;

    @Autowired
    private OpCustomerDOMapper opCustomerDOMapper;

    /**
     * 查询零售公司店均拓客TOP10
     * @param startDate 开始时间
     * @param endDate 结束时间
     * @return
     */
    public List<CompanyAvgAddDTO> listCompanyAvgAddTop(Long userId,String startDate, String endDate) {
        List<CompanyAvgAddDTO> results = null;
        //初始化所有零售公司
        List<PrivilageOrganizational> companyList = retailCompanyService.listOfRetailOrg(userId, null, null, null).stream().filter(org -> LEVEL_COMPANY_L.equals(org.getLevel())).distinct().collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(companyList)){
            results = new ArrayList<>();
            for (PrivilageOrganizational company : companyList) {
                //查询零售公司下所有店铺
                List<PoiStore> poiStores = poiStoreDOMapper.selectShopByCompany(company.getId());
                if (CollectionUtils.isNotEmpty(poiStores)){
                    List<Long> storeIds = poiStores.stream().map(store -> store.getId()).collect(Collectors.toList());
                    //查询店铺拓客数量
                    List<OpCustomer> customerList = opCustomerDOMapper.selectCustomerList(storeIds, null, null, startDate, endDate);
                    //初始化返回数据
                    CompanyAvgAddDTO result = new CompanyAvgAddDTO();
                    result.setAddCustomerNum(customerList.size());
                    result.setStoreNum(storeIds.size());
                    result.setCompanyName(company.getName());
                    result.setAvgAddCustomerNum(new BigDecimal(customerList.size()).divide(new BigDecimal(storeIds.size()),0, BigDecimal.ROUND_HALF_UP));
                    results.add(result);
                }
            }
            //返回数据排序
            results.sort(new Comparator<CompanyAvgAddDTO>() {
                @Override
                public int compare(CompanyAvgAddDTO o1, CompanyAvgAddDTO o2) {
                    return o1.getAvgAddCustomerNum().compareTo(o2.getAvgAddCustomerNum());
                }
            });
        }
        return results;
    }


    /**
     * 查询门店均拓客TOP10
     * @param startDate 开始时间
     * @param endDate 结束时间
     * @return
     */
    public List<StoreAddDTO> listStoreAddTop(Long userId, String startDate, String endDate) {
        //查询店铺数
        List<Long> shopIds = customerViewService.getShopIds(userId);
        if(CollectionUtils.isEmpty(shopIds)){
            return null;
        }
        List<StoreAddDTO> results = opCustomerDOMapper.selectAddCustomerTopShop(shopIds,startDate,endDate);
        return results;
    }

    /**
     * 查询日拓客列表
     * @param startDate 开始时间
     * @param endDate 结束时间
     * @return
     */
    public List<DateAddDTO> listDateAdd(Long userId, String startDate, String endDate) {
        //查询店铺数
        List<Long> shopIds = customerViewService.getShopIds(userId);
        if(CollectionUtils.isEmpty(shopIds)){
            return null;
        }
        //查询拓客数量
        List<OpCustomer> customerList = opCustomerDOMapper.selectCustomerList(shopIds, null, null, startDate, endDate);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Map<String, Long> customerSizeMap = customerList.stream().filter(customer -> customer.getRegisterTime() != null).collect(Collectors.groupingBy(customer -> sdf.format(customer.getRegisterTime()), Collectors.counting()));
        List<DateAddDTO> results = new ArrayList<>();
        customerSizeMap.forEach((k,v) -> {
            DateAddDTO result = new DateAddDTO();
            result.setStatDate(k);
            result.setAddCustomerNum(v);
            results.add(result);
        });
        return results;
    }

    /**
     * 查询总拓客和新增拓客
     * @param startDate 开始时间
     * @param endDate 结束时间
     * @return
     */
    public LsInfoDTO listAddInfo(Long userId, String startDate, String endDate) {
        List<Long> shopIds = customerViewService.getShopIds(userId);
        //好友总数
        List<OpCustomer> customerList = opCustomerDOMapper.selectCustomerList(shopIds, null, null, null, null);
        Long newCustomerCount = customerList.stream().filter(customerDO -> customerViewService.filterCustomerByRegisterTime(customerDO, startDate, endDate)).count();
        LsInfoDTO result = new LsInfoDTO(newCustomerCount,Long.parseLong(customerList.size()+""));
        return result;
    }

    /**
     * 查询总拓客和新增拓客
     * @param startDate 开始时间
     * @param endDate 结束时间
     * @return
     */
    public List<ProvinceAddInfoDTO> listProvinceInfo(Long userId, String startDate, String endDate) {
        List<Long> shopIds = customerViewService.getShopIds(userId);
        List<ProvinceAddInfoDTO> provinceAddInfoDTOS = groupAndAddProvince(shopIds);
        for(ProvinceAddInfoDTO province:provinceAddInfoDTOS){
            List<OpCustomer> customerList = opCustomerDOMapper.selectCustomerList(province.getStoreIds(), null, null, startDate, endDate);
            province.setAddCustomerNum(customerList.size());
        }

        return provinceAddInfoDTOS;
    }

    /**
     * 店铺分组并填加省
     * @param shopIds
     * @return
     */
    private List<ProvinceAddInfoDTO> groupAndAddProvince(List<Long> shopIds){
        List<ProvinceAddInfoDTO> results = new ArrayList<>();
        QueryWrapper<PoiStore> storesQw = new QueryWrapper<>();
        storesQw.in("id",shopIds);
        List<PoiStore> poiStores = poiStoreDOMapper.selectList(storesQw);
        Map<Long,List<PoiStore>> cityMap = new HashMap<>();
        //分组
        for (PoiStore poiStore : poiStores) {
            if (cityMap.get(poiStore.getCity()) !=null){
                List<PoiStore> cityStores = cityMap.get(poiStore.getCity());
                cityStores.add(poiStore);
            }else{
                List<PoiStore> cityStores = new ArrayList<>();
                cityStores.add(poiStore);
                cityMap.put(poiStore.getCity(),cityStores);
            }
        }
        Set<Long> cities = cityMap.keySet();
        for (Long provinceId : cities) {
            String provinceName = poiStoreDOMapper.selectProvinceName(provinceId);
            List<PoiStore> provinceStores = cityMap.get(provinceId);
            List<Long> provinceStoreIds = provinceStores.stream().map(provinceStore -> provinceStore.getId()).collect(Collectors.toList());
            ProvinceAddInfoDTO result = new ProvinceAddInfoDTO();
            result.setProvinceName(provinceName);
            result.setStoreIds(provinceStoreIds);
            results.add(result);
        }
        return results;
    }
}
