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

import cn.hutool.core.collection.CollectionUtil;
import com.gic.cloud.common.api.base.Page;
import com.gic.cloud.data.api.dto.*;
import com.gic.cloud.data.api.service.MaidianDataService;
import com.gic.cloud.web.service.api.dto.CloudStoreGroupDTO;
import com.gic.cloud.web.service.api.service.CloudStoreGroupService;
import com.gic.commons.util.EntityUtil;
import com.gic.haoban.common.utils.AuthWebRequestUtil;
import com.gic.haoban.common.utils.ExcelUtils;
import com.gic.haoban.common.utils.HaobanResponse;
import com.gic.haoban.manage.api.service.StaffApiService;
import com.gic.haoban.manage.web.errCode.HaoBanErrCode;
import com.gic.redis.data.util.RedisUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("web")
public class MaidianDataController extends WebBaseController {

    private static final Logger logger = LoggerFactory.getLogger(MaidianDataController.class);

    @Autowired
    private MaidianDataService maidianDataService;
    @Autowired
    private CloudStoreGroupService cloudStoreGroupService;
    @Autowired
    private StaffApiService staffApiService;

    //首页-分组列表
    @RequestMapping("/use-haoban3-service")
    public HaobanResponse useHaoban3Service(String wxEnterpriseId) {
        Object o = RedisUtil.getCache("usesMaidianWxEnterpriseId");
        boolean b = false;
        if (o != null) {
            String wxEnterpriseIds = o.toString();
            if (wxEnterpriseIds.contains(wxEnterpriseId) || "-1".equals(wxEnterpriseIds)) {
                b = true;
            }
        }
        return resultResponse(HaoBanErrCode.ERR_1, b);
    }

    //首页-分组列表
    @RequestMapping("/cloud-grouplist-pid")
    public HaobanResponse cloudGrouplistPid(String enterpriseId) {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        List<CloudStoreGroupDTO> list = cloudStoreGroupService.queryAllStoreGroupByStoreGroupId(enterpriseId);
        if (CollectionUtil.isEmpty(list)) {
            list = new ArrayList<>();
        }
        returnMap.put("list", list);
        return resultResponse(HaoBanErrCode.ERR_1, returnMap);
    }

