package com.kiisoo.ic.generalize.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.kiisoo.ic.customer.entity.OpSellerCustomerRelation;
import com.kiisoo.ic.customer.mapper.OpSellerCustomerRelationDOMapper;
import com.kiisoo.ic.generalize.bean.*;
import com.kiisoo.ic.generalize.entity.CompanyStoreDO;
import com.kiisoo.ic.generalize.entity.PoiCustomerContactDataStat;
import com.kiisoo.ic.generalize.entity.PrivilageOrganizational;
import com.kiisoo.ic.generalize.entity.PrivilageOrganizationalMember;
import com.kiisoo.ic.generalize.mapper.OrganizationalMemberMapper;
import com.kiisoo.ic.generalize.mapper.PoiCustomerContactDataStatMapper;
import com.kiisoo.ic.generalize.mapper.RetailCompanyMapper;
import com.kiisoo.ic.store.entity.PoiStore;
import com.kiisoo.ic.store.entity.PoiStoreStaff;
import com.kiisoo.ic.store.mapper.PoiStoreDOMapper;
import com.kiisoo.ic.store.mapper.PoiStoreStaffDOMapper;
import com.kiisoo.ic.system.entity.PrivilageUserDO;
import com.kiisoo.ic.system.mapper.PrivilageUserDOMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName: RetailCompanyService
 * @Description:
 * @Auther: Caps
 * @Date: 2020/4/15 0015 11:08
 * @Version:
 */
@Service
public class RetailCompanyService {

    private RetailCompanyMapper retailCompanyMapper;

    private OrganizationalMemberMapper organizationalMemberMapper;

    private OpSellerCustomerRelationDOMapper opSellerCustomerRelationDOMapper;

    private PoiCustomerContactDataStatMapper poiCustomerContactDataStatMapper;

    private PoiStoreDOMapper poiStoreDOMapper;

    private PrivilageUserDOMapper privilageUserDOMapper;

    private PoiStoreStaffDOMapper poiStoreStaffDOMapper;

    @Autowired
    public RetailCompanyService(RetailCompanyMapper retailCompanyMapper,OrganizationalMemberMapper organizationalMemberMapper,OpSellerCustomerRelationDOMapper opSellerCustomerRelationDOMapper,PoiCustomerContactDataStatMapper poiCustomerContactDataStatMapper,PoiStoreDOMapper poiStoreDOMapper,PrivilageUserDOMapper privilageUserDOMapper,PoiStoreStaffDOMapper poiStoreStaffDOMapper){
        this.retailCompanyMapper = retailCompanyMapper;
        this.organizationalMemberMapper = organizationalMemberMapper;
        this.opSellerCustomerRelationDOMapper = opSellerCustomerRelationDOMapper;
        this.poiCustomerContactDataStatMapper = poiCustomerContactDataStatMapper;
        this.poiStoreDOMapper = poiStoreDOMapper;
        this.privilageUserDOMapper = privilageUserDOMapper;
        this.poiStoreStaffDOMapper = poiStoreStaffDOMapper;
    }


    /**
     * 找到用户公司
     * @param parentId 父区域id
     * @param userId 用户id
     * @param level 等级
     * @return
     */
    public List<PrivilageOrganizational> getUserOrg(Long parentId, long userId, int level){

        QueryWrapper<PrivilageOrganizationalMember> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("user_id",userId);
        PrivilageOrganizational p = new PrivilageOrganizational();
        List<PrivilageOrganizationalMember> pm = organizationalMemberMapper.selectList(wrapper1);
        QueryWrapper<PrivilageOrganizational> wrapper = new QueryWrapper<>();
        if(pm.isEmpty()) {
            return null;
        }else {
            wrapper.eq("type", 1).eq("status", 1).eq("level",level).
                    in("id", pm.stream().map(PrivilageOrganizationalMember::getOrgId).
                            collect(Collectors.toList()));
            if(null != parentId){
                wrapper.eq("parent_id",parentId);
            }
            return retailCompanyMapper.selectList(wrapper);
        }
    }

