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

import cn.hutool.core.date.DatePattern;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gic.api.base.commons.JSONResponse;
import com.gic.api.base.commons.Page;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.clerk.api.dto.AuthorizedUser;
import com.gic.commons.util.DateUtil;
import com.gic.commons.util.EntityUtil;
import com.gic.commons.util.PageHelperUtils;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.enterprise.api.dto.StoreDTO;
import com.gic.enterprise.api.dto.StoreSearchDTO;
import com.gic.enterprise.api.service.StoreGroupService;
import com.gic.enterprise.api.service.StoreService;
import com.gic.haoban.base.api.common.pojo.dto.WebLoginDTO;
import com.gic.haoban.common.utils.AuthWebRequestUtil;
import com.gic.haoban.manage.api.dto.moment.QwMomentPlanAttendDTO;
import com.gic.haoban.manage.api.dto.moment.QwMomentPlanDTO;
import com.gic.haoban.manage.api.dto.moment.QwMomentPlanDataDTO;
import com.gic.haoban.manage.api.qdto.moment.PlanClerkListQDTO;
import com.gic.haoban.manage.api.qdto.moment.PlanDataListQDTO;
import com.gic.haoban.manage.api.qdto.moment.QwMomentPlanQDTO;
import com.gic.haoban.manage.api.service.moment.QwMomentApiService;
import com.gic.haoban.manage.web.log.LogRecordUserServiceImpl;
import com.gic.haoban.manage.web.qo.moment.PlanClerkListQO;
import com.gic.haoban.manage.web.qo.moment.PlanDataListQO;
import com.gic.haoban.manage.web.qo.moment.PlanListQO;
import com.gic.haoban.manage.web.qo.moment.QwMomentPlanQO;
import com.gic.haoban.manage.web.utils.CreatorUtils;
import com.gic.haoban.manage.web.vo.moment.ClerkVO;
import com.gic.haoban.manage.web.vo.moment.HaobanQwMomentPlanVO;
import com.gic.haoban.manage.web.vo.moment.QwMomentPlanAttendVO;
import com.gic.haoban.manage.web.vo.moment.QwMomentPlanDataVO;
import com.gic.log.record.anno.GicLogRecord;
import com.gic.log.record.util.GicLogRecordCategoryEnum;
import com.gic.log.record.util.GicLogRecordEvaluationContext;
import com.gic.log.record.util.GicLogRecordOptTypeEnum;
import com.gic.member.api.dto.es.MemberDataDTO;
import com.gic.qcloud.BucketNameEnum;
import com.gic.search.engine.api.constant.OperateEnum;
import com.gic.search.engine.api.dto.ESResponseQueryBatch;
import com.gic.search.engine.api.dto.dynamic.DynamicSearchDTO;
import com.gic.search.engine.api.filter.NewNodeAddUtil;
import com.gic.search.engine.api.service.dynamic.ESDataDynamicOperationApiService;
import com.gic.web.common.download.DownloadTask;
import com.gic.web.common.download.DownloadTaskUtil;
import com.gic.web.common.download.constants.TaskTypeEnum;
import com.google.common.collect.Sets;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * 企微朋友圈
 */
@RestController
@RequestMapping("/qw-moment")
public class QwMomentController {

    private static Logger logger = LogManager.getLogger(QwMomentController.class);

    @Autowired
    private QwMomentApiService qwMomentApiService ;
    @Autowired
    private MomentPlanExcelHandler momentPlanExcelHandler ;
    @Autowired
    private MomentClerkExcelHandler momentClerkExcelHandler ;
    @Autowired
    private MomentDataExcelHandler momentDataExcelHandler ;
    @Autowired
    private StoreService storeService ;
    @Autowired
    private ESDataDynamicOperationApiService esDataDynamicOperationApiService ;
    @Autowired
    private StoreGroupService storeGroupService;

