package com.gic.haoban.manage.web.controller.potential;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Pair;
import com.alibaba.fastjson.JSON;
import com.gic.api.base.commons.BasePageInfo;
import com.gic.api.base.commons.Page;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.clerk.api.dto.ClerkDTO;
import com.gic.clerk.api.service.ClerkService;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.enterprise.api.dto.StoreDTO;
import com.gic.haoban.app.customer.dto.ChildDTO;
import com.gic.haoban.app.customer.dto.CustomerDTO;
import com.gic.haoban.app.customer.dto.FilterListDTO;
import com.gic.haoban.app.customer.dto.MemberInfoListParamsDTO;
import com.gic.haoban.app.customer.dto.contact.ContactParamDTO;
import com.gic.haoban.app.customer.dto.contact.ContactSumDTO;
import com.gic.haoban.app.customer.service.api.service.CustomerApiService;
import com.gic.haoban.manage.api.dto.contact.ContactOrderDetailDTO;
import com.gic.haoban.manage.api.qdto.contact.ContactOrderSearchQDTO;
import com.gic.haoban.manage.api.service.contact.ContactOrderApiService;
import com.gic.haoban.manage.web.controller.content.adaptor.ClerkStoreAdaptor;
import com.gic.haoban.manage.web.controller.potential.adaptor.PotentialDataAdaptor;
import com.gic.haoban.manage.web.qo.contact.ContactOrderPageQO;
import com.gic.haoban.manage.web.qo.potential.*;
import com.gic.haoban.manage.web.utils.EsMemberInfoUtils;
import com.gic.haoban.manage.web.utils.storestatusfilter.StoreStatusFilterUtils;
import com.gic.haoban.manage.web.vo.potential.*;
import com.gic.store.goods.dto.potential.PlatformPotentialCustomerOutDTO;
import com.gic.store.goods.service.potential.PlatformPotentialCustomerApiService;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * 潜客雷达-数据
 */
@RestController
@RequestMapping()
public class PotentialDataController {

    @Autowired
    private ContactOrderApiService contactOrderApiService;
    @Autowired
    private ClerkService clerkService;
    @Autowired
    private ClerkStoreAdaptor clerkStoreAdaptor;
    @Autowired
    private PotentialDataAdaptor potentialDataAdaptor;
    @Autowired
    private EsMemberInfoUtils esMemberInfoUtils;
    @Autowired
    private PlatformPotentialCustomerApiService platformPotentialCustomerApiService;
    @Autowired
    private CustomerApiService customerService;

    /**
     * 分页查询转化记录
     * @param contactOrderPageQO
     * @return
     */
    @RequestMapping(path = "/contact/page-order")
    public RestResponse<Page<ContactOrderDetailDTO>> pageOrder(@RequestBody ContactOrderPageQO contactOrderPageQO) {
        String enterpriseId = contactOrderPageQO.getEnterpriseId();
        String clerkId = contactOrderPageQO.getClerkId();
        String storeId = contactOrderPageQO.getStoreId();
        List<String> storeIds = new ArrayList<>();
        if (StringUtils.isNotBlank(clerkId)) {
            ClerkDTO clerkDTO = clerkService.getclerkById(clerkId);
            if (clerkDTO == null) {
                return RestResponse.failure("-1", "导购不存在");
            }
            Integer clerkType = clerkDTO.getClerkType();
            if (clerkType >= 2) {
                storeIds = clerkStoreAdaptor.queryClerkStoreIds(clerkId, contactOrderPageQO.getEnterpriseId(),
                        StoreStatusFilterUtils.getStoreStatusList(contactOrderPageQO.getStoreStatusFilter()));
                clerkId = "";
            }
        }
        if (StringUtils.isNotBlank(storeId)) {
            storeIds.add(storeId);
        }
        ContactOrderSearchQDTO searchQDTO = new ContactOrderSearchQDTO();
        if (CollectionUtils.isNotEmpty(storeIds)) {
            searchQDTO.setStoreIdList(storeIds);
        }
        if (StringUtils.isNotBlank(clerkId)) {
            searchQDTO.setClerkId(clerkId);
        }
        searchQDTO.setBeginTime(contactOrderPageQO.getBeginTime());
        searchQDTO.setEndTime(contactOrderPageQO.getEndTime());
        searchQDTO.setChannelType(contactOrderPageQO.getChannelType());
        BasePageInfo basePageInfo = contactOrderPageQO.getBasePageInfo();
        ServiceResponse<Page<ContactOrderDetailDTO>> serviceResponse = contactOrderApiService.pageContactOrder(enterpriseId,searchQDTO,basePageInfo);
        if (!serviceResponse.isSuccess()) {
            return RestResponse.failure(serviceResponse.getCode(), serviceResponse.getMessage());
        }
        return RestResponse.successResult(serviceResponse.getResult());
    }