    /**
     * 查询所有的零售公司信息
     */
    public List<PrivilageOrganizational> listOfRetailCompany(long userId){
        QueryWrapper<PrivilageOrganizationalMember> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("user_id",userId);
        List<PrivilageOrganizationalMember> pm = organizationalMemberMapper.selectList(wrapper1);
        QueryWrapper<PrivilageOrganizational> wrapper = new QueryWrapper<>();
        if(pm.isEmpty()) {
            return null;
        }else {
            wrapper.eq("type", 1).eq("status", 1).eq("level",2).in("id", pm.stream().map(PrivilageOrganizationalMember::getOrgId).collect(Collectors.toList()));
            return retailCompanyMapper.selectList(wrapper);
        }
    }

    /**
     * 查询零售公司下的店铺
     * @param orgId 零售公司id
     * @return 门店信息
     */
    public List<PoiStore> selectShopByCompany(Long orgId){
        return poiStoreDOMapper.selectShopByCompany(orgId);
    }

    /**
     * 查询零售公司下的店铺
     * @param shopId 零售公司id
     * @return 门店信息
     */
    public List<PrivilageUserDO> selectSellerByShop(Long shopId){
        return poiStoreDOMapper.selectSellerByShop(shopId);
    }

    /**
     * 查询所有零售公司的推广数据
     * @param startTime 日期
     * @param endTime 日期
     * @param orgId 零售公司
     * @return 零售公司的推广数据
     */
    public OrganizationVO generalizeOfRetail(String startTime,String endTime,Long orgId,int pageNum,int pageSize){
        //零售公司信息
        QueryWrapper<PrivilageOrganizational> wrapper = new QueryWrapper<>();
        wrapper.eq("type",1).eq("status",1);
        if(orgId != null){
            wrapper.eq("id",orgId);
        }
        PageHelper.startPage(pageNum, pageSize);
        List<PrivilageOrganizational> listOfOrg = retailCompanyMapper.selectList(wrapper);

        List<RetailOrganizationalVO> list = new ArrayList<>();
        listOfOrg.forEach(org -> {
            RetailOrganizationalVO organizationalVO = new RetailOrganizationalVO();
            organizationalVO.setRetailCompany(org.getName());

            //查询零售公司的门店
            List<PoiStore> list1 = selectShopByCompany(org.getId());
            List<Long> stores = list1.stream().map(PoiStore::getId).collect(Collectors.toList());

            //组织成员
            QueryWrapper<PrivilageOrganizationalMember> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("org_id",org.getId());
            List<PrivilageOrganizationalMember> memberList = organizationalMemberMapper.selectList(wrapper1);
            //组织成员的客户个数
            QueryWrapper<OpSellerCustomerRelation> wrapper2 = new QueryWrapper<>();
            wrapper2.in("user_id",memberList.stream().map(PrivilageOrganizationalMember::getUserId).collect(Collectors.toList()));
            List<OpSellerCustomerRelation> opRelations = opSellerCustomerRelationDOMapper.selectList(wrapper2);
            long count = opRelations.stream().map(OpSellerCustomerRelation::getCustomerId).distinct().count();
            organizationalVO.setAllCustomer((int) count);
            //组织成员的客户有效个数
            QueryWrapper<OpSellerCustomerRelation> wrapper4 = new QueryWrapper<>();
            wrapper4.in("user_id",memberList.stream().map(PrivilageOrganizationalMember::getUserId).collect(Collectors.toList()));
            wrapper4.eq("type",1);
            List<OpSellerCustomerRelation> opRelations1 = opSellerCustomerRelationDOMapper.selectList(wrapper4);
            long countAble = opRelations1.stream().map(OpSellerCustomerRelation::getCustomerId).distinct().count();
            organizationalVO.setEffectiveCustomer((int) countAble);

            //计算新增客户数据
            newCustomerUser(startTime,endTime,organizationalVO,memberList.stream().map(PrivilageOrganizationalMember::getUserId).collect(Collectors.toList()));

            //被拉黑的客户数
            QueryWrapper<PoiCustomerContactDataStat> wrapper3 = new QueryWrapper<>();
            if(stores.isEmpty()){
                stores.add(-1L);
            }
            wrapper3.in("store_id",stores);
            List<PoiCustomerContactDataStat> dataStats = poiCustomerContactDataStatMapper.selectList(wrapper3);
            long allAge = dataStats.stream().mapToLong(PoiCustomerContactDataStat::getNegativeFeedbackCnt).sum();

            organizationalVO.setDelCustomer((int) allAge);
            organizationalVO.setDelRate(check(allAge,count));
            list.add(organizationalVO);
        });
        OrganizationVO vo = new OrganizationVO();
        //总条数
        if (listOfOrg.size() > 0) {
            vo.setDataVOS(list);
            Page<PrivilageOrganizational> pageList = (Page<PrivilageOrganizational>) listOfOrg;
            long totalSize = pageList.getTotal();
            vo.setSizeNum(totalSize);
        } else {
            return new OrganizationVO();
        }
        return vo;
    }