    /**
     * 新建任务
     */
    @RequestMapping("add")
    @ResponseBody
    @GicLogRecord(value = "${#logValue}", category = GicLogRecordCategoryEnum.QW_MOMENT, optType = GicLogRecordOptTypeEnum.QW_MOMENT_ADD, userFunc = LogRecordUserServiceImpl.class, optPage = "企微朋友圈-朋友圈列表-新建页面")
    public RestResponse<String> add(@RequestBody QwMomentPlanQO qo){
        logger.info("新建任务={}", JSONObject.toJSONString(qo));
        QwMomentPlanDTO plan = EntityUtil.changeEntityByJSON(QwMomentPlanDTO.class,qo) ;
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        plan.setEnterpriseId(loginUser.getEnterpriseId());
        plan.setWxEnterpriseId(loginUser.getWxEnterpriseId());
        plan.setCreatorId(loginUser.getClerkId());
        plan.setCreatorName(loginUser.getClerkName());
        ServiceResponse<QwMomentPlanDTO> resp = this.qwMomentApiService.save(plan) ;
        String logContent = "新增企微朋友圈活动【" + resp.getResult().getTitle() + "-" + resp.getResult().getPlanId() + "】";
        GicLogRecordEvaluationContext.putAttribute("logValue", logContent);
        return RestResponse.successResult(resp.getResult().getPlanId()+"")  ;
    }


    /**
     * 更新
     */
    @RequestMapping("update")
    @ResponseBody
    @GicLogRecord(value = "${#logValue}", category = GicLogRecordCategoryEnum.QW_MOMENT, optType = GicLogRecordOptTypeEnum.QW_MOMENT_EIDT, userFunc = LogRecordUserServiceImpl.class, optPage = "企微朋友圈-朋友圈列表-编辑页面")
    public RestResponse<String> update(@RequestBody QwMomentPlanQO qo) {
        logger.info("更新任务={}", JSONObject.toJSONString(qo));
        if(null == qo.getPlanId()) {
            GicLogRecordEvaluationContext.noWriteLog();
            return RestResponse.failure("9999","活动id为空") ;
        }
        ServiceResponse<QwMomentPlanDTO> planResp = this.qwMomentApiService.detail(qo.getPlanId()) ;
        if(null == planResp.getResult()) {
            GicLogRecordEvaluationContext.noWriteLog();
            return RestResponse.failure("9999","活动不存在") ;
        }
        QwMomentPlanDTO oldPlan = planResp.getResult() ;

        QwMomentPlanDTO plan = EntityUtil.changeEntityByJSON(QwMomentPlanDTO.class,qo) ;
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        plan.setEnterpriseId(loginUser.getEnterpriseId());
        plan.setWxEnterpriseId(loginUser.getWxEnterpriseId());
        plan.setCreatorId(loginUser.getClerkId());
        plan.setCreatorName(loginUser.getClerkName());

        ServiceResponse<QwMomentPlanDTO> resp = this.qwMomentApiService.save(plan) ;
        String logTitle = "编辑企微朋友圈活动【" + resp.getResult().getTitle() + "-" + resp.getResult().getPlanId() + "】";
        ServiceResponse<QwMomentPlanDTO> newPlanResp = this.qwMomentApiService.detail(qo.getPlanId()) ;
        String logContent = this.getLogContent(loginUser.getEnterpriseId(), oldPlan, newPlanResp.getResult());
        logger.info("日志内容logContent={}",logContent);
        if(StringUtils.isBlank(logContent.trim())) {
            GicLogRecordEvaluationContext.noWriteLog();
        }else {
            GicLogRecordEvaluationContext.putAttribute("logValue", logTitle + logContent);
        }
        return RestResponse.successResult(resp.getResult().getPlanId()+"")  ;
    }

