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

import cn.hutool.core.date.DateUtil;
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.content.api.dto.material.ContentMaterialFrontDTO;
import com.gic.content.api.qdto.material.ContentMaterialPageFrontQDTO;
import com.gic.content.api.service.ContentMaterialApiService;
import com.gic.enterprise.api.dto.StoreDTO;
import com.gic.enterprise.api.service.StoreService;
import com.gic.haoban.manage.web.controller.content.adaptor.ClerkStoreAdaptor;
import com.gic.haoban.manage.web.controller.content.adaptor.MaterialDataAdaptor;
import com.gic.haoban.manage.web.qo.content.ContentMaterialBaseQO;
import com.gic.haoban.manage.web.qo.content.statistics.MaterialAnalyzeDataQO;
import com.gic.haoban.manage.web.qo.content.statistics.MaterialReportQO;
import com.gic.haoban.manage.web.qo.content.statistics.MaterialStatisticsBaseQO;
import com.gic.haoban.manage.web.vo.content.statistics.MaterialAreaUsedDataVO;
import com.gic.haoban.manage.web.vo.content.statistics.MaterialClerkUsedDataVO;
import com.gic.haoban.manage.web.vo.content.statistics.MaterialDataOverviewVO;
import com.gic.haoban.manage.web.vo.content.statistics.MaterialIndexDataVO;
import com.gic.haoban.manage.web.vo.content.statistics.MaterialRealDataVO;
import com.gic.haoban.manage.web.vo.content.statistics.MaterialStoreUsedDataVO;
import com.gic.haoban.manage.web.vo.content.statistics.bo.MaterialTodayDataBO;
import com.gic.haoban.manage.web.vo.content.statistics.report.MaterialPersonalUsedDataVO;
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.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 素材-好办数据统计
 **/
@RequestMapping(path = "/material/data")
@RestController
public class MaterialDataStaticsController {

    @Autowired
    private ClerkStoreAdaptor clerkStoreAdaptor;
    @Autowired
    private MaterialDataAdaptor materialDataAdaptor;
    @Autowired
    private ContentMaterialApiService contentMaterialApiService;
    @Autowired
    private ClerkService clerkService;
    @Autowired
    private StoreService storeService;

    /**
     * 获取素材首页数据
     *
     * @param contentMaterialBaseQO
     * @return
     */
    @RequestMapping(path = "/content/material/index/data")
    public RestResponse<MaterialIndexDataVO> queryMaterialIndexData(@RequestBody ContentMaterialBaseQO contentMaterialBaseQO) {

        ContentMaterialPageFrontQDTO search = new ContentMaterialPageFrontQDTO();
        search.setEnterpriseId(contentMaterialBaseQO.getEnterpriseId());
        search.setPublishBeginStartTime(DateUtil.beginOfDay(new Date()));
        search.setPublishBeginEndTime(DateUtil.endOfDay(new Date()));
        List<String> storeIds = new ArrayList<>();
        if (StringUtils.isBlank(contentMaterialBaseQO.getStoreId())) {
            // 区经 获取管辖的权限
            storeIds = this.clerkStoreAdaptor.queryClerkStoreIds(contentMaterialBaseQO.getClerkId(), contentMaterialBaseQO.getWxEnterpriseId());
            search.setStoreIdList(storeIds);
        } else {
            storeIds.add(contentMaterialBaseQO.getStoreId());
            search.setStoreIdList(storeIds);
        }
        BasePageInfo pageInfo = new BasePageInfo();
        pageInfo.setPageNum(1);
        pageInfo.setPageSize(1);
        int totalMaterialNum = 0;
        ServiceResponse<Page<ContentMaterialFrontDTO>> serviceResponse = this.contentMaterialApiService.pageMaterialFront(search, pageInfo);
        if (serviceResponse.isSuccess() && serviceResponse.getResult() != null) {
            totalMaterialNum = serviceResponse.getResult().getTotalCount();
        }
        int totalManagerStoreNum = 0;
        MaterialTodayDataBO temp = materialDataAdaptor.queryMaterialTodayData(contentMaterialBaseQO.getEnterpriseId(), storeIds);
        if (CollectionUtils.isEmpty(storeIds)) {
            // 超管
            totalManagerStoreNum = clerkStoreAdaptor.countAdminManagerStore(contentMaterialBaseQO.getClerkId(), contentMaterialBaseQO.getWxEnterpriseId());
        }
        MaterialIndexDataVO indexDataVO = MaterialIndexDataVO.builder()
                .newMaterialNum(totalMaterialNum)
                .useMaterialClerkNum(temp.getUseMatlClerkNum())
                .unUseMaterialClerkNum(temp.getUnusedMatlClerkNum())
                .conversionAmount(Optional.ofNullable(temp.getConvSalesAmt()).orElse(BigDecimal.ZERO))
                .storeManagerNum(totalManagerStoreNum)
                .build();
        return RestResponse.successResult(indexDataVO);
    }