    /**
     * 计算新增客户数和新增有效客户数
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param organizationalVO 封装实体
     */
    private void newCustomerUser(String startTime, String endTime, DataVO organizationalVO, List<Long> userIds){
        //最初时间的总客户人数
        QueryWrapper<OpSellerCustomerRelation> wrapper2 = new QueryWrapper<>();
        wrapper2.in("user_id",userIds);
        wrapper2.lt("create_time",startTime);
        List<OpSellerCustomerRelation> opRelations = opSellerCustomerRelationDOMapper.selectList(wrapper2);
        long count = opRelations.stream().map(OpSellerCustomerRelation::getCustomerId).distinct().count();
        //最初时间的有效总客户人数
        wrapper2.in("user_id",userIds);
        wrapper2.eq("type",1);
        wrapper2.lt("create_time",startTime);
        List<OpSellerCustomerRelation> opRelations2 = opSellerCustomerRelationDOMapper.selectList(wrapper2);
        long count2 = opRelations2.stream().map(OpSellerCustomerRelation::getCustomerId).distinct().count();
        //最后时间的总客户人数
        QueryWrapper<OpSellerCustomerRelation> wrapper3 = new QueryWrapper<>();
        wrapper3.in("user_id",userIds);
        wrapper3.lt("create_time",endTime);
        List<OpSellerCustomerRelation> opRelationsEnd = opSellerCustomerRelationDOMapper.selectList(wrapper3);
        long countEnd = opRelationsEnd.stream().map(OpSellerCustomerRelation::getCustomerId).distinct().count();
        //最后时间的有效总客户人数
        wrapper3.in("user_id",userIds);
        wrapper3.eq("type",1);
        wrapper3.lt("create_time",endTime);
        List<OpSellerCustomerRelation> opRelationsEnd2 = opSellerCustomerRelationDOMapper.selectList(wrapper3);
        long countEnd2 = opRelationsEnd2.stream().map(OpSellerCustomerRelation::getCustomerId).distinct().count();

        //计算两个时间间隔用于计算平均值
        LocalDate start = LocalDate.parse(startTime);
        LocalDate end = LocalDate.parse(endTime);
        long days = end.until(start, ChronoUnit.DAYS);

        organizationalVO.setNewCustomer((int) (countEnd - count));
        organizationalVO.setNewEffectiveCustomer((int) (countEnd2 - count2));
        organizationalVO.setAvgNewCustomer(check(countEnd - count,days));
        organizationalVO.setAvgNewEffectiveCustomer(check(countEnd2 - count2,days));
    }
    private void newCustomerStore(String startTime, String endTime, DataVO organizationalVO, List<Long> storeIds){
        //最初时间的总客户人数
        QueryWrapper<OpSellerCustomerRelation> wrapper2 = new QueryWrapper<>();
        wrapper2.in("store_id",storeIds);
        wrapper2.lt("create_time",startTime);
        List<OpSellerCustomerRelation> opRelations = opSellerCustomerRelationDOMapper.selectList(wrapper2);
        long count = opRelations.stream().map(OpSellerCustomerRelation::getCustomerId).distinct().count();
        //最初时间的有效总客户人数
        wrapper2.in("store_id",storeIds);
        wrapper2.eq("type",1);
        wrapper2.lt("create_time",startTime);
        List<OpSellerCustomerRelation> opRelations2 = opSellerCustomerRelationDOMapper.selectList(wrapper2);
        long count2 = opRelations2.stream().map(OpSellerCustomerRelation::getCustomerId).distinct().count();
        //最后时间的总客户人数
        QueryWrapper<OpSellerCustomerRelation> wrapper3 = new QueryWrapper<>();
        wrapper3.in("store_id",storeIds);
        wrapper3.lt("create_time",endTime);
        List<OpSellerCustomerRelation> opRelationsEnd = opSellerCustomerRelationDOMapper.selectList(wrapper3);
        long countEnd = opRelationsEnd.stream().map(OpSellerCustomerRelation::getCustomerId).distinct().count();
        //最后时间的有效总客户人数
        wrapper3.in("store_id",storeIds);
        wrapper3.eq("type",1);
        wrapper3.lt("create_time",endTime);
        List<OpSellerCustomerRelation> opRelationsEnd2 = opSellerCustomerRelationDOMapper.selectList(wrapper3);
        long countEnd2 = opRelationsEnd2.stream().map(OpSellerCustomerRelation::getCustomerId).distinct().count();

        //计算两个时间间隔用于计算平均值
        LocalDate start = LocalDate.parse(startTime);
        LocalDate end = LocalDate.parse(endTime);
        long days = end.until(start, ChronoUnit.DAYS);

        organizationalVO.setNewCustomer((int) (countEnd - count));
        organizationalVO.setNewEffectiveCustomer((int) (countEnd2 - count2));
        organizationalVO.setAvgNewCustomer(check(countEnd - count,days));
        organizationalVO.setAvgNewEffectiveCustomer(check(countEnd2 - count2,days));
    }

