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

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Pair;
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.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.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;

    /**
     * 分页查询转化记录
     * @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.isBlank(storeId)) {
            storeIds = clerkStoreAdaptor.queryClerkStoreIds(storeId, contactOrderPageQO.getEnterpriseId(),
                    StoreStatusFilterUtils.getStoreStatusList(contactOrderPageQO.getStoreStatusFilter()));
        } else {
            storeIds.add(storeId);
        }
        ContactOrderSearchQDTO searchQDTO = new ContactOrderSearchQDTO();
        if (CollectionUtils.isNotEmpty(storeIds)) {
            searchQDTO.setStoreIdList(storeIds);
        }
        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();
        List<String> storeIds = getStoreIds(potentialOverviewQO);

        // 建联数据
        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);
        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) {
        List<String> storeIds = getStoreIds(potentialOverviewQO);
        Page<PotentialContactOverviewVO> page = potentialDataAdaptor.pagePotentialContactOverview(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.getOrDefault(x.getClerkId(), new ClerkDTO());
                StoreDTO storeDTO = storeMap.getOrDefault(x.getStoreId(), new StoreDTO());
                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);
    }

    /**
     * 转化明细概览 周/月报
     *
     * @return
     */
    @RequestMapping(path = "/potential/conv-detail")
    public RestResponse<Page<PotentialConvDetailOverviewVO>> queryPotentialConvReport(@RequestBody PotentialConvOverviewQO potentialOverviewQO) {
        List<String> storeIds = getStoreIds(potentialOverviewQO);
        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);
        // 使用数据
        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);
        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);
        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);
        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);
        Page<RecommendConvTrendVO> page = potentialDataAdaptor.pageRecommendConvTrend(potentialOverviewQO, storeIds);
        return RestResponse.successResult(page);
    }

    private List<String> getStoreIds(PotentialStatisticsBaseQO potentialStatisticsBaseQO) {
        String wxEnterpriseId = potentialStatisticsBaseQO.getWxEnterpriseId();
        String storeId = potentialStatisticsBaseQO.getStoreId();
        Integer storeStatusFilter = potentialStatisticsBaseQO.getStoreStatusFilter();
        List<String> storeIds = new ArrayList<>();
        if (StringUtils.isBlank(storeId)) {
            storeIds = clerkStoreAdaptor.queryClerkStoreIds(storeId, wxEnterpriseId,
                    StoreStatusFilterUtils.getStoreStatusList(storeStatusFilter));
        } else {
            storeIds.add(storeId);
        }
        return storeIds;
    }
}