    private String getLogContent(String enterpriseId ,QwMomentPlanDTO oldDTO , QwMomentPlanDTO newDTO) {
        List<String> logList = new ArrayList<>();
        this.otherLog("活动标题",oldDTO.getTitle(),newDTO.getTitle() , logList) ;
        this.otherLog("活动描述",oldDTO.getRemark(),newDTO.getRemark() , logList) ;

        String oldExecType = "" ;
        String newExecType = "" ;
        this.otherLog("执行方式",oldExecType,newExecType , logList) ;

        // 0全部导购 1部分导购
        int oldPlanClerkType = oldDTO.getPlanClerkType() ;
        int newPlanClerkTyp = newDTO.getPlanClerkType() ;
        if(oldPlanClerkType==0 && newPlanClerkTyp==1) {
            this.otherLog("执行人类型","全部导购","部分导购" , logList) ;
        }else  if(oldPlanClerkType==1 && newPlanClerkTyp==0) {
            this.otherLog("执行人类型","部分导购","全部导购" , logList) ;
        }else if(oldPlanClerkType==1 && newPlanClerkTyp==1) {
            List<String> oldClerkIdList = oldDTO.getClerkList().stream().map(o->o.getClerkId()).collect(Collectors.toList());
            List<String> newClerkIdList = newDTO.getClerkList().stream().map(o->o.getClerkId()).collect(Collectors.toList());
            String del = "" ;
            String add = "" ;
            for(String clerkId : oldClerkIdList) {
                List<String> nameList = new ArrayList<>() ;
                if(!newClerkIdList.contains(clerkId)) {
                    nameList.add(clerkId);
                }
                if(CollectionUtils.isNotEmpty(nameList)) {
                    del = "删除【"+nameList.stream().collect(Collectors.joining("、"))+"】" ;
                }
            }
            for(String clerkId : newClerkIdList) {
                List<String> nameList = new ArrayList<>() ;
                if(!oldClerkIdList.contains(clerkId)) {
                    nameList.add(clerkId);
                }
                if(CollectionUtils.isNotEmpty(nameList)) {
                    add = "新增【"+nameList.stream().collect(Collectors.joining("、"))+"】" ;
                }
            }
            if(StringUtils.isNotBlank(del) || StringUtils.isNotBlank(add)) {
                logList.add("修改部分导购："+ add +  ";" + del);
            }
        }
        if(!oldDTO.getMediaInfo().equals(newDTO.getMediaInfo())) {
            logList.add("变更朋友圈配置");
        }
        // 1立即发布2定时发布
        int oldPublishType = oldDTO.getPublishType() ;
        int newPublishType = newDTO.getPublishType() ;
        if(oldPublishType==2 && newPublishType==1) {
            Date publishTime = oldDTO.getPublishTime() ;
            this.otherLog("发送时间","定时发布-"+DateUtil.dateToStr(publishTime,"yyyy-MM-dd HH:mm:ss"),"立即发布" , logList) ;
        }else if(oldPublishType==2 && newPublishType==2) {
            Date oldPublishTime = oldDTO.getPublishTime() ;
            Date newPublishTime = oldDTO.getPublishTime() ;
            this.otherLog("发送时间",DateUtil.dateToStr(oldPublishTime,"yyyy-MM-dd HH:mm:ss"),DateUtil.dateToStr(newPublishTime,"yyyy-MM-dd HH:mm:ss") , logList) ;
        }

        int oldExpireDays = oldDTO.getExpireDays() ;
        int newExpireDays = newDTO.getExpireDays() ;
        this.otherLog("失效时间",oldExpireDays+"天后",newExpireDays+"天后" , logList) ;

        return logList.stream().filter(o->StringUtils.isNotBlank(o)).collect(Collectors.joining(";"));
    }