    /**
     * 建联/转化概览 周/月报
     *
     * @return
     */
    @RequestMapping(path = "/potential/overview")
    public RestResponse<PotentialOverviewVO> queryPotentialOverviewReport(@RequestBody PotentialBusiOverviewQO potentialOverviewQO) {
        String clerkId = potentialOverviewQO.getClerkId();
        Pair<Integer, List<String>> pair = getStoreIds(potentialOverviewQO);
        Integer clerkType = pair.getKey();
        List<String> storeIds = pair.getValue();
        if (StringUtils.isBlank(clerkId)) {
            potentialOverviewQO.setPotGroup(1);
        } else if (clerkType != null && clerkType >= 2) {
            potentialOverviewQO.setPotGroup(3);
        } else {
            potentialOverviewQO.setPotGroup(2);
        }
        // 建联数据
        PotentialContactOverviewVO contactOverviewVO = null;
        // 转化数据
        PotentialConvOverviewVO convOverviewVO = null;
        PotentialOverviewVO overviewVO = new PotentialOverviewVO();
        // 查询的业务列表 默认所有 1建联数据 2转化数据
        List<Integer> queryBiz = potentialOverviewQO.getQueryBiz();
        if (CollectionUtils.isEmpty(queryBiz)) {
            contactOverviewVO = potentialDataAdaptor.potentialContactOverview(potentialOverviewQO,storeIds);
            convOverviewVO = potentialDataAdaptor.potentialConvOverview(potentialOverviewQO,storeIds);
        } else if (queryBiz.contains(1)) {
            contactOverviewVO = potentialDataAdaptor.potentialContactOverview(potentialOverviewQO,storeIds);
        } else if (queryBiz.contains(2)) {
            convOverviewVO = potentialDataAdaptor.potentialConvOverview(potentialOverviewQO,storeIds);
        }
        overviewVO.setConv(convOverviewVO);
        overviewVO.setContact(contactOverviewVO);
        Pair<String, String> datePair = potentialDataAdaptor.getDateParam(potentialOverviewQO.getReportType(), potentialOverviewQO.getBizDate());
        if (StringUtils.isNotBlank(datePair.getKey())) {
            overviewVO.setStartTime(DateUtil.parseDate(datePair.getKey()));
        }
        if (StringUtils.isNotBlank(datePair.getValue())) {
            overviewVO.setEndTime(DateUtil.parseDate(datePair.getValue()));
        }
        if (StringUtils.isNotBlank(clerkId)) {
            ClerkDTO clerkInfo = clerkService.getClerkByClerkId(clerkId);
            overviewVO.setClerk(clerkInfo);
        }
        return RestResponse.successResult(overviewVO);
    }