    /**
     * 素材使用分析页面-实时数据统计
     *
     * @return
     */
    @RequestMapping(path = "/content/material/real/use/data")
    public RestResponse<MaterialRealDataVO> queryMaterialUsedAnalyze(@RequestBody MaterialStatisticsBaseQO materialStatisticsBaseQO) {

        List<String> storeIds = new ArrayList<>();
        if (StringUtils.isBlank(materialStatisticsBaseQO.getStoreId())) {
            storeIds = clerkStoreAdaptor.queryClerkStoreIds(materialStatisticsBaseQO.getClerkId(), materialStatisticsBaseQO.getWxEnterpriseId());
        } else {
            storeIds.add(materialStatisticsBaseQO.getStoreId());
        }
        MaterialTodayDataBO materialTodayDataBO = materialDataAdaptor.queryMaterialTodayData(materialStatisticsBaseQO.getEnterpriseId(), storeIds);
        MaterialRealDataVO temp = new MaterialRealDataVO();
        temp.setUseMatlClerkNum(materialTodayDataBO.getUseMatlClerkNum());
        temp.setUnusedMatlClerkNum(materialTodayDataBO.getUnusedMatlClerkNum());
        temp.setClickUserNum(materialTodayDataBO.getClickUserNum());
        temp.setConvUserNum(materialTodayDataBO.getConvUserNum());
        temp.setConvSalesAmt(materialTodayDataBO.getConvSalesAmt());
        return RestResponse.successResult(temp);
    }

    /**
     * 素材使用分析页面-数据概览
     *
     * @param materialStatisticsBaseQO
     * @return
     */
    @RequestMapping(path = "/content/material/overview/data")
    public RestResponse<MaterialDataOverviewVO> queryMaterialOverviewData(@RequestBody MaterialAnalyzeDataQO materialStatisticsBaseQO) {

        List<String> storeIds = new ArrayList<>();
        if (StringUtils.isBlank(materialStatisticsBaseQO.getStoreId())) {
            storeIds = clerkStoreAdaptor.queryClerkStoreIds(materialStatisticsBaseQO.getClerkId(), materialStatisticsBaseQO.getWxEnterpriseId());
        } else {
            storeIds.add(materialStatisticsBaseQO.getStoreId());
        }
        MaterialDataOverviewVO materialDataOverviewVO =
                materialDataAdaptor.queryMaterialDataOverview(materialStatisticsBaseQO.getEnterpriseId(), storeIds, materialStatisticsBaseQO.getFixedDateDiff());
        return RestResponse.successResult(materialDataOverviewVO);
    }


