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

import cn.hutool.core.date.DateTime;
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.ContentMaterialDTO;
import com.gic.content.api.dto.material.ContentMaterialFrontDTO;
import com.gic.content.api.enums.MaterialSearchSceneEnum;
import com.gic.content.api.qdto.material.ContentMaterialPageFrontQDTO;
import com.gic.content.api.qdto.material.ContentMaterialPageQDTO;
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.api.enums.content.MaterialReportType;
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.*;
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.BeanUtils;
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) {

        ContentMaterialPageQDTO search = new ContentMaterialPageQDTO();
        search.setQueryScene(MaterialSearchSceneEnum.HAOBAN_MARKETING.value);
        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<ContentMaterialDTO>> serviceResponse = this.contentMaterialApiService.pageMaterial(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(temp.getOmniConvSalesAmt())
                .storeManagerNum(totalManagerStoreNum)
                .clickUserNum(temp.getClickUserNum())
                .offlineConvUserNum(temp.getOfflineConvUserNum())
                .offlineConvSalesAmt(temp.getOfflineConvSalesAmt())
                .omniConvSalesAmt(temp.getOmniConvSalesAmt())
                .omniConvUserNum(temp.getOmniConvUserNum())
                .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();
        BeanUtils.copyProperties(materialTodayDataBO, temp);
        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, 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,storeIds);
        return RestResponse.successResult(clerkUsedData);
    }

    /**
     * 素材使用分析页面-门店纬度使用数据
     *
     * @return
     */
    @RequestMapping(path = "/content/material/store/data")
    public RestResponse<Page<MaterialStoreUsedDataVO>> queryMaterialStoreUsedData(@RequestBody MaterialStoreAnalyzeDataQO 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,storeIds);
        if (CollectionUtils.isNotEmpty(storeUsedData.getResult())) {
            List<String> tempStoreIds = storeUsedData.getResult()
                    .stream()
                    .map(MaterialStoreUsedDataVO::getStoreId)
                    .collect(Collectors.toList());
            String[] storeIdsArry = new String[tempStoreIds.size()];
            List<StoreDTO> storeDTOS = storeService.getStores(tempStoreIds.toArray(storeIdsArry));
            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());
        }

        ClerkDTO clerkInfo = clerkService.getClerkByClerkId(materialReportQO.getClerkId());
        Page<MaterialPersonalUsedDataVO> usedDataVOPage =
                materialDataAdaptor.queryMaterialClerkUsedReport(materialReportQO, storeIds);
        if (usedDataVOPage == null || CollectionUtils.isEmpty(usedDataVOPage.getResult())) {
            DateTime startTime = null;
            DateTime endTime = null;
            if (MaterialReportType.WEEK.getCode().equals(materialReportQO.getReportType())) {
                // 周报
                startTime = DateUtil.beginOfWeek(DateUtil.lastWeek());
                endTime = DateUtil.endOfWeek(DateUtil.lastWeek());
            } else {
                startTime = DateUtil.beginOfMonth(DateUtil.lastMonth());
                endTime = DateUtil.endOfMonth(DateUtil.lastMonth());
            }
            MaterialPersonalUsedDataVO temp = new MaterialPersonalUsedDataVO();
            temp.setStartTime(startTime);
            temp.setEndTime(endTime);
            if (clerkInfo != null) {
                temp.setClerkId(materialReportQO.getClerkId());
                temp.setClerkName(clerkInfo.getClerkName());
                temp.setClerkCode(clerkInfo.getClerkCode());
                temp.setImageUrl(clerkInfo.getImageUrl());
            }
            return RestResponse.successResult(temp);
        }
        MaterialPersonalUsedDataVO materialPersonalUsedDataVO = usedDataVOPage.getResult().get(0);
        // 补充导购信息
        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 MaterialStoreReportQO materialReportQO) {

        List<String> storeIds = new ArrayList<>();
        if (StringUtils.isBlank(materialReportQO.getStoreId())) {
            storeIds = clerkStoreAdaptor.queryClerkStoreIds(materialReportQO.getClerkId(), materialReportQO.getWxEnterpriseId());
        } else {
            storeIds.add(materialReportQO.getStoreId());
        }
        // 补充导购信息
        ClerkDTO clerkInfo = clerkService.getClerkByClerkId(materialReportQO.getClerkId());
        Page<MaterialStoreUsedDataVO> usedDataVOPage =
                materialDataAdaptor.queryMaterialStoreUseReport(materialReportQO, storeIds);
        if (usedDataVOPage == null || CollectionUtils.isEmpty(usedDataVOPage.getResult())) {
            MaterialStoreUsedDataVO temp = new MaterialStoreUsedDataVO();
            DateTime startTime = null;
            DateTime endTime = null;
            if (MaterialReportType.WEEK.getCode().equals(materialReportQO.getReportType())) {
                // 周报
                startTime = DateUtil.beginOfWeek(DateUtil.lastWeek());
                endTime = DateUtil.endOfWeek(DateUtil.lastWeek());
            } else {
                startTime = DateUtil.beginOfMonth(DateUtil.lastMonth());
                endTime = DateUtil.endOfMonth(DateUtil.lastMonth());
            }
            temp.setStartTime(startTime);
            temp.setEndTime(endTime);
            if (clerkInfo != null) {
                temp.setClerkId(materialReportQO.getClerkId());
                temp.setClerkName(clerkInfo.getClerkName());
                temp.setClerkCode(clerkInfo.getClerkCode());
                temp.setImageUrl(clerkInfo.getImageUrl());
            }
            return RestResponse.successResult(temp);
        }
        MaterialStoreUsedDataVO materialStoreUsedDataVO = usedDataVOPage.getResult().get(0);
        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());
        }

        materialReportQO.setClerkId(null);
        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(clerkInfo.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 MaterialStoreReportQO materialReportQO) {
        List<String> storeIds = new ArrayList<>();
        if (StringUtils.isBlank(materialReportQO.getStoreId())) {
            storeIds = clerkStoreAdaptor.queryClerkStoreIds(materialReportQO.getClerkId(), materialReportQO.getWxEnterpriseId());
        } else {
            storeIds.add(materialReportQO.getStoreId());
        }

        if (StringUtils.isNotBlank(materialReportQO.getOrderByField())) {
            if (StringUtils.equals("dayAvgUseRate", materialReportQO.getOrderByField())) {
                // 日均使用导购数
                materialReportQO.setOrderByField("dayAvgUseBindProportion");
            }
            if (StringUtils.equals("convSalesNmt", materialReportQO.getOrderByField())) {
                // 客户转化金额
                materialReportQO.setOrderByField("convSalesAmt");
            }

            if (StringUtils.equals("clickUserNum", materialReportQO.getOrderByField())) {
                // 店家客户数
                materialReportQO.setOrderByField("userClickNum");
            }
        }
        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());
        String[] storeIdsArry = new String[tempStoreIds.size()];
        List<StoreDTO> storeDTOS = storeService.getStores(tempStoreIds.toArray(storeIdsArry));
        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);
    }

}