    /**
     * 除法计算
     * @param l1 被除数
     * @param l2 除数
     * @return 值
     */
    public Integer check(Long l1,Long l2){
        if(l2 == null || l1 == null || l2 == 0){
            return 0;
        }else {
            return Math.round((l1 / l2) * 100);
        }
    }

    /**
     * 查询门店推广数据
     * @param startTime 日期
     * @param endTime 日期
     * @param orgId 零售公司id
     * @param shopId 门店id
     * @param pageNum 页码
     * @param pageSize 页面显示个数
     * @return 门店推广数据
     */
    public OrganizationVO generalizeOfStore(String startTime, String endTime, Long orgId, Long shopId, int pageNum, int pageSize){
        //根据零售公司查询门店
        PageHelper.startPage(pageNum, pageSize);
        List<CompanyStoreDO> list = retailCompanyMapper.selectShopIdByRetail(orgId,shopId);

        List<StoreOrganizationalVO> list1 = new ArrayList<>();
        list.forEach(li -> {
            StoreOrganizationalVO storeOrganizationalVO = new StoreOrganizationalVO();

            //查询所有的客户
            QueryWrapper<OpSellerCustomerRelation> wrapper = new QueryWrapper<>();
            wrapper.eq("store_id",li.getShopId());
            long count = opSellerCustomerRelationDOMapper.selectCount(wrapper);
            //查询所有的有效客户
            QueryWrapper<OpSellerCustomerRelation> wrapper2 = new QueryWrapper<>();
            wrapper2.eq("store_id",li.getShopId());
            wrapper2.eq("type",1);
            long countAble = opSellerCustomerRelationDOMapper.selectCount(wrapper2);
            //计算新客户数据
            newCustomerStore(startTime,endTime,storeOrganizationalVO, Collections.singletonList(li.getShopId()));
            //查询店铺的名称
            PoiStore poiStore = poiStoreDOMapper.selectById(li.getShopId());

            //被拉黑的客户数
            QueryWrapper<PoiCustomerContactDataStat> wrapper3 = new QueryWrapper<>();
            wrapper3.eq("store_id",li.getShopId());
            List<PoiCustomerContactDataStat> dataStats = poiCustomerContactDataStatMapper.selectList(wrapper3);
            long allAge = dataStats.stream().mapToLong(PoiCustomerContactDataStat::getNegativeFeedbackCnt).sum();

            storeOrganizationalVO.setShopName(poiStore == null ? null : poiStore.getName());
            storeOrganizationalVO.setShopCode(poiStore == null ? null : poiStore.getCode());
            storeOrganizationalVO.setAllCustomer((int) count);
            storeOrganizationalVO.setEffectiveCustomer((int) countAble);
            storeOrganizationalVO.setDelCustomer((int) allAge);
            storeOrganizationalVO.setCompanyName(li.getCompanyName());
            storeOrganizationalVO.setDelRate(check(allAge,count));
            list1.add(storeOrganizationalVO);
        });
        OrganizationVO vo = new OrganizationVO();
        //总条数
        if (list.size() > 0) {
            vo.setDataVOS(list1);
            Page<CompanyStoreDO> pageList = (Page<CompanyStoreDO>) list;
            long totalSize = pageList.getTotal();
            vo.setSizeNum(totalSize);
        } else {
            return new OrganizationVO();
        }
        return vo;
    }