    /**
     * 素材使用分析页面-导购纬度使用数据
     *
     * @return
     */
    @RequestMapping(path = "/content/material/clerk/data")
    public RestResponse<Page<MaterialClerkUsedDataVO>> queryMaterialClerkUsedData(@RequestBody MaterialAnalyzeDataQO materialStatisticsBaseQO) {
        //
        List<String> storeIds = new ArrayList<>();
        if (StringUtils.isBlank(materialStatisticsBaseQO.getStoreId())) {
            storeIds = clerkStoreAdaptor.queryClerkStoreIds(materialStatisticsBaseQO.getClerkId(), materialStatisticsBaseQO.getWxEnterpriseId());
        } else {
            storeIds.add(materialStatisticsBaseQO.getStoreId());
        }
        Page<MaterialClerkUsedDataVO> clerkUsedData = materialDataAdaptor.queryMaterialClerkUsedData(materialStatisticsBaseQO.getEnterpriseId(), storeIds,
                materialStatisticsBaseQO.getFixedDateDiff(), materialStatisticsBaseQO.getOrderByField(), materialStatisticsBaseQO.getOrder(), materialStatisticsBaseQO.getPageNum(), materialStatisticsBaseQO.getPageSize());
        return RestResponse.successResult(clerkUsedData);
    }

    /**
     * 素材使用分析页面-门店纬度使用数据
     *
     * @return
     */
    @RequestMapping(path = "/content/material/store/data")
    public RestResponse<Page<MaterialStoreUsedDataVO>> queryMaterialStoreUsedData(@RequestBody MaterialAnalyzeDataQO materialStatisticsBaseQO) {
        List<String> storeIds = new ArrayList<>();
        if (StringUtils.isBlank(materialStatisticsBaseQO.getStoreId())) {
            storeIds = clerkStoreAdaptor.queryClerkStoreIds(materialStatisticsBaseQO.getClerkId(), materialStatisticsBaseQO.getWxEnterpriseId());
        } else {
            storeIds.add(materialStatisticsBaseQO.getStoreId());
        }
        Page<MaterialStoreUsedDataVO> storeUsedData = materialDataAdaptor.queryMaterialStoreUsedData(materialStatisticsBaseQO.getEnterpriseId(), storeIds,
                materialStatisticsBaseQO.getFixedDateDiff(), materialStatisticsBaseQO.getOrderByField(), materialStatisticsBaseQO.getOrder(), materialStatisticsBaseQO.getPageNum(), materialStatisticsBaseQO.getPageSize());
        if (CollectionUtils.isNotEmpty(storeUsedData.getResult())) {
            List<String> tempStoreIds = storeUsedData.getResult()
                    .stream()
                    .map(MaterialStoreUsedDataVO::getStoreId)
                    .distinct()
                    .collect(Collectors.toList());
            List<StoreDTO> storeDTOS = storeService.queryStore(tempStoreIds);
            if (CollectionUtils.isNotEmpty(storeDTOS)) {
                Map<String, StoreDTO> storeInfoMap = storeDTOS.stream()
                        .collect(Collectors.toMap(StoreDTO::getStoreId, Function.identity(), (v1, v2) -> v1));
                for (MaterialStoreUsedDataVO materialStoreUsedDataVO : storeUsedData.getResult()) {
                    StoreDTO storeDTO = storeInfoMap.get(materialStoreUsedDataVO.getStoreId());
                    if (storeDTO != null) {
                        materialStoreUsedDataVO.setStoreName(storeDTO.getStoreName());
                        materialStoreUsedDataVO.setStoreCode(storeDTO.getStoreCode());
                    }
                }
            }
        }
        return RestResponse.successResult(storeUsedData);
    }


    // 导购 周报/月报数据

    /**
     * 周/月报--导购/店长-素材使用个人数据
     *
     * @return
     */
    @RequestMapping(path = "/content/material/personal/used/data")
    public RestResponse<MaterialPersonalUsedDataVO> queryMaterialUsedReport(@RequestBody MaterialReportQO materialReportQO) {
        List<String> storeIds = new ArrayList<>();
        if (StringUtils.isBlank(materialReportQO.getStoreId())) {
            storeIds = clerkStoreAdaptor.queryClerkStoreIds(materialReportQO.getClerkId(), materialReportQO.getWxEnterpriseId());
        } else {
            storeIds.add(materialReportQO.getStoreId());
        }

        Page<MaterialPersonalUsedDataVO> usedDataVOPage =
                materialDataAdaptor.queryMaterialClerkUsedReport(materialReportQO, storeIds);
        if (usedDataVOPage == null || CollectionUtils.isEmpty(usedDataVOPage.getResult())) {
            return RestResponse.successResult();
        }
        MaterialPersonalUsedDataVO materialPersonalUsedDataVO = usedDataVOPage.getResult().get(0);
        // 补充导购信息
        ClerkDTO clerkInfo = clerkService.getClerkByClerkId(materialReportQO.getClerkId());
        if (clerkInfo != null) {
            materialPersonalUsedDataVO.setClerkId(materialReportQO.getClerkId());
            materialPersonalUsedDataVO.setClerkName(clerkInfo.getClerkName());
            materialPersonalUsedDataVO.setClerkCode(clerkInfo.getClerkCode());
            materialPersonalUsedDataVO.setImageUrl(clerkInfo.getImageUrl());
        }
        return RestResponse.successResult(materialPersonalUsedDataVO);
    }

