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

import cn.hutool.core.date.DatePattern;
import com.alibaba.fastjson.JSON;
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.clerk.api.dto.ClerkDTO;
import com.gic.clerk.api.service.ClerkService;
import com.gic.commons.util.DateUtil;
import com.gic.commons.util.EntityUtil;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.enterprise.api.dto.StoreDTO;
import com.gic.enterprise.api.enums.PlatformChannelEnum;
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.QwMomentPlanDTO;
import com.gic.haoban.manage.api.service.moment.QwMomentApiService;
import com.gic.haoban.manage.web.qo.moment.MomentDataQO;
import com.gic.haoban.manage.web.vo.moment.MomentDataClickVO;
import com.gic.haoban.manage.web.vo.moment.MomentDataMemberVO;
import com.gic.haoban.manage.web.vo.moment.MomentDataOrderVO;
import com.gic.haoban.manage.web.vo.moment.MomentDataVO;
import com.gic.member.api.dto.es.MemberDataDTO;
import com.gic.qcloud.BucketNameEnum;
import com.gic.web.common.download.DownloadTask;
import com.gic.web.common.download.DownloadTaskUtil;
import com.gic.web.common.download.constants.TaskTypeEnum;
import com.gic.web.common.utils.DataApiUtils;
import com.gic.web.common.utils.SessionContextUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.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.RestController;

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

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

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

    @Autowired
    private QwMomentController qwMomentController ;
    @Autowired
    private StoreService storeService ;
    @Autowired
    private ClerkService clerkService ;
    @Autowired
    private QwMomentApiService qwMomentApiService ;
    @Autowired
    private MomentDataClickExcelHandler momentDataClickExcelHandler ;
    @Autowired
    private MomentDataOrderExcelHandler momentDataOrderExcelHandler ;
    @Autowired
    private MomentDataMemberExcelHandler momentDataMemberExcelHandler ;

    /**
     * 概览
     */
    @RequestMapping("data_qw_moment_plan_overview")
    public RestResponse<MomentDataVO> data(@RequestBody MomentDataQO qo) {
        JSONObject json = this.paramsJson(qo) ;
        Map<String, Object> res = DataApiUtils.http(json.toJSONString(), "data_qw_moment_plan_overview");
        JSONObject data = DataApiUtils.getPageOne(res);
        MomentDataVO vo = new MomentDataVO();
        if(null != data) {
            vo.setMatlClickCnt(data.getInteger("matlClickCnt"));
            vo.setMatlClickMbrNum(data.getInteger("matlClickMbrNum"));
            vo.setMatlConvsAmt(data.getDoubleValue("matlConvsAmt"));
            vo.setMatlConvsMbrNum(data.getInteger("matlConvsMbrNum"));
        }
        return RestResponse.successResult(vo);
    }

    /**
     * 转化会员
     */
    @RequestMapping("data_qw_moment_mbr_detail")
    public RestResponse<Page<MomentDataMemberVO>> memberData(@RequestBody MomentDataQO qo) {
        JSONObject json = this.paramsJson(qo) ;
        Map<String, Object> res = DataApiUtils.http(json.toJSONString(), "data_qw_moment_mbr_detail");
        Page page =  DataApiUtils.getPageData(res);
        Page<MomentDataMemberVO> retPage = EntityUtil.changeEntityByJSON(Page.class, page);
        if (CollectionUtils.isEmpty(page.getResult())) {
            return RestResponse.successResult(retPage);
        }
        List<MomentDataMemberVO> voList = EntityUtil.changeEntityListByJSON(MomentDataMemberVO.class, page.getResult());
        if(CollectionUtils.isNotEmpty(voList)) {
            List<String> memberIdList = voList.stream().map(o->o.getMbrId()).collect(Collectors.toList());
            Map<String, MemberDataDTO> map = this.qwMomentController.getMemberMap(AuthWebRequestUtil.getLoginUser().getEnterpriseId(),memberIdList) ;
            for (MomentDataMemberVO vo : voList) {
                String memberId = vo.getMbrId();
                vo.setMemberId(memberId);
                if(null == map.get(memberId)) {
                    vo.setMemberScene(2);
                }else {
                    MemberDataDTO data = map.get(memberId) ;
                    vo.setMemberName(data.getName());
                    vo.setMemberNick(data.getNickName());
                    vo.setMemberCardNo(data.getCardNo());
                    vo.setMemberPhone(data.getPhoneNumber());
                    vo.setMemberImage(data.getDefineHeadImg());
                    vo.setClerkId(data.getMainClerkId());
                    vo.setStoreId(data.getMainStoreId());
                    vo.setMemberScene(3);
                }
            }
            Set<String> storeSet = voList.stream().filter(o->StringUtils.isNotBlank(o.getStoreId()) && !"-1".equals(o.getStoreId())).map(o->o.getStoreId()).collect(Collectors.toSet()) ;
            Set<String> clerkSet = voList.stream().filter(o->StringUtils.isNotBlank(o.getClerkId()) && !"-1".equals(o.getClerkId())).map(o->o.getClerkId()).collect(Collectors.toSet());
            Map<String,StoreDTO> storeMap = this.storeMap(storeSet) ;
            Map<String,ClerkDTO> clerkMap = this.clerkMap(clerkSet) ;
            for (MomentDataMemberVO vo : voList) {
                if(null != storeMap.get(vo.getStoreId())) {
                    vo.setStoreCode(storeMap.get(vo.getStoreId()).getStoreCode());
                    vo.setStoreName(storeMap.get(vo.getStoreId()).getStoreName());
                }
                if(null != clerkMap.get(vo.getClerkId())) {
                    vo.setClerkCode(clerkMap.get(vo.getClerkId()).getClerkCode());
                    vo.setClerkName(clerkMap.get(vo.getClerkId()).getClerkName());
                }
            }
        }
        retPage.setResult(voList);
        return RestResponse.successResult(retPage);
    }

    /**
     * 转化会员导出
     */
    @RequestMapping("data_qw_moment_mbr_detail_excel")
    public RestResponse<String> memberDataExcel(@RequestBody MomentDataQO qo) {
        JSONObject json = this.paramsJson(qo) ;
        json.put("pageSize",1) ;
        Map<String, Object> res = DataApiUtils.http(json.toJSONString(), "data_qw_moment_mbr_detail");
        Page page =  DataApiUtils.getPageData(res);
        if (CollectionUtils.isEmpty(page.getResult())) {
            return RestResponse.failure("9999", "导出数据条数为0");
        }
        AuthorizedUser loginUser = SessionContextUtils.getLoginUser() ;
        DownloadTask task = new DownloadTask();
        task.setTaskTypeEnum(TaskTypeEnum.QYWX_MOMENT);
        task.setUser(loginUser);
        task.setDataType(qo.getDataType());
        task.setTotalCount(page.getTotalCount());
        ServiceResponse<QwMomentPlanDTO>  resp = this.qwMomentApiService.detail(qo.getPlanId()) ;
        String date = DateUtil.dateToStr(new Date(),"yyyy-MM-dd HH:mm:ss") ;
        String fileName = "企微朋友圈-"+resp.getResult().getTitle()+"-客户明细-转化明细"+date ;
        task.setFileName(fileName);
        task.setChannelName(TaskTypeEnum.QYWX_MOMENT.getName());
        task.setBucketName(BucketNameEnum.REPORT_50000.getName());
        json.put("pageSize",1000) ;
        task.setSearchDataParams(json.toJSONString());
        task.setHandler(momentDataMemberExcelHandler);
        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);
    }

    /**
     * 转化订单
     */
    @RequestMapping("data_qw_moment_order_detail")
    public RestResponse<Page<MomentDataOrderVO>> orderData(@RequestBody MomentDataQO qo) {
        JSONObject json = this.paramsJson(qo) ;
        Map<String, Object> res = DataApiUtils.http(json.toJSONString(), "data_qw_moment_order_detail");
        Page page =  DataApiUtils.getPageData(res);
        Page<MomentDataOrderVO> retPage = EntityUtil.changeEntityByJSON(Page.class, page);
        if (CollectionUtils.isEmpty(page.getResult())) {
            return RestResponse.successResult(retPage);
        }
        List<MomentDataOrderVO> voList = EntityUtil.changeEntityListByJSON(MomentDataOrderVO.class, page.getResult());
        if(CollectionUtils.isNotEmpty(voList)) {
            List<String> memberIdList = voList.stream().map(o -> o.getMbrId()).collect(Collectors.toList());
            Map<String, MemberDataDTO> map = this.qwMomentController.getMemberMap(AuthWebRequestUtil.getLoginUser().getEnterpriseId(), memberIdList);
            for (MomentDataOrderVO vo : voList) {
                String memberId = vo.getMbrId();
                vo.setMemberId(memberId);
                if (null == map.get(memberId)) {
                    vo.setMemberScene(2);
                } else {
                    MemberDataDTO data = map.get(memberId);
                    vo.setMemberName(data.getName());
                    vo.setMemberNick(data.getNickName());
                    vo.setMemberCardNo(data.getCardNo());
                    vo.setMemberPhone(data.getPhoneNumber());
                    vo.setMemberImage(data.getDefineHeadImg());
                    vo.setMemberScene(3);
                }
                PlatformChannelEnum channel = PlatformChannelEnum.getEnumByChannelCode(vo.getChannelCode()) ;
                if(null != channel) {
                    vo.setChannelName(channel.getChannelNameOrder());
                }
            }
            Set<String> storeSet = voList.stream().filter(o -> StringUtils.isNotBlank(o.getOrderStoreId()) && !"-1".equals(o.getOrderStoreId())).map(o -> o.getOrderStoreId()).collect(Collectors.toSet());
            Map<String, StoreDTO> storeMap = this.storeMap(storeSet);
            for (MomentDataOrderVO vo : voList) {
                if (null != storeMap.get(vo.getOrderStoreId())) {
                    vo.setOrderStoreCode(storeMap.get(vo.getOrderStoreId()).getStoreCode());
                    vo.setOrderStoreName(storeMap.get(vo.getOrderStoreId()).getStoreName());
                }
            }
        }
        retPage.setResult(voList);
        return RestResponse.successResult(retPage);
    }

    /**
     * 转化订单导出
     */
    @RequestMapping("data_qw_moment_order_detail_excel")
    public RestResponse<String> orderDataExcel(@RequestBody MomentDataQO qo) {
        JSONObject json = this.paramsJson(qo) ;
        json.put("pageSize",1) ;
        Map<String, Object> res = DataApiUtils.http(json.toJSONString(), "data_qw_moment_order_detail");
        Page page =  DataApiUtils.getPageData(res);
        if (CollectionUtils.isEmpty(page.getResult())) {
            return RestResponse.failure("9999", "导出数据条数为0");
        }
        AuthorizedUser loginUser = SessionContextUtils.getLoginUser() ;
        DownloadTask task = new DownloadTask();
        task.setTaskTypeEnum(TaskTypeEnum.QYWX_MOMENT);
        task.setUser(loginUser);
        task.setDataType(qo.getDataType());
        task.setTotalCount(page.getTotalCount());
        ServiceResponse<QwMomentPlanDTO>  resp = this.qwMomentApiService.detail(qo.getPlanId()) ;
        String date = DateUtil.dateToStr(new Date(),"yyyy-MM-dd HH:mm:ss") ;
        String fileName = "企微朋友圈-"+resp.getResult().getTitle()+"-客户明细-转化订单"+date ;
        task.setFileName(fileName);
        task.setChannelName(TaskTypeEnum.QYWX_MOMENT.getName());
        task.setBucketName(BucketNameEnum.REPORT_50000.getName());
        json.put("pageSize",1000) ;
        task.setSearchDataParams(json.toJSONString());
        task.setHandler(momentDataOrderExcelHandler);
        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);
    }

    /**
     * 点击数据
     */
    @RequestMapping("data_qw_moment_mbr_click_detail")
    public RestResponse<Page<MomentDataClickVO>> clerkData(@RequestBody MomentDataQO qo) {
        JSONObject json = this.paramsJson(qo) ;
        Map<String, Object> res = DataApiUtils.http(json.toJSONString(), "data_qw_moment_mbr_click_detail");
        Page page =  DataApiUtils.getPageData(res);
        Page<MomentDataClickVO> retPage = EntityUtil.changeEntityByJSON(Page.class, page);
        if (CollectionUtils.isEmpty(page.getResult())) {
            return RestResponse.successResult(retPage);
        }
        List<MomentDataClickVO> voList = EntityUtil.changeEntityListByJSON(MomentDataClickVO.class, page.getResult());
        if(CollectionUtils.isNotEmpty(voList)) {
            List<String> memberIdList = voList.stream().map(o->o.getMbrId()).collect(Collectors.toList());
            Map<String, MemberDataDTO> map = this.qwMomentController.getMemberMap(AuthWebRequestUtil.getLoginUser().getEnterpriseId(),memberIdList) ;
            for (MomentDataClickVO vo : voList) {
                String memberId = vo.getMbrId();
                vo.setMemberId(memberId);
                if(null == map.get(memberId)) {
                    vo.setMemberScene(2);
                }else {
                    MemberDataDTO data = map.get(memberId) ;
                    vo.setMemberName(data.getName());
                    vo.setMemberNick(data.getNickName());
                    vo.setMemberCardNo(data.getCardNo());
                    vo.setMemberPhone(data.getPhoneNumber());
                    vo.setMemberImage(data.getDefineHeadImg());
                    vo.setClerkId(data.getMainClerkId());
                    vo.setStoreId(data.getMainStoreId());
                    vo.setMemberScene(3);
                }
            }
            Set<String> storeSet = voList.stream().filter(o->StringUtils.isNotBlank(o.getStoreId()) && !"-1".equals(o.getStoreId())).map(o->o.getStoreId()).collect(Collectors.toSet()) ;
            Set<String> clerkSet = voList.stream().filter(o->StringUtils.isNotBlank(o.getClerkId()) && !"-1".equals(o.getClerkId())).map(o->o.getClerkId()).collect(Collectors.toSet());
            Map<String,StoreDTO> storeMap = this.storeMap(storeSet) ;
            Map<String,ClerkDTO> clerkMap = this.clerkMap(clerkSet) ;
            for (MomentDataClickVO vo : voList) {
                if(null != storeMap.get(vo.getStoreId())) {
                    vo.setStoreCode(storeMap.get(vo.getStoreId()).getStoreCode());
                    vo.setStoreName(storeMap.get(vo.getStoreId()).getStoreName());
                }
                if(null != clerkMap.get(vo.getClerkId())) {
                    vo.setClerkCode(clerkMap.get(vo.getClerkId()).getClerkCode());
                    vo.setClerkName(clerkMap.get(vo.getClerkId()).getClerkName());
                }
            }
        }
        retPage.setResult(voList);
        return RestResponse.successResult(retPage);
    }

    /**
     * 点击导出
     */
    @RequestMapping("data_qw_moment_mbr_click_detail_excel")
    public RestResponse<String> clerkDataExcel(@RequestBody MomentDataQO qo) {
        JSONObject json = this.paramsJson(qo) ;
        json.put("pageSize",1) ;
        Map<String, Object> res = DataApiUtils.http(json.toJSONString(), "data_qw_moment_mbr_click_detail");
        Page page =  DataApiUtils.getPageData(res);
        if (CollectionUtils.isEmpty(page.getResult())) {
            return RestResponse.failure("9999", "导出数据条数为0");
        }
        AuthorizedUser loginUser = SessionContextUtils.getLoginUser() ;
        DownloadTask task = new DownloadTask();
        task.setTaskTypeEnum(TaskTypeEnum.QYWX_MOMENT);
        task.setUser(loginUser);
        task.setDataType(qo.getDataType());
        task.setTotalCount(page.getTotalCount());
        ServiceResponse<QwMomentPlanDTO>  resp = this.qwMomentApiService.detail(qo.getPlanId()) ;
        String date = DateUtil.dateToStr(new Date(),"yyyy-MM-dd HH:mm:ss") ;
        String fileName = "企微朋友圈-"+resp.getResult().getTitle()+"-客户明细-点击明细"+date ;
        task.setFileName(fileName);
        task.setChannelName(TaskTypeEnum.QYWX_MOMENT.getName());
        task.setBucketName(BucketNameEnum.REPORT_50000.getName());
        json.put("pageSize",1000) ;
        task.setSearchDataParams(json.toJSONString());
        task.setHandler(momentDataClickExcelHandler);
        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);
    }


    private JSONObject paramsJson(MomentDataQO qo) {
        WebLoginDTO user = AuthWebRequestUtil.getLoginUser();
        String enterpriseId = user.getEnterpriseId();
        JSONObject json = new JSONObject();
        json.put("planId", qo.getPlanId()) ;
        json.put("enterpriseId",enterpriseId) ;
        json.put("pageNum",qo.getPageNum()) ;
        json.put("pageSize",qo.getPageSize()) ;
        if(StringUtils.isNotBlank(qo.getMemberId())) {
            json.put("mbrId",qo.getMemberId()) ;
        }
        if(StringUtils.isNotBlank(qo.getOrderNumber())) {
            json.put("orderCode",qo.getOrderNumber()) ;
        }
        if(StringUtils.isNotBlank(qo.getOrderChannel())) {
            PlatformChannelEnum channel = PlatformChannelEnum.getEnumByOldOrderType(Integer.valueOf(qo.getOrderChannel())) ;
            if(null != channel) {
                json.put("channelCode", channel.getChannelCode());
            }
        }
        return json ;
    }


    public Map<String, StoreDTO> storeMap(Set<String> storeIdList) {
        Map<String, StoreDTO> storeMap = new HashMap<>();
        if(CollectionUtils.isEmpty(storeIdList)) {
            return storeMap ;
        }
        List<String> list = new ArrayList<>() ;
        list.addAll(storeIdList) ;
        if (CollectionUtils.isNotEmpty(storeIdList)) {
            List<StoreDTO> mainStoreList = storeService.queryStore(list);
            if (CollectionUtils.isNotEmpty(mainStoreList)) {
                storeMap = mainStoreList.stream().collect(Collectors.toMap(e -> e.getStoreId(), e -> e));
            }
        }
        return storeMap ;
    }

    public Map<String, ClerkDTO> clerkMap(Set<String> clerkIdList) {
        Map<String, ClerkDTO> clerkMap = new HashMap<>();
        if(CollectionUtils.isEmpty(clerkIdList)) {
            return clerkMap ;
        }
        List<ClerkDTO> mainClerkList = clerkService.getClerkByClerkIds(clerkIdList);
        if (CollectionUtils.isNotEmpty(mainClerkList)) {
            clerkMap = mainClerkList.stream().collect(Collectors.toMap(e -> e.getClerkId(), e -> e));
        }
        return clerkMap ;
    }
}