    /**
     * 查询导购的推广数据
     * @param startTime 日期
     * @param endTime 日期
     * @param orgId 零售哦给弄死id
     * @param shopId 门店id
     * @param sellerId 导购id
     * @param pageNum 页码
     * @param pageSize 页面个数
     * @return 导购的推广数据
     */
    public OrganizationVO generalizeOfSeller(String startTime, String endTime, Long orgId, Long shopId,Long sellerId, int pageNum, int pageSize){
        //根据零售公司查询门店
        PageHelper.startPage(pageNum, pageSize);
        List<Long> sellerIds = retailCompanyMapper.selectSellerIdsByShop(orgId,shopId,sellerId);
        List<SellerOrganizationalVO> list = new ArrayList<>();
        sellerIds.forEach(seller -> {
            SellerOrganizationalVO sellerOrganizationalVO = new SellerOrganizationalVO();

            //查询所有的客户
            QueryWrapper<OpSellerCustomerRelation> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id",seller);
            long count = opSellerCustomerRelationDOMapper.selectCount(wrapper);

            //查询导购信息
            PrivilageUserDO privilageUserDO = privilageUserDOMapper.selectById(seller);
            QueryWrapper<PoiStoreStaff> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("user_id",seller).last("limit 1");
            PoiStoreStaff poiStoreStaff = poiStoreStaffDOMapper.selectOne(wrapper1);
            //计算新客户数据
            newCustomerUser(startTime,endTime,sellerOrganizationalVO, Collections.singletonList(seller));
            //查询导购所属公司门店
            CompanyStoreDO companyStoreDO = poiStoreDOMapper.selectCompanyStore(seller);
            sellerOrganizationalVO.setShopName(companyStoreDO == null ? null : companyStoreDO.getShopName());
            sellerOrganizationalVO.setShopCode(companyStoreDO == null ? null : companyStoreDO.getShopCode());
            sellerOrganizationalVO.setSellerCode(poiStoreStaff == null ? null : poiStoreStaff.getStaffCode());
            sellerOrganizationalVO.setCompanyName(companyStoreDO == null ? null : companyStoreDO.getCompanyName());
            sellerOrganizationalVO.setSellerName(privilageUserDO == null ? null :privilageUserDO.getName());
            sellerOrganizationalVO.setAllCustomer((int) count);
            list.add(sellerOrganizationalVO);
        });

        OrganizationVO vo = new OrganizationVO();
        //总条数
        if (sellerIds.size() > 0) {
            vo.setDataVOS(list);
            Page<Long> pageList = (Page<Long>) sellerIds;
            long totalSize = pageList.getTotal();
            vo.setSizeNum(totalSize);
        } else {
            return new OrganizationVO();
        }
        return vo;
    }

    /**
     * 找到最小公司集合
     */
    public void getMinCompany(Set<Long> companys,Set<Long> needs){
        companys.forEach(item -> {
            getMinCompany(item, needs);
        });
    }

    /**
     * 找到最小公司集合
     */
    public void getMinCompany(Long company,Set<Long> needs){
        QueryWrapper<PrivilageOrganizational> q = new QueryWrapper();
        q.eq("parent_id", company);
        List<PrivilageOrganizational> listOfOrg = retailCompanyMapper.selectList(q);
        Set<Long> companys = listOfOrg.stream().map(item -> item.getId()).collect(Collectors.toSet());
        if(companys.size() > 0) {
            getMinCompany(companys, needs);
        }else{
            needs.add(company);
        }
    }

}