    /**
     * 潜客转化会员明细
     *
     * @return
     */
    @RequestMapping(path = "/potential/conv-member")
    public RestResponse<Page<PotentialMemberConvVO>> queryPotentialConvMember(@RequestBody PotentialConvMemberQO potentialOverviewQO) {
        List<String> storeIds = getStoreIds(potentialOverviewQO).getValue();
        Page<PotentialMemberConvVO> page = potentialDataAdaptor.pagePotentialConvMember(potentialOverviewQO, storeIds);
        List<PotentialMemberConvVO> result = page.getResult();
        if (CollectionUtils.isNotEmpty(result)) {
            esMemberInfoUtils.setMemberInfo(potentialOverviewQO.getEnterpriseId(), result, Sets.newHashSet("memberName", "memberNick", "memberImage", "memberCard"));
        }
        return RestResponse.successResult(page);
    }

    /**
     * 建联明细概览 周/月报
     *
     * @return
     */
    @RequestMapping(path = "/potential/contact-detail")
    public RestResponse<Page<PotentialContactDetailOverviewVO>> queryPotentialContactReport(@RequestBody PotentialContactOverviewQO potentialOverviewQO) {
        String enterpriseId = potentialOverviewQO.getEnterpriseId();
        String wxEnterpriseId = potentialOverviewQO.getWxEnterpriseId();
        ServiceResponse<PlatformPotentialCustomerOutDTO> potentialResponse = platformPotentialCustomerApiService.getPotentialCustomerOutRule(enterpriseId);
        if (!potentialResponse.isSuccess() || potentialResponse.getResult() == null) {
            return RestResponse.successResult(new Page<>());
        }
        List<String> storeIds = getStoreIds(potentialOverviewQO).getValue();
        Page<PotentialContactOverviewVO> page = null;
        // 是否周月报 周月报不用实时查当前未建联数
        boolean weekMonth = StringUtils.isNotBlank(potentialOverviewQO.getBizDate());
        if (weekMonth) {
            page = potentialDataAdaptor.pagePotentialContactOverview(potentialOverviewQO, storeIds);
        }else {
            page = potentialDataAdaptor.pagePotentialContactDetail(potentialOverviewQO, storeIds);
        }
        List<PotentialContactOverviewVO> result = page.getResult();
        List<PotentialContactDetailOverviewVO> list = null;
        if (CollectionUtils.isNotEmpty(result)) {
            Pair<Map<String, ClerkDTO>, Map<String, StoreDTO>> pair = clerkStoreAdaptor.getClerkStoreIdMap(result);
            Map<String, ClerkDTO> clerkMap = pair.getKey();
            Map<String, StoreDTO> storeMap = pair.getValue();
            list = result.stream().map(x -> {
                ClerkDTO clerkDTO = clerkMap.get(x.getClerkId());
                StoreDTO storeDTO = storeMap.get(x.getStoreId());
                if (!weekMonth) {
                    // 无归属导购
                    boolean unassigned = Objects.equals(x.getClerkId(), "-1") ? true : false;
                    // 实时获取当前未建联数 todo
                    Integer noConnPotCusNum = getNoConnPotCusNum(potentialResponse, enterpriseId, wxEnterpriseId, storeDTO, clerkDTO,unassigned);
                    x.setNoConnPotCusNum(noConnPotCusNum);
                }
                PotentialContactDetailOverviewVO overviewVO = new PotentialContactDetailOverviewVO();
                overviewVO.setContact(x);
                overviewVO.setStore(storeDTO);
                overviewVO.setClerk(clerkDTO);
                return overviewVO;
            }).collect(Collectors.toList());
        }
        Page<PotentialContactDetailOverviewVO> res = new Page<>();
        res.setCurrentPage(page.getCurrentPage());
        res.setPageSize(page.getPageSize());
        res.setTotalPage(page.getTotalPage());
        res.setTotalCount(page.getTotalCount());
        res.setResult(list);
        return RestResponse.successResult(res);
    }