    //首页-企业概况
    @RequestMapping("/total-activation-data")
    public HaobanResponse totalActivationData(MemberAnalyzeParamsDTO paramsDTO) {
        List<String> storeList = staffApiService.getHaoBanStoreIdsRolesByClerkId(AuthWebRequestUtil.getLoginUser().getClerkId(), AuthWebRequestUtil.getLoginUser().getWxEnterpriseId());
        if(CollectionUtils.isEmpty(storeList)) {
            return resultResponse(HaoBanErrCode.ERR_100007);
        }
        if(!(storeList.size()==1 && storeList.contains("-1"))) {
            paramsDTO.setStoreIdList(storeList);
        }
        paramsDTO.setWebFlag(1);
        Map<String, Object> returnMap = new HashMap<String, Object>();
        AdsGicLogHaobanStoreLoginDDTO dto = maidianDataService.totalActivationData(paramsDTO);
        if (dto == null) {
            return resultResponse(HaoBanErrCode.ERR_1, returnMap);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        paramsDTO.setStartDate(sdf.format(new Date()));
        AdsGicLogHaobanStoreLoginDDTO today = maidianDataService.totalActivationData(paramsDTO);
        if (today == null) {
            today = new AdsGicLogHaobanStoreLoginDDTO();
        }
        returnMap.put("loginClerkCnt", dto.getLoginClerkCnt());
        returnMap.put("activeClerkCnt", dto.getActiveClerkCnt());
        returnMap.put("loginClerkTimes", dto.getLoginClerkTimes());
        returnMap.put("notActiveClerkCnt", dto.getNotActiveClerkCnt());
        returnMap.put("totalClerkCnt", dto.getTotalClerkCnt());
        returnMap.put("notLoginClerkCnt", dto.getNotLoginClerkCnt());
        if (dto.getLoginClerkCnt() == null || dto.getLoginClerkCnt() == 0) {
            returnMap.put("avgLoginTimes", 0);
            returnMap.put("avgVisitTime", 0);
        } else {
            returnMap.put("avgLoginTimes", dto.getLoginClerkTimes() / dto.getLoginClerkCnt());
            returnMap.put("avgVisitTime", dto.getStayTime() / dto.getLoginClerkCnt());
        }
        returnMap.put("toDayLoginClerkCnt", today.getLoginClerkCnt());

        return resultResponse(HaoBanErrCode.ERR_1, returnMap);
    }

    //首页-好办登陆信息总人数概况
    @RequestMapping("/total-login-data")
    public HaobanResponse totalLoginData(MemberAnalyzeParamsDTO paramsDTO, int datesType) {
        paramsDTO.setWebFlag(1);
        List<String> storeList = staffApiService.getHaoBanStoreIdsRolesByClerkId(AuthWebRequestUtil.getLoginUser().getClerkId(),AuthWebRequestUtil.getLoginUser().getWxEnterpriseId());
        if(CollectionUtils.isEmpty(storeList)) {
            return resultResponse(HaoBanErrCode.ERR_100007);
        }
        if(!(storeList.size()==1 && storeList.contains("-1"))) {
            paramsDTO.setStoreIdList(storeList);
        }
        Map<String, Object> returnMap = new HashMap<String, Object>();
        List<HaobanLoginInfoDTO> resultList = new ArrayList<HaobanLoginInfoDTO>();
        if (datesType == 1) {
            //近7日
            List<AdsGicLogHaobanStoreLoginDDTO> list = maidianDataService.totalLoginData(paramsDTO);
            resultList = EntityUtil.changeEntityListByJSON(HaobanLoginInfoDTO.class, list);
        } else {
            //当日
            List<AdsGicLogHaobanStoreIntervalLoginDDTO> list = maidianDataService.totalLoginInternalData(paramsDTO);
            resultList = EntityUtil.changeEntityListByJSON(HaobanLoginInfoDTO.class, list);
        }
        for (HaobanLoginInfoDTO dto : resultList) {
            if (dto.getLoginClerkCnt() == 0) {
                dto.setAvgVisitTime("0");
                dto.setAvgLoginTimes("0");
            } else {
                dto.setAvgVisitTime((double) dto.getStayTime() / dto.getLoginClerkCnt() + "");
                dto.setAvgLoginTimes(dto.getLoginClerkTimes() / dto.getLoginClerkCnt() + "");
            }
        }
        if (CollectionUtil.isEmpty(resultList)) {
            resultList = new ArrayList<>();
        }
        returnMap.put("result", resultList);
        return resultResponse(HaoBanErrCode.ERR_1, returnMap);
    }

    //首页-区域排行
    @RequestMapping("/area-login-ranking")
    public HaobanResponse areaLoginRanking(MemberAnalyzeParamsDTO paramsDTO) {
        paramsDTO.setWebFlag(1);
        List<String> storeList = staffApiService.getHaoBanStoreIdsRolesByClerkId(AuthWebRequestUtil.getLoginUser().getClerkId(),AuthWebRequestUtil.getLoginUser().getWxEnterpriseId());
        if(CollectionUtils.isEmpty(storeList)) {
            return resultResponse(HaoBanErrCode.ERR_100007);
        }
        if(!(storeList.size()==1 && storeList.contains("-1"))) {
            paramsDTO.setStoreIdList(storeList);
        }
        Map<String, Object> returnMap = new HashMap<String, Object>();
        List<AreaLoginDTO> list = maidianDataService.areaLoginRanking(paramsDTO);
        if (CollectionUtil.isEmpty(list)) {
            list = new ArrayList<>();
        }
        returnMap.put("result", list);
        return resultResponse(HaoBanErrCode.ERR_1, returnMap);
    }

    //激活明细-激活趋势图
    @RequestMapping("/activite-date")
    public HaobanResponse activiteDate(MemberAnalyzeParamsDTO paramsDTO) {
        paramsDTO.setWebFlag(1);
        List<String> storeList = staffApiService.getHaoBanStoreIdsRolesByClerkId(AuthWebRequestUtil.getLoginUser().getClerkId(),AuthWebRequestUtil.getLoginUser().getWxEnterpriseId());
        if(CollectionUtils.isEmpty(storeList)) {
            return resultResponse(HaoBanErrCode.ERR_100007);
        }
        if(!(storeList.size()==1 && storeList.contains("-1"))) {
            paramsDTO.setStoreIdList(storeList);
        }
        Map<String, Object> returnMap = new HashMap<String, Object>();
        List<HaobanLoginInfoDTO> resultList = new ArrayList<HaobanLoginInfoDTO>();
        //近7日
        List<AdsGicLogHaobanStoreLoginDDTO> list = maidianDataService.totalLoginData(paramsDTO);
        resultList = EntityUtil.changeEntityListByJSON(HaobanLoginInfoDTO.class, list);
        if (CollectionUtil.isEmpty(resultList)) {
            resultList = new ArrayList<>();
        }
        returnMap.put("result", resultList);
        return resultResponse(HaoBanErrCode.ERR_1, returnMap);
    }

    //激活明细-激活列表
    @RequestMapping("/activite-list")
    public HaobanResponse activiteList(MemberAnalyzeParamsDTO paramsDTO) {
        paramsDTO.setWebFlag(1);
        List<String> storeList = staffApiService.getHaoBanStoreIdsRolesByClerkId(AuthWebRequestUtil.getLoginUser().getClerkId(),AuthWebRequestUtil.getLoginUser().getWxEnterpriseId());
        if(CollectionUtils.isEmpty(storeList)) {
            return resultResponse(HaoBanErrCode.ERR_100007);
        }
        if(!(storeList.size()==1 && storeList.contains("-1"))) {
            paramsDTO.setStoreIdList(storeList);
        }
        Page<HaobanClerkLoginDTO> page = maidianDataService.pageActiviteList(paramsDTO);
        return resultResponse(HaoBanErrCode.ERR_1, page);

    }

    //导出-激活明细-激活列表
    @RequestMapping("/export-activite-list")
    public HaobanResponse exportActiviteList(HttpServletRequest request, HttpServletResponse response, MemberAnalyzeParamsDTO paramsDTO) {
        paramsDTO.setWebFlag(1);
        List<String> storeList = staffApiService.getHaoBanStoreIdsRolesByClerkId(AuthWebRequestUtil.getLoginUser().getClerkId(),AuthWebRequestUtil.getLoginUser().getWxEnterpriseId());
        if(CollectionUtils.isEmpty(storeList)) {
            return resultResponse(HaoBanErrCode.ERR_100007);
        }
        if(!(storeList.size()==1 && storeList.contains("-1"))) {
            paramsDTO.setStoreIdList(storeList);
        }
        paramsDTO.setCurrentPage(1);
        paramsDTO.setPageSize(Integer.MAX_VALUE);
        Page<HaobanClerkLoginDTO> page = maidianDataService.pageActiviteList(paramsDTO);
        List<String> titleList = Arrays.asList("导购姓名", "导购代码", "归属门店", "最后登录时间", "活跃状态");
        List<String> fileList = Arrays.asList("clerkName", "clerkCode", "storeName", "lastLoginTime", "activationStatus");
        try {
            ExcelUtils.xls(response, request, "详情报表", page.getList(), fileList, titleList);
        } catch (Exception e) {
            logger.info(e.getMessage(), e);
        }
        return resultResponse(HaoBanErrCode.ERR_1);
    }

    //导出-登陆明细-明细列表
    @RequestMapping("/export-login-detail-list")
    public HaobanResponse exportLoginDetailList(HttpServletRequest request, HttpServletResponse response, MemberAnalyzeParamsDTO paramsDTO) {
        paramsDTO.setWebFlag(1);
        List<String> storeList = staffApiService.getHaoBanStoreIdsRolesByClerkId(AuthWebRequestUtil.getLoginUser().getClerkId(),AuthWebRequestUtil.getLoginUser().getWxEnterpriseId());
        if(CollectionUtils.isEmpty(storeList)) {
            return resultResponse(HaoBanErrCode.ERR_100007);
        }
        if(!(storeList.size()==1 && storeList.contains("-1"))) {
            paramsDTO.setStoreIdList(storeList);
        }
        //默认排序
        if (StringUtils.isEmpty(paramsDTO.getSortColumn())) {
            paramsDTO.setSortColumn("lastLoginTime");
        }
        if (StringUtils.isEmpty(paramsDTO.getSortType())) {
            paramsDTO.setSortType("desc");
        }
        paramsDTO.setCurrentPage(1);
        paramsDTO.setPageSize(Integer.MAX_VALUE);
        Page<HaobanClerkLoginDTO> page = maidianDataService.pageClerkLogin(paramsDTO);
        if (paramsDTO.getLoginStatus() == 1) {
            //已登陆
            try {
                List<String> titleList = Arrays.asList("导购姓名", "导购代码", "归属门店", "最后登录时间", "登录次数", "平均访问总时长");
                List<String> fileList = Arrays.asList("clerkName", "clerkCode", "storeName", "lastLoginTime", "loginTimes", "avgVisitTimeString");
                ExcelUtils.xls(response, request, "详情报表", page.getList(), fileList, titleList);
            } catch (Exception e) {
                logger.info(e.getMessage(), e);
            }
        } else {
            //未登陆
            try {
                List<String> titleList = Arrays.asList("导购姓名", "导购代码", "归属门店", "最后登录时间");
                List<String> fileList = Arrays.asList("clerkName", "clerkCode", "storeName", "lastLoginTime");
                ExcelUtils.xls(response, request, "详情报表", page.getList(), fileList, titleList);
            } catch (Exception e) {
                logger.info(e.getMessage(), e);
            }
        }
        return resultResponse(HaoBanErrCode.ERR_1);
    }

    //登陆明细-明细列表
    @RequestMapping("/login-detail-list")
    public HaobanResponse loginDetailList(MemberAnalyzeParamsDTO paramsDTO) {
        paramsDTO.setWebFlag(1);
        List<String> storeList = staffApiService.getHaoBanStoreIdsRolesByClerkId(AuthWebRequestUtil.getLoginUser().getClerkId(),AuthWebRequestUtil.getLoginUser().getWxEnterpriseId());
        if(CollectionUtils.isEmpty(storeList)) {
            return resultResponse(HaoBanErrCode.ERR_100007);
        }
        if(!(storeList.size()==1 && storeList.contains("-1"))) {
            paramsDTO.setStoreIdList(storeList);
        }
        //默认排序
        if (StringUtils.isEmpty(paramsDTO.getSortColumn())) {
            paramsDTO.setSortColumn("lastLoginTime");
        }
        if (StringUtils.isEmpty(paramsDTO.getSortType())) {
            paramsDTO.setSortType("desc");
        }
        Map<String, Object> returnMap = new HashMap<String, Object>();
        Page<HaobanClerkLoginDTO> page = maidianDataService.pageClerkLogin(paramsDTO);
        returnMap.put("result", page);
        return resultResponse(HaoBanErrCode.ERR_1, returnMap);
    }

    //区域排行-区域图表
    @RequestMapping("area-ranking-date")
    public HaobanResponse areaRankingDate(MemberAnalyzeParamsDTO paramsDTO) {
        paramsDTO.setWebFlag(1);
        List<String> storeList = staffApiService.getHaoBanStoreIdsRolesByClerkId(AuthWebRequestUtil.getLoginUser().getClerkId(),AuthWebRequestUtil.getLoginUser().getWxEnterpriseId());
        if(CollectionUtils.isEmpty(storeList)) {
            return resultResponse(HaoBanErrCode.ERR_100007);
        }
        if(!(storeList.size()==1 && storeList.contains("-1"))) {
            paramsDTO.setStoreIdList(storeList);
        }
        Map<String, Object> returnMap = new HashMap<String, Object>();
        List<AreaLoginDTO> list = maidianDataService.areaRankingDate(paramsDTO);
        returnMap.put("result", list);
        return resultResponse(HaoBanErrCode.ERR_1, returnMap);
    }

    //区域排行-区域列表
    @RequestMapping("/area-ranking-list")
    public HaobanResponse areaRankingList(MemberAnalyzeParamsDTO paramsDTO) {
        paramsDTO.setWebFlag(1);
        List<String> storeList = staffApiService.getHaoBanStoreIdsRolesByClerkId(AuthWebRequestUtil.getLoginUser().getClerkId(),AuthWebRequestUtil.getLoginUser().getWxEnterpriseId());
        if(CollectionUtils.isEmpty(storeList)) {
            return resultResponse(HaoBanErrCode.ERR_100007);
        }
        if(!(storeList.size()==1 && storeList.contains("-1"))) {
            paramsDTO.setStoreIdList(storeList);
        }
        //默认排序
        if (StringUtils.isEmpty(paramsDTO.getSortColumn())) {
            paramsDTO.setSortColumn("loginRate");
        }
        if (StringUtils.isEmpty(paramsDTO.getSortType())) {
            paramsDTO.setSortType("desc");
        }
        paramsDTO.setAreaType("store");
        Map<String, Object> returnMap = new HashMap<String, Object>();
        Page<AreaLoginDTO> page = maidianDataService.areaRankingList(paramsDTO);
        returnMap.put("result", page);
        return resultResponse(HaoBanErrCode.ERR_1, returnMap);
    }

    //导出-区域排行-区域列表
    @RequestMapping("/export-area-ranking-list")
    public HaobanResponse exportAreaRankingList(HttpServletRequest request, HttpServletResponse response, MemberAnalyzeParamsDTO paramsDTO) {
        paramsDTO.setWebFlag(1);
        List<String> storeList = staffApiService.getHaoBanStoreIdsRolesByClerkId(AuthWebRequestUtil.getLoginUser().getClerkId(),AuthWebRequestUtil.getLoginUser().getWxEnterpriseId());
        if(CollectionUtils.isEmpty(storeList)) {
            return resultResponse(HaoBanErrCode.ERR_100007);
        }
        if(!(storeList.size()==1 && storeList.contains("-1"))) {
            paramsDTO.setStoreIdList(storeList);
        }
        //默认排序
        if (StringUtils.isEmpty(paramsDTO.getSortColumn())) {
            paramsDTO.setSortColumn("loginRate");
        }
        if (StringUtils.isEmpty(paramsDTO.getSortType())) {
            paramsDTO.setSortType("desc");
        }
        paramsDTO.setAreaType("store");
        paramsDTO.setCurrentPage(1);
        paramsDTO.setPageSize(Integer.MAX_VALUE);
        Page<AreaLoginDTO> page = maidianDataService.areaRankingList(paramsDTO);
        List<String> titleList = Arrays.asList("门店名称", "门店code", "分组名称", "登录率", "登录人数");
        List<String> fileList = Arrays.asList("exportName", "storeCode", "storeGroupName", "loginRateString", "loginClerkCnt");
        try {
            ExcelUtils.xls(response, request, "详情报表", page.getList(), fileList, titleList);
        } catch (Exception e) {
            logger.info(e.getMessage(), e);
        }
        return resultResponse(HaoBanErrCode.ERR_1);
    }
}