    /**
     * 周/月报--查询门店素材使用数据 店长
     *
     * @param materialReportQO
     * @return
     */
    @RequestMapping(path = "/content/material/store/used/data")
    public RestResponse<MaterialStoreUsedDataVO> queryMaterialStoreUseReport(@RequestBody MaterialReportQO materialReportQO) {

        List<String> storeIds = new ArrayList<>();
        if (StringUtils.isBlank(materialReportQO.getStoreId())) {
            storeIds = clerkStoreAdaptor.queryClerkStoreIds(materialReportQO.getClerkId(), materialReportQO.getWxEnterpriseId());
        } else {
            storeIds.add(materialReportQO.getStoreId());
        }

        Page<MaterialStoreUsedDataVO> usedDataVOPage =
                materialDataAdaptor.queryMaterialStoreUseReport(materialReportQO, storeIds);
        if (usedDataVOPage == null || CollectionUtils.isEmpty(usedDataVOPage.getResult())) {
            return RestResponse.successResult();
        }
        MaterialStoreUsedDataVO materialStoreUsedDataVO = usedDataVOPage.getResult().get(0);
        // 补充导购信息
        ClerkDTO clerkInfo = clerkService.getClerkByClerkId(materialReportQO.getClerkId());
        if (clerkInfo != null) {
            materialStoreUsedDataVO.setClerkId(materialReportQO.getClerkId());
            materialStoreUsedDataVO.setClerkName(clerkInfo.getClerkName());
            materialStoreUsedDataVO.setClerkCode(clerkInfo.getClerkCode());
            materialStoreUsedDataVO.setImageUrl(clerkInfo.getImageUrl());
        }
        return RestResponse.successResult(materialStoreUsedDataVO);
    }


    /**
     * 周/月报--查询区经素材使用数据 区经
     *
     * @param materialReportQO
     * @return
     */
    @RequestMapping(path = "/content/material/area/used/data")
    public RestResponse<MaterialAreaUsedDataVO> queryMaterialAreaUseReport(@RequestBody MaterialReportQO materialReportQO) {
        List<String> storeIds = new ArrayList<>();
        if (StringUtils.isBlank(materialReportQO.getStoreId())) {
            storeIds = clerkStoreAdaptor.queryClerkStoreIds(materialReportQO.getClerkId(), materialReportQO.getWxEnterpriseId());
        } else {
            storeIds.add(materialReportQO.getStoreId());
        }
        MaterialAreaUsedDataVO materialAreaUsedDataVO = materialDataAdaptor.queryMaterialAreaOverviewData(materialReportQO.getEnterpriseId(),
                materialReportQO.getClerkId(), materialReportQO.getReportType(), storeIds, materialReportQO.getBizDate());
        return RestResponse.successResult(materialAreaUsedDataVO);
    }