    private Integer getNoConnPotCusNum(ServiceResponse<PlatformPotentialCustomerOutDTO> potentialResponse, String enterpriseId,String wxEnterpriseId,StoreDTO storeDTO,ClerkDTO clerkDTO,boolean unassigned) {
        if (storeDTO == null && clerkDTO == null) {
            return 0;
        }
        String storeId = "";
        if (storeDTO != null) {
            storeId = storeDTO.getStoreId();
        }
        String clerkTypeStr = "1";
        CustomerDTO params = new CustomerDTO();
        String clerkId = null;
        if (clerkDTO != null) {
            clerkTypeStr = "0";
            clerkId = clerkDTO.getClerkId();
            Integer clerkType = clerkDTO.getClerkType();
            if (clerkType == 0 || clerkType == 1) {
                storeId = clerkDTO.getStoreId();
            }
        }
        ContactParamDTO contact = new ContactParamDTO();
        contact.setRuleJSON(JSON.toJSONString(potentialResponse.getResult()));
        contact.setContactType(0);
        params.setStoreId(storeId);
        params.setClerkId(clerkId);
        params.setClerkType(clerkTypeStr);
        params.setEnterpriseId(enterpriseId);
        params.setWxEnterpriseId(wxEnterpriseId);
        params.setContactParamDTO(contact);
        MemberInfoListParamsDTO memberInfoListParamsDTO = new MemberInfoListParamsDTO();
        // 查询无归属数据
        if (unassigned) {
            FilterListDTO filterListDTO = new FilterListDTO();
            filterListDTO.setFilterType("1");
            ChildDTO child = new ChildDTO();
            child.setId("-1");
            filterListDTO.setChild(child);
            memberInfoListParamsDTO.setFilterList(Lists.newArrayList(filterListDTO));
        }
        ServiceResponse<ContactSumDTO> noContactResponse = customerService.contactMemberSum(new com.gic.haoban.base.api.common.BasePageInfo(), params, memberInfoListParamsDTO);
        return noContactResponse.getResult() != null ? noContactResponse.getResult().getTotalCount() : 0;
    }


    /**
     * 转化明细概览 周/月报
     *
     * @return
     */
    @RequestMapping(path = "/potential/conv-detail")
    public RestResponse<Page<PotentialConvDetailOverviewVO>> queryPotentialConvReport(@RequestBody PotentialConvOverviewQO potentialOverviewQO) {
        List<String> storeIds = getStoreIds(potentialOverviewQO).getValue();
        Page<PotentialConvOverviewVO> page = potentialDataAdaptor.pagePotentialConvOverview(potentialOverviewQO, storeIds);
        List<PotentialConvOverviewVO> result = page.getResult();
        List<PotentialConvDetailOverviewVO> list = null;
        if (CollectionUtils.isNotEmpty(result)) {
            Pair<Map<String, ClerkDTO>, Map<String, StoreDTO>> pair = clerkStoreAdaptor.getClerkStoreIdMap(result);
            Map<String, ClerkDTO> clerkMap = pair.getKey();
            Map<String, StoreDTO> storeMap = pair.getValue();
            list = result.stream().map(x -> {
                ClerkDTO clerkDTO = clerkMap.getOrDefault(x.getClerkId(), new ClerkDTO());
                StoreDTO storeDTO = storeMap.getOrDefault(x.getStoreId(), new StoreDTO());
                PotentialConvDetailOverviewVO overviewVO = new PotentialConvDetailOverviewVO();
                overviewVO.setConv(x);
                overviewVO.setStore(storeDTO);
                overviewVO.setClerk(clerkDTO);
                return overviewVO;
            }).collect(Collectors.toList());
        }
        Page<PotentialConvDetailOverviewVO> res = new Page<>();
        res.setCurrentPage(page.getCurrentPage());
        res.setPageSize(page.getPageSize());
        res.setTotalPage(page.getTotalPage());
        res.setTotalCount(page.getTotalCount());
        res.setResult(list);
        return RestResponse.successResult(res);
    }