    private static List<String> differenceList(List<String> list1, List<String> list2) {
        if (CollectionUtils.isNotEmpty(list1) && CollectionUtils.isNotEmpty(list2)) {
            Sets.SetView<String> setView = Sets.difference(Sets.newHashSet(list1), Sets.newHashSet(list2));
            return setView.stream().collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    private String otherLog(String s1, String s2, String s3 , List<String> logList) {
        if(null == s2) {
            s2 = "" ;
        }
        if(null == s3) {
            s3 = "" ;
        }
        if (!s2.equals(s3)) {
            String s =  new StringBuilder(s1).append("从【").append(s2).append("】修改为【").append(s3).append("】").toString() ;
            if(null != logList) {
                logList.add(s);
            }
            return s ;
        }
        return "";
    }

    /**
     * 删除
     * @return
     */
    @RequestMapping("del")
    @ResponseBody
    @GicLogRecord(value = "${#logValue}", category = GicLogRecordCategoryEnum.QW_MOMENT, optType = GicLogRecordOptTypeEnum.QW_MOMENT_DEL, userFunc = LogRecordUserServiceImpl.class, optPage = "企微朋友圈-朋友圈列表")
    public RestResponse<Void> del(Long planId){
        ServiceResponse<QwMomentPlanDTO> resp = this.qwMomentApiService.detail(planId) ;
        if(null == resp.getResult()) {
            GicLogRecordEvaluationContext.noWriteLog();
            return RestResponse.failure("9999","活动不存在") ;
        }
        this.qwMomentApiService.del(planId) ;
        String logContent = "删除企微朋友圈活动任务【" + resp.getResult().getTitle() + "-" + planId + "】";
        GicLogRecordEvaluationContext.putAttribute("logValue", logContent);
        return RestResponse.successResult() ;
    }

    /**
     * 终止
     * @return
     */
    @RequestMapping("stop")
    @ResponseBody
    @GicLogRecord(value = "${#logValue}", category = GicLogRecordCategoryEnum.QW_MOMENT, optType = GicLogRecordOptTypeEnum.QW_MOMENT_STOP, userFunc = LogRecordUserServiceImpl.class, optPage = "企微朋友圈-朋友圈列表")
    public RestResponse<Void> stop(Long planId){
        ServiceResponse<QwMomentPlanDTO> resp = this.qwMomentApiService.detail(planId) ;
        if(null == resp.getResult()) {
            GicLogRecordEvaluationContext.noWriteLog();
            return RestResponse.failure("9999","活动不存在") ;
        }
        this.qwMomentApiService.stop(planId) ;
        String logContent = "终止企微朋友圈活动【" + resp.getResult().getTitle() + "-" + planId + "】";
        GicLogRecordEvaluationContext.putAttribute("logValue", logContent);
        return RestResponse.successResult() ;
    }

    /**
     * 复制
     * @return
     */
    @RequestMapping("copy")
    @ResponseBody
    public RestResponse<HaobanQwMomentPlanVO> copy(Long planId){
        RestResponse<HaobanQwMomentPlanVO> detailResponse = this.detail(planId) ;
        // 删除ID
        HaobanQwMomentPlanVO vo = detailResponse.getResult() ;
        vo.setPlanId(null);
        vo.setPublishTime(null);
        vo.setPublishType(1);
        vo.setExpireDays(null);
        return RestResponse.successResult(vo) ;
    }


    /**
     * 活动列表
     */
    @RequestMapping("plan-list")
    public RestResponse<Page<HaobanQwMomentPlanVO>> planList(@RequestBody PlanListQO qo) {
        QwMomentPlanQDTO qdto =  EntityUtil.changeEntityByJSON(QwMomentPlanQDTO.class,qo) ;
        if(null != qdto.getEndTime()) {
            qdto.setEndTime(DateUtil.getEndTimeOfDay(qdto.getEndTime()));
        }
        qdto.setCreatorIdList(CreatorUtils.getCreatorIdList(qo.getShowSelfFlag()));
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        qdto.setEnterpriseId(loginUser.getEnterpriseId());
        qdto.setWxEnterpriseId(loginUser.getWxEnterpriseId());
        ServiceResponse<Page<QwMomentPlanDTO>> resp = this.qwMomentApiService.planList(qdto) ;
        Page<HaobanQwMomentPlanVO> retPage = PageHelperUtils.changePageToCurrentPage(resp.getResult(), HaobanQwMomentPlanVO.class);
        List<HaobanQwMomentPlanVO> voList= retPage.getResult() ;
        if(CollectionUtils.isNotEmpty(voList)) {
            for (HaobanQwMomentPlanVO vo : voList) {
                if(null != vo.getExecRate() && vo.getExecRate() > 0) {
                    vo.setExecRateFloat(BigDecimal.valueOf(vo.getExecRate()).divide(BigDecimal.valueOf(100),2,2).doubleValue());
                }
                if(vo.getStatusFlag()==1) {
                    if (vo.getBeginDate().getTime() > System.currentTimeMillis()) {
                        vo.setStatusFlag(0);
                    }else if(vo.getEndDate().getTime() < System.currentTimeMillis()) {
                        vo.setStatusFlag(3);
                    }
                }
            }
            retPage.setResult(voList);
        }
        return RestResponse.successResult(retPage);
    }

    /**
     * 活动详情
     */
    @RequestMapping("detail")
    public RestResponse<HaobanQwMomentPlanVO> detail(Long planId) {
        ServiceResponse<QwMomentPlanDTO> detaiResp = this.qwMomentApiService.detail(planId) ;
        if (!detaiResp.isSuccess()) {
            return RestResponse.failure("1", "活动不存在");
        }
        // 查询素材列表
        HaobanQwMomentPlanVO vo = EntityUtil.changeEntityByJSON(HaobanQwMomentPlanVO.class, detaiResp.getResult());
        // 部分导购
        if(vo.getPlanClerkType()==1) {
            List<QwMomentPlanAttendDTO> clerkList = detaiResp.getResult().getClerkList() ;
            if(CollectionUtils.isNotEmpty(clerkList)) {
                List<ClerkVO> list = clerkList.stream().map(o->{
                    ClerkVO clerkVO = new ClerkVO();
                    clerkVO.setClerkId(o.getClerkId());
                    clerkVO.setClerkCode(o.getClerkCode());
                    clerkVO.setClerkName(o.getClerkName());
                    return clerkVO ;
                }).collect(Collectors.toList()) ;
                vo.setClerkVOList(list);
            }
        }
        if(null != detaiResp.getResult().getExecRate()) {
            vo.setExecRateFloat(BigDecimal.valueOf(detaiResp.getResult().getExecRate()).divide(BigDecimal.valueOf(100),2,2).doubleValue());
        }
        if(vo.getStatusFlag()==1) {
            if (vo.getBeginDate().getTime() > System.currentTimeMillis()) {
                vo.setStatusFlag(0);
            }else if(vo.getEndDate().getTime() < System.currentTimeMillis()) {
                vo.setStatusFlag(3);
            }
        }
        return RestResponse.successResult(vo);
    }


    /**
     * 执行导购列表
     */
    @RequestMapping("clerk-list")
    public RestResponse<Page<QwMomentPlanAttendVO>> clerkList(@RequestBody PlanClerkListQO qo) {
        List<String> storeIdList = this.getGicStoreId(qo.getStoreGroupIds(), AuthWebRequestUtil.getLoginUser().getEnterpriseId()) ;
        if(CollectionUtils.isNotEmpty(storeIdList) && storeIdList.size() ==1 && storeIdList.contains("-1")) {
            return RestResponse.successResult(new Page<>());
        }
        PlanClerkListQDTO qdto = EntityUtil.changeEntityByJSON(PlanClerkListQDTO.class,qo) ;
        qdto.setStoreIdList(storeIdList);
        ServiceResponse<Page<QwMomentPlanAttendDTO>> resp = this.qwMomentApiService.attendList(qdto) ;
        Page<QwMomentPlanAttendVO> retPage = PageHelperUtils.changePageToCurrentPage(resp.getResult(), QwMomentPlanAttendVO.class);
        List<QwMomentPlanAttendVO> list = retPage.getResult() ;
        if(CollectionUtils.isNotEmpty(list)) {
            for (QwMomentPlanAttendVO vo : list) {
                String storeId = vo.getStoreId() ;
                if(StringUtils.isNotBlank(storeId)) {
                    StoreDTO store = this.storeService.getStore(storeId);
                    vo.setStoreId(storeId);
                    vo.setStoreName(store.getStoreName());
                    vo.setStoreCode(store.getStoreCode());
                    vo.setStoreGroupId(store.getStoreGroupId());
                    vo.setStoreGroupName(store.getStoreGroupName());
                }
            }
        }
        return RestResponse.successResult(retPage);
    }

    /**
     * 统计
     */
    @RequestMapping("data-list")
    public RestResponse<Page<QwMomentPlanDataVO>> dataList(@RequestBody PlanDataListQO qo) {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        List<String> storeIdList = this.getGicStoreId(qo.getStoreGroupIds(), loginUser.getEnterpriseId()) ;
        if(CollectionUtils.isNotEmpty(storeIdList) && storeIdList.size() ==1 && storeIdList.contains("-1")) {
            return RestResponse.successResult(new Page<>());
        }
        PlanDataListQDTO qdto = EntityUtil.changeEntityByJSON(PlanDataListQDTO.class,qo) ;
        qdto.setStoreIdList(storeIdList);
        ServiceResponse<Page<QwMomentPlanDataDTO>> resp = this.qwMomentApiService.dataList(qdto) ;
        Page<QwMomentPlanDataVO> retPage = PageHelperUtils.changePageToCurrentPage(resp.getResult(), QwMomentPlanDataVO.class);
        List<QwMomentPlanDataVO> list = retPage.getResult() ;
        if(CollectionUtils.isNotEmpty(list)) {
            for (QwMomentPlanDataVO vo : list) {
                String storeId = vo.getStoreId() ;
                if(StringUtils.isNotBlank(storeId)) {
                    StoreDTO store = this.storeService.getStore(storeId);
                    vo.setStoreId(storeId);
                    vo.setStoreName(store.getStoreName());
                    vo.setStoreCode(store.getStoreCode());
                    vo.setStoreGroupId(store.getStoreGroupId());
                    vo.setStoreGroupName(store.getStoreGroupName());
                }
            }
            List<String> memberIdList = list.stream().map(o->o.getMemberId()).collect(Collectors.toList());
            Map<String,MemberDataDTO> map = this.getMemberMap(loginUser.getEnterpriseId(),memberIdList) ;
            for (QwMomentPlanDataVO vo : list) {
                String memberId = vo.getMemberId() ;
                if(null == map.get(memberId)) {
                    vo.setMemberScene(2);
                }else {
                    MemberDataDTO data = map.get(memberId) ;
                    vo.setMemberName(data.getName());
                    vo.setMemberNick(data.getNickName());
                    vo.setMemberCard(data.getCardNo());
                    vo.setMemberImage(data.getPhotoUrl());
                    vo.setMemberPhone(data.getPhoneNumber());
                    vo.setMemberScene(3);
                }
            }
        }
        return RestResponse.successResult(retPage);
    }


    /**
     * 统计-导出
     */
    @RequestMapping("data-list-excel")
    public RestResponse<String> dataListExcel(@RequestBody PlanDataListQO qo) {
        ServiceResponse<QwMomentPlanDTO>  detailResp = this.qwMomentApiService.detail(qo.getPlanId()) ;
        PlanDataListQDTO qdto = EntityUtil.changeEntityByJSON(PlanDataListQDTO.class,qo) ;
        if(null != qdto.getEndTime()) {
            qdto.setEndTime(DateUtil.getEndTimeOfDay(qdto.getEndTime()));
        }
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        qdto.setWxEnterpriseId(loginUser.getWxEnterpriseId());
        qdto.setEnterpriseId(loginUser.getEnterpriseId());
        qdto.setPageNum(1);
        qdto.setPageSize(1);
        List<String> storeIdList = this.getGicStoreId(qo.getStoreGroupIds(), loginUser.getEnterpriseId()) ;
        if(CollectionUtils.isNotEmpty(storeIdList) && storeIdList.size() ==1 && storeIdList.contains("-1")) {
            return RestResponse.failure("9999", "导出数据条数为0");
        }
        qdto.setStoreIdList(storeIdList);
        ServiceResponse<Page<QwMomentPlanDataDTO>> pageResp = this.qwMomentApiService.dataList(qdto);
        final int totalCount = pageResp.getResult().getTotalCount();
        if (totalCount == 0) {
            return RestResponse.failure("9999", "导出数据条数为0");
        }
        AuthorizedUser user = new AuthorizedUser();
        user.setUserId(loginUser.getClerkId());
        user.setEnterpriseId(loginUser.getEnterpriseId());
        user.setRealName(loginUser.getClerkName());
        String fileName = "企微朋友圈-"+detailResp.getResult().getTitle()+"-点赞数据";
        if(qo.getType()==2) {
            fileName = "企微朋友圈-"+detailResp.getResult().getTitle()+"-评论数据";
        }
        Date startDate = qo.getStartTime() ;
        Date endDate = qo.getEndTime() ;
        if (null != startDate && null != endDate) {
            fileName = fileName + "-" + DateUtil.formatString(startDate, "yyyy-MM-dd") + "到" + DateUtil.formatString(endDate, "yyyy-MM-dd");
        }
        // 1.组装数据查询条件
        DownloadTask task = new DownloadTask();
        task.setTaskTypeEnum(TaskTypeEnum.QYWX_MOMENT);
        task.setUser(user);
        task.setDataType(1);
        task.setTotalCount(totalCount);
        task.setFileName(fileName);
        task.setChannelName(TaskTypeEnum.QYWX_MOMENT.getName());
        task.setBucketName(BucketNameEnum.REPORT_50000.getName());
        task.setSearchDataParams(JSON.toJSONStringWithDateFormat(qdto, DatePattern.NORM_DATETIME_PATTERN));
        task.setHandler(momentDataExcelHandler);
        JSONResponse jsonResponse = DownloadTaskUtil.createDownloadTask(task);
        final String reportId;
        if (jsonResponse.isSuccess()) {
            reportId = (String) jsonResponse.getResult();
        } else {
            return RestResponse.failure("9999", jsonResponse.getErrorMessage());
        }
        return RestResponse.successResult(reportId);
    }


    /**
     * 活动列表-导出
     * @param qo
     * @return
     */
    @RequestMapping("plan-list-excel")
    public RestResponse<String> planListExcel(@RequestBody PlanListQO qo) {
        QwMomentPlanQDTO qdto = EntityUtil.changeEntityByJSON(QwMomentPlanQDTO.class,qo) ;
        if(null != qdto.getEndTime()) {
            qdto.setEndTime(DateUtil.getEndTimeOfDay(qdto.getEndTime()));
        }
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        qdto.setWxEnterpriseId(loginUser.getWxEnterpriseId());
        qdto.setEnterpriseId(loginUser.getEnterpriseId());
        qdto.setPageNum(1);
        qdto.setPageSize(1);
        ServiceResponse<Page<QwMomentPlanDTO>> pageResp = this.qwMomentApiService.planList(qdto);
        final int totalCount = pageResp.getResult().getTotalCount();
        if (totalCount == 0) {
            return RestResponse.failure("9999", "导出数据条数为0");
        }
        AuthorizedUser user = new AuthorizedUser();
        user.setUserId(loginUser.getClerkId());
        user.setEnterpriseId(loginUser.getEnterpriseId());
        user.setRealName(loginUser.getClerkName());
        String fileName = "企微朋友圈-活动列表";
        Date startDate = qo.getStartTime() ;
        Date endDate = qo.getEndTime() ;
        if (null != startDate && null != endDate) {
            fileName = fileName + "-" + DateUtil.formatString(startDate, "yyyy-MM-dd") + "到" + DateUtil.formatString(endDate, "yyyy-MM-dd");
        }
        // 1.组装数据查询条件
        DownloadTask task = new DownloadTask();
        task.setTaskTypeEnum(TaskTypeEnum.QYWX_MOMENT);
        task.setUser(user);
        task.setDataType(1);
        task.setTotalCount(totalCount);
        task.setFileName(fileName);
        task.setChannelName(TaskTypeEnum.QYWX_MOMENT.getName());
        task.setBucketName(BucketNameEnum.REPORT_50000.getName());
        task.setSearchDataParams(JSON.toJSONStringWithDateFormat(qdto, DatePattern.NORM_DATETIME_PATTERN));
        task.setHandler(momentPlanExcelHandler);
        JSONResponse jsonResponse = DownloadTaskUtil.createDownloadTask(task);
        final String reportId;
        if (jsonResponse.isSuccess()) {
            reportId = (String) jsonResponse.getResult();
        } else {
            return RestResponse.failure("9999", jsonResponse.getErrorMessage());
        }
        return RestResponse.successResult(reportId);
    }


    /**
     * 执行导购列表-导出
     * @param qo
     * @return
     */
    @RequestMapping("clerk-list-excel")
    public RestResponse<String> clerkListExcel(@RequestBody PlanClerkListQO qo) {
        ServiceResponse<QwMomentPlanDTO>  detailResp = this.qwMomentApiService.detail(qo.getPlanId()) ;
        PlanClerkListQDTO qdto = EntityUtil.changeEntityByJSON(PlanClerkListQDTO.class,qo) ;
        if(null != qdto.getEndTime()) {
            qdto.setEndTime(DateUtil.getEndTimeOfDay(qdto.getEndTime()));
        }
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        qdto.setWxEnterpriseId(loginUser.getWxEnterpriseId());
        qdto.setEnterpriseId(loginUser.getEnterpriseId());
        qdto.setPageNum(1);
        qdto.setPageSize(1);
        List<String> storeIdList = this.getGicStoreId(qo.getStoreGroupIds(), AuthWebRequestUtil.getLoginUser().getEnterpriseId()) ;
        if(CollectionUtils.isNotEmpty(storeIdList) && storeIdList.size() ==1 && storeIdList.contains("-1")) {
            return RestResponse.failure("9999", "导出数据条数为0");
        }
        qdto.setStoreIdList(storeIdList);
        ServiceResponse<Page<QwMomentPlanAttendDTO>> pageResp = this.qwMomentApiService.attendList(qdto);
        final int totalCount = pageResp.getResult().getTotalCount();
        if (totalCount == 0) {
            return RestResponse.failure("9999", "导出数据条数为0");
        }
        AuthorizedUser user = new AuthorizedUser();
        user.setUserId(loginUser.getClerkId());
        user.setEnterpriseId(loginUser.getEnterpriseId());
        user.setRealName(loginUser.getClerkName());
        String fileName = "企微朋友圈-"+detailResp.getResult().getTitle()+"-执行情况";
        Date startDate = qo.getStartTime() ;
        Date endDate = qo.getEndTime() ;
        if (null != startDate && null != endDate) {
            fileName = fileName + "-" + DateUtil.formatString(startDate, "yyyy-MM-dd") + "到" + DateUtil.formatString(endDate, "yyyy-MM-dd");
        }
        // 1.组装数据查询条件
        DownloadTask task = new DownloadTask();
        task.setTaskTypeEnum(TaskTypeEnum.QYWX_MOMENT);
        task.setUser(user);
        task.setDataType(1);
        task.setTotalCount(totalCount);
        task.setFileName(fileName);
        task.setChannelName(TaskTypeEnum.QYWX_MOMENT.getName());
        task.setBucketName(BucketNameEnum.REPORT_50000.getName());
        task.setSearchDataParams(JSON.toJSONStringWithDateFormat(qdto, DatePattern.NORM_DATETIME_PATTERN));
        task.setHandler(momentClerkExcelHandler);
        JSONResponse jsonResponse = DownloadTaskUtil.createDownloadTask(task);
        final String reportId;
        if (jsonResponse.isSuccess()) {
            reportId = (String) jsonResponse.getResult();
        } else {
            return RestResponse.failure("9999", jsonResponse.getErrorMessage());
        }
        return RestResponse.successResult(reportId);
    }


    public Map<String,MemberDataDTO> getMemberMap(String enterpriseId, List<String> memberIdList) {
        String returnFields = "memberId,mainStoreId,mainClerkId,openStoreId,openClerkId,name,nickName,phoneNumber,photoUrl,cardNo";
        List<JSONObject> esList = this.queryDataBatch(enterpriseId, memberIdList, returnFields);
        if(CollectionUtils.isEmpty(esList)) {
            logger.info("会员查询无");
            return new HashMap<>() ;
        }
        logger.info("会员信息={}",JSONObject.toJSONString(esList));
        List<MemberDataDTO> list = JSONArray.parseArray(JSONArray.toJSONString(esList),MemberDataDTO.class);
        Map<String,MemberDataDTO> map = list.stream().collect(Collectors.toMap(o->o.getMemberId(),o->o,(k1,k2)->k1));
        if(null == map) {
            map = new HashMap<>() ;
        }
        return map;
    }

    public List<JSONObject> queryDataBatch(String enterpriseId, List<String> memberIdList, String returnFields) {
        DynamicSearchDTO search = new DynamicSearchDTO();
        search.setEnterpriseId(enterpriseId);
        search.setColumnCategoryCode("member");
        String memberIds = String.join(" ", memberIdList);
        JSONObject searchObj = new JSONObject();
        searchObj = NewNodeAddUtil.addNewNodeForAnd("memberId", OperateEnum.OPERATE_CONTAIN.getValue(), memberIds,
                searchObj);
        search.setSearchJson(searchObj);
        search.setReturnFileds(returnFields);
        search.setSortJson(NewNodeAddUtil.createSortNode("memberId", NewNodeAddUtil.SORT_RULE_ASC));
        search.setBegin(0);
        search.setRecordNumber(memberIdList.size());
        ESResponseQueryBatch response = this.esDataDynamicOperationApiService.queryDataBatch(search, Boolean.FALSE,
                null);
        return response.getRes();
    }

    public List<String> getGicStoreId(String groupIds , String enterpriseId) {
        if(StringUtils.isBlank(groupIds)) {
            logger.info("groupid is null");
            return null;
        }
        List<String> groupIdList = Arrays.asList(groupIds.split(",")).stream().filter(StringUtils::isNotBlank).collect(Collectors.toList()) ;
        if(CollectionUtils.isEmpty(groupIdList)) {
            logger.info("groupid is null");
            return null;
        }
        List<String> allGroupIds = storeGroupService.getStoreGroupIdsByParentGroupId(enterpriseId, groupIdList);
        Page pageSearch = new Page<>();
        pageSearch.setCurrentPage(-1);
        StoreSearchDTO storeSearch = new StoreSearchDTO();
        storeSearch.setStoreGroupIdList(allGroupIds);
        storeSearch.setEnterpriseId(enterpriseId);
        storeSearch.setStatus("2");
        Page<com.gic.enterprise.api.dto.StoreDTO> resultPage = this.storeService.storeListPage(pageSearch, storeSearch);
        List<com.gic.enterprise.api.dto.StoreDTO> storeList = resultPage.getResult();
        List<String> storeIdList = storeList.stream().map(StoreDTO::getStoreId).distinct().collect(Collectors.toList());
        if(CollectionUtils.isEmpty(storeIdList)) {
            storeIdList = new ArrayList<>();
            storeIdList.add("-1") ;
        }
        logger.info("storeIdList={}",storeIdList);
        return storeIdList;
    }
}