    /**
     * 周/月报--查询导购素材使用数据列表
     *
     * @return
     */
    @RequestMapping(path = "/content/material/personal/used/data/list")
    public RestResponse<Page<MaterialPersonalUsedDataVO>> queryMaterialUsedReportList(@RequestBody MaterialReportQO materialReportQO) {

        List<String> storeIds = new ArrayList<>();
        if (StringUtils.isBlank(materialReportQO.getStoreId())) {
            storeIds = clerkStoreAdaptor.queryClerkStoreIds(materialReportQO.getClerkId(), materialReportQO.getWxEnterpriseId());
        } else {
            storeIds.add(materialReportQO.getStoreId());
        }

        Page<MaterialPersonalUsedDataVO> usedDataVOPage =
                materialDataAdaptor.queryMaterialClerkUsedReport(materialReportQO, storeIds);
        if (usedDataVOPage == null || CollectionUtils.isEmpty(usedDataVOPage.getResult())) {
            return RestResponse.successResult();
        }
        // 补充导购信息
        Set<String> clerkIds = usedDataVOPage.getResult()
                .stream()
                .map(MaterialPersonalUsedDataVO::getClerkId)
                .collect(Collectors.toSet());
        List<ClerkDTO> clerkInfos = clerkService.getClerkByClerkIds(clerkIds);
        Map<String, ClerkDTO> clerkInfoMap = Collections.emptyMap();
        if (CollectionUtils.isNotEmpty(clerkInfos)) {
            clerkInfoMap = clerkInfos.stream()
                    .collect(Collectors.toMap(ClerkDTO::getClerkId, Function.identity(), (v1, v2) -> v1));
        }
        for (MaterialPersonalUsedDataVO materialPersonalUsedDataVO : usedDataVOPage.getResult()) {
            ClerkDTO clerkInfo = clerkInfoMap.get(materialPersonalUsedDataVO.getClerkId());
            if (clerkInfo != null) {
                materialPersonalUsedDataVO.setClerkId(materialReportQO.getClerkId());
                materialPersonalUsedDataVO.setClerkName(clerkInfo.getClerkName());
                materialPersonalUsedDataVO.setClerkCode(clerkInfo.getClerkCode());
                materialPersonalUsedDataVO.setImageUrl(clerkInfo.getImageUrl());
            }
        }

        return RestResponse.successResult(usedDataVOPage);
    }


    /**
     * 周/月报--查询门店纬度素材使用数据列表
     *
     * @param materialReportQO
     * @return
     */
    @RequestMapping(path = "/content/material/store/used/data/list")
    public RestResponse<Page<MaterialStoreUsedDataVO>> queryMaterialStoreUseReportList(@RequestBody MaterialReportQO materialReportQO) {
        List<String> storeIds = new ArrayList<>();
        if (StringUtils.isBlank(materialReportQO.getStoreId())) {
            storeIds = clerkStoreAdaptor.queryClerkStoreIds(materialReportQO.getClerkId(), materialReportQO.getWxEnterpriseId());
        } else {
            storeIds.add(materialReportQO.getStoreId());
        }

        Page<MaterialStoreUsedDataVO> usedDataVOPage =
                materialDataAdaptor.queryMaterialStoreUseReport(materialReportQO, storeIds);
        if (usedDataVOPage == null || CollectionUtils.isEmpty(usedDataVOPage.getResult())) {
            return RestResponse.successResult();
        }
        // 补充门店信息
        List<String> tempStoreIds = usedDataVOPage.getResult()
                .stream()
                .map(MaterialStoreUsedDataVO::getStoreId)
                .collect(Collectors.toList());
        List<StoreDTO> storeDTOS = storeService.queryStore(tempStoreIds);
        Map<String, StoreDTO> storeInfoMap = Collections.emptyMap();
        if (CollectionUtils.isNotEmpty(storeDTOS)) {
            storeInfoMap = storeDTOS
                    .stream()
                    .collect(Collectors.toMap(StoreDTO::getStoreId, Function.identity(), (v1, v2) -> v1));
        }
        for (MaterialStoreUsedDataVO materialStoreUsedDataVO : usedDataVOPage.getResult()) {
            StoreDTO storeDTO = storeInfoMap.get(materialStoreUsedDataVO.getStoreId());
            if (storeDTO != null) {
                materialStoreUsedDataVO.setStoreCode(storeDTO.getStoreCode());
                materialStoreUsedDataVO.setStoreName(storeDTO.getStoreName());
            }
        }
        return RestResponse.successResult(usedDataVOPage);
    }

}