    /**
     * 人货匹配推荐概览
     *
     * @return
     */
    @RequestMapping(path = "/recommend/overview")
    public RestResponse<RecommendOverviewVO> queryRecommendOverviewReport(@RequestBody RecommendBusiOverviewQO potentialOverviewQO) {
        List<String> storeIds = getStoreIds(potentialOverviewQO).getValue();
        // 使用数据
        RecommendUsedOverviewVO usedOverviewVO = null;
        // 转化数据
        RecommendConvOverviewVO convOverviewVO = null;
        RecommendOverviewVO overviewVO = new RecommendOverviewVO();
        // 查询的业务列表 默认所有 1使用数据 2转化数据
        List<Integer> queryBiz = potentialOverviewQO.getQueryBiz();
        if (CollectionUtils.isEmpty(queryBiz)) {
            usedOverviewVO = potentialDataAdaptor.recommendUsedOverview(potentialOverviewQO,storeIds);
            convOverviewVO = potentialDataAdaptor.recommendConvOverview(potentialOverviewQO,storeIds);
        } else if (queryBiz.contains(1)) {
            usedOverviewVO = potentialDataAdaptor.recommendUsedOverview(potentialOverviewQO,storeIds);
        } else if (queryBiz.contains(2)) {
            convOverviewVO = potentialDataAdaptor.recommendConvOverview(potentialOverviewQO,storeIds);
        }
        overviewVO.setUsed(usedOverviewVO);
        overviewVO.setConv(convOverviewVO);
        return RestResponse.successResult(overviewVO);
    }

    /**
     * 人货匹配使用概览明细
     *
     * @return
     */
    @RequestMapping(path = "/recommend/used-detail")
    public RestResponse<Page<RecommendUsedDetailOverviewVO>> queryRecommendUsedReport(@RequestBody RecommendUsedOverviewQO potentialOverviewQO) {
        List<String> storeIds = getStoreIds(potentialOverviewQO).getValue();
        Page<RecommendUsedOverviewVO> page = potentialDataAdaptor.pageRecommendUsedOverview(potentialOverviewQO, storeIds);
        List<RecommendUsedOverviewVO> result = page.getResult();
        List<RecommendUsedDetailOverviewVO> list = null;
        if (CollectionUtils.isNotEmpty(result)) {
            Pair<Map<String, ClerkDTO>, Map<String, StoreDTO>> pair = clerkStoreAdaptor.getClerkStoreIdMap(result);
            Map<String, ClerkDTO> clerkMap = pair.getKey();
            Map<String, StoreDTO> storeMap = pair.getValue();
            list = result.stream().map(x -> {
                ClerkDTO clerkDTO = clerkMap.getOrDefault(x.getClerkId(), new ClerkDTO());
                StoreDTO storeDTO = storeMap.getOrDefault(x.getStoreId(), new StoreDTO());
                RecommendUsedDetailOverviewVO overviewVO = new RecommendUsedDetailOverviewVO();
                overviewVO.setUsed(x);
                overviewVO.setStore(storeDTO);
                overviewVO.setClerk(clerkDTO);
                return overviewVO;
            }).collect(Collectors.toList());
        }
        Page<RecommendUsedDetailOverviewVO> res = new Page<>();
        res.setCurrentPage(page.getCurrentPage());
        res.setPageSize(page.getPageSize());
        res.setTotalPage(page.getTotalPage());
        res.setTotalCount(page.getTotalCount());
        res.setResult(list);
        return RestResponse.successResult(res);
    }

    /**
     * 人货匹配转化概览明细
     *
     * @return
     */
    @RequestMapping(path = "/recommend/conv-detail")
    public RestResponse<Page<RecommendConvDetailOverviewVO>> queryRecommendConvReport(@RequestBody RecommendConvOverviewQO potentialOverviewQO) {
        List<String> storeIds = getStoreIds(potentialOverviewQO).getValue();
        Page<RecommendConvOverviewVO> page = potentialDataAdaptor.pageRecommendConvOverview(potentialOverviewQO, storeIds);
        List<RecommendConvOverviewVO> result = page.getResult();
        List<RecommendConvDetailOverviewVO> list = null;
        if (CollectionUtils.isNotEmpty(result)) {
            Pair<Map<String, ClerkDTO>, Map<String, StoreDTO>> pair = clerkStoreAdaptor.getClerkStoreIdMap(result);
            Map<String, ClerkDTO> clerkMap = pair.getKey();
            Map<String, StoreDTO> storeMap = pair.getValue();
            list = result.stream().map(x -> {
                ClerkDTO clerkDTO = clerkMap.getOrDefault(x.getClerkId(), new ClerkDTO());
                StoreDTO storeDTO = storeMap.getOrDefault(x.getStoreId(), new StoreDTO());
                RecommendConvDetailOverviewVO overviewVO = new RecommendConvDetailOverviewVO();
                overviewVO.setConv(x);
                overviewVO.setStore(storeDTO);
                overviewVO.setClerk(clerkDTO);
                return overviewVO;
            }).collect(Collectors.toList());
        }
        Page<RecommendConvDetailOverviewVO> res = new Page<>();
        res.setCurrentPage(page.getCurrentPage());
        res.setPageSize(page.getPageSize());
        res.setTotalPage(page.getTotalPage());
        res.setTotalCount(page.getTotalCount());
        res.setResult(list);
        return RestResponse.successResult(res);
    }

    /**
     * 人货匹配使用趋势
     *
     * @return
     */
    @RequestMapping(path = "/recommend/used-trend")
    public RestResponse<Page<RecommendUsedTrendVO>> queryRecommendUsedTrend(@RequestBody RecommendUsedTrendQO potentialOverviewQO) {
        List<String> storeIds = getStoreIds(potentialOverviewQO).getValue();
        Page<RecommendUsedTrendVO> page = potentialDataAdaptor.pageRecommendUsedTrend(potentialOverviewQO, storeIds);
        return RestResponse.successResult(page);
    }

    /**
     * 人货匹配转化趋势
     *
     * @return
     */
    @RequestMapping(path = "/recommend/conv-trend")
    public RestResponse<Page<RecommendConvTrendVO>> queryRecommendConvTrend(@RequestBody RecommendConvTrendQO potentialOverviewQO) {
        List<String> storeIds = getStoreIds(potentialOverviewQO).getValue();
        Page<RecommendConvTrendVO> page = potentialDataAdaptor.pageRecommendConvTrend(potentialOverviewQO, storeIds);
        return RestResponse.successResult(page);
    }

    private Pair<Integer,List<String>> getStoreIds(PotentialStatisticsBaseQO potentialStatisticsBaseQO) {
        String clerkId = potentialStatisticsBaseQO.getClerkId();
        String wxEnterpriseId = potentialStatisticsBaseQO.getWxEnterpriseId();
        String storeId = potentialStatisticsBaseQO.getStoreId();
        Integer storeStatusFilter = potentialStatisticsBaseQO.getStoreStatusFilter();
        List<String> storeIds = new ArrayList<>();
        Integer clerkType = null;
        if (StringUtils.isNotBlank(clerkId)) {
            ClerkDTO clerkDTO = clerkService.getclerkById(clerkId);
            if (clerkDTO == null) {
                return new Pair<>(null, Lists.newArrayList("-1"));
            }
            clerkType = clerkDTO.getClerkType();
            if (clerkType >= 2) {
                potentialStatisticsBaseQO.setClerkId("");
                if (StringUtils.isBlank(storeId)) {
                    storeIds = clerkStoreAdaptor.queryClerkStoreIds(clerkId, wxEnterpriseId,
                            StoreStatusFilterUtils.getStoreStatusList(storeStatusFilter));
                }
            }
        }
        if (StringUtils.isNotBlank(storeId)) {
            storeIds.add(storeId);
        }
        return new Pair<>(clerkType, storeIds);
    }
}
