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

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.gic.business.order.dto.ordermanage.ListOrderDTO;
import com.gic.business.order.qdto.ordermanage.ListOrderManageQDTO;
import com.gic.business.order.service.ordermanage.WebOrderManageApiService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.logging.log4j.LogManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.gic.api.base.commons.BasePageInfo;
import com.gic.api.base.commons.Page;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.commons.util.CollectionUtil;
import com.gic.commons.util.DateUtil;
import com.gic.commons.util.EntityUtil;
import com.gic.commons.util.StringUtil;
import com.gic.commons.web.qo.PageQo;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.ecm.api.dto.EcmPlanDTO;
import com.gic.ecm.api.dto.MemberEcmLogDTO;
import com.gic.ecm.api.service.EcmPlanService;
import com.gic.enterprise.service.CustomSettingApiService;
import com.gic.game.api.dto.GameActivityDTO;
import com.gic.game.api.service.GameService;
import com.gic.haoban.manage.web.controller.WebBaseController;
import com.gic.haoban.manage.web.vo.AiMemberLogListVO;
import com.gic.integralmall.api.dto.IntegralMallExchangeLogDTO;
import com.gic.integralmall.api.service.IntegralmallService;
import com.gic.marketing.api.dto.CoupCardShelfDTO;
import com.gic.marketing.api.dto.MemberCardLogDTO;
import com.gic.marketing.api.dto.WechatCard;
import com.gic.marketing.api.dto.member.MemberSmsLogDTO;
import com.gic.marketing.api.dto.member.MemberWechatLogDTO;
import com.gic.marketing.api.service.CardExportService;
import com.gic.marketing.api.service.CouponCardService;
import com.gic.marketing.api.service.SmsService;
import com.gic.marketing.api.service.WechatMarketingService;
import com.gic.marketing.pro.api.dto.ai.AiMemberLogListDTO;
import com.gic.marketing.pro.api.dto.game.GameDTO;
import com.gic.marketing.pro.api.service.ai.AiMemberLogApiService;
import com.gic.marketing.pro.api.service.game.GameApiService;
import com.gic.member.api.dto.AchievementSystemDTO;
import com.gic.member.api.dto.MemberDTO;
import com.gic.member.api.service.AchievementService;
import com.google.common.collect.Lists;

/**
 * 
* @ClassName: MemberMarketingController
* @Description: 客户营销记录
* @author xugh
* @date 2022年10月28日 上午9:57:23
*
 */
@RestController
public class MemberMarketingController extends WebBaseController {

    private static final org.apache.logging.log4j.Logger logger = LogManager.getLogger(MemberMarketingController.class);

    @Autowired
    private EcmPlanService ecmPlanService;
    @Autowired
    private CardExportService cardExportService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private WechatMarketingService wechatMarketingService;
    @Autowired
    private AiMemberLogApiService aiMemberLogApiService;
    @Autowired
    private CustomSettingApiService customSettingApiService;
    @Autowired
    private CouponCardService couponCardService;
    @Autowired
    private GameService gameService;
    @Autowired
    private GameApiService gameApiService;
    @Autowired
    private AchievementService achievementService;
    @Autowired
    private IntegralmallService integralMallService;
    @Autowired
    private WebOrderManageApiService webOrderManageApiService;

    // 会员积分商城订单数
    @RequestMapping("/member/integral-order-num")
    private RestResponse<Object> getIntegralOrderNum(String enterpriseId, String memberId) {
        ListOrderManageQDTO qdto = new ListOrderManageQDTO();
        qdto.setEnterpriseId(enterpriseId);
        qdto.setMemberId(memberId);
        qdto.setBusinessType(2);
        logger.info("积分商城订单查询,qdto={}", JSON.toJSONString(qdto));
        qdto.setPageNum(1);
        qdto.setPageSize(1);
        ServiceResponse<Page<ListOrderDTO>> ret = webOrderManageApiService.listOrder(qdto);
        return RestResponse.successResult(ret.getResult().getTotalCount()) ;
    }
    
    /**
     * ECM营销日志
     *
     * @param memberId      会员ID
     * @param search        搜索条件：计划名称
     * @param marketingType 营销类型 图文-teletext 文本 text 小程序-wxa 图片-image 卡券-card 短信-message 话务-teltask 企微-qywx 群发消息 qfxx 积分 integral 会员卡升级 grade
     * @param beginTime     开始时间
     * @param endTime       结束时间
     * @param currentPage   currentPage
     * @param pageSize      pageSize
     * @return Response
     */

    @RequestMapping("/member/ecm-log-page")
    @ResponseBody
    public RestResponse<Object> memberEcmLogPage(@RequestParam(defaultValue = "-1") String memberId, String search,
            String marketingType, Date beginTime, Date endTime, @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "20") int pageSize, String enterpriseId) {
        Page<MemberEcmLogDTO> page = new Page<>(currentPage, pageSize);
        // 时间默认一个月
        if (beginTime == null || endTime == null) {
            Calendar start = Calendar.getInstance();
            start.add(Calendar.MONTH, -3);
            beginTime = start.getTime();
            endTime = new Date();
        }
        beginTime = DateUtil.getStartTimeOfDay(beginTime);
        endTime = DateUtil.getEndTimeOfDay(endTime);
        page = ecmPlanService.memberEcmLogPage(enterpriseId, memberId, search, marketingType, beginTime, endTime, page);
        return RestResponse.successResult(page);
    }

    /**
     * 卡券营销日志
     *
     * @param memberId         会员ID
     * @param search           搜索条件：卡券代码
     * @param receiveCode      投放渠道
     * @param putBeginTime     投放开始时间
     * @param putEndTime       投放结束时间
     * @param receiveBeginTime 领取开始时间
     * @param receiveEndTime   领取结束时间
     * @param currentPage      currentPage
     * @param pageSize         pageSize
     * @return Response
     */

    @RequestMapping("/member/card-log-page")
    @ResponseBody
    public RestResponse<Object> memberCardLogPage(@RequestParam(defaultValue = "-1") String memberId, String search,
            String receiveCode, Date putBeginTime, Date putEndTime, Date receiveBeginTime, Date receiveEndTime,
            @RequestParam(defaultValue = "1") int currentPage, @RequestParam(defaultValue = "20") int pageSize,
            String enterpriseId) {
        Page<MemberCardLogDTO> page = new Page<>(currentPage, pageSize);
        Map<String, Object> params = new HashMap<>();
        page.setPageSize(pageSize);
        page.setCurrentPage(currentPage);

        params.put("memberId", memberId);
        params.put("enterpriseId", enterpriseId);
        params.put("receiveCode", receiveCode);
        params.put("receiveType", "CARD_RECEIVE_TYPE");
        params.put("showCardCodeFlag", "");
        params.put("search", search);
        // 时间默认一个月
        if (putBeginTime == null || putEndTime == null) {
            Calendar start = Calendar.getInstance();
            start.add(Calendar.MONTH, -3);
            putBeginTime = start.getTime();
            putEndTime = new Date();
        }
        params.put("beginTime", DateUtil.getStartTimeOfDay(putBeginTime));
        params.put("endTime", DateUtil.getEndTimeOfDay(putEndTime));

        if (receiveBeginTime != null) {
            params.put("receiveBeginTime", DateUtil.getStartTimeOfDay(receiveBeginTime));
        }
        if (receiveEndTime != null) {
            params.put("receiveEndTime", DateUtil.getEndTimeOfDay(receiveEndTime));
        }
        page.setParams(params);
        page = cardExportService.getCardLogs(page);
        cardReceiveTypeName(enterpriseId, page);
        return RestResponse.successResult(page);
    }

    /**
     * 短信营销日志
     *
     * @param memberId    会员ID
     * @param smsType     模板类型：0-普通短信 1-营销短信
     * @param beginTime   开始时间
     * @param endTime     结束时间
     * @param currentPage currentPage
     * @param pageSize    pageSize
     * @return Response
     */

    @RequestMapping("/member/sms-log-page")
    @ResponseBody
    public RestResponse<Object> memberSmsLogPage(@RequestParam(defaultValue = "-1") String memberId, Integer smsType,
            Date beginTime, Date endTime, @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "20") int pageSize, @RequestParam(defaultValue = "-1") int source,
            String enterpriseId) {
        // 时间默认一个月
        if (beginTime == null || endTime == null) {
            Calendar start = Calendar.getInstance();
            start.add(Calendar.MONTH, -3);
            beginTime = start.getTime();
            endTime = new Date();
        }
        beginTime = DateUtil.getStartTimeOfDay(beginTime);
        endTime = DateUtil.getEndTimeOfDay(endTime);
        Page<MemberSmsLogDTO> page = new Page<>(currentPage, pageSize);
        Map<String, Object> params = new HashMap<>();
        if (-1 != source) {
            params.put("source", source);
        }
        page.setParams(params);
        page = smsService.memberSmsLogPage(enterpriseId, memberId, smsType, beginTime, endTime, page);
        return RestResponse.successResult(page);
    }

    /**
     * 微信营销日志
     *
     * @param memberId    会员ID
     * @param contentType 图文类型（0：图文消息，1：文本消息, 2: 图片）
     * @param beginTime   开始时间
     * @param endTime     结束时间
     * @param currentPage currentPage
     * @param pageSize    pageSize
     * @return ResponseZ
     */

    @RequestMapping("/member/wechat-log-page")
    @ResponseBody
    public RestResponse<Object> memberWechatLogPage(@RequestParam(defaultValue = "-1") String memberId,
            Integer contentType, Date beginTime, Date endTime, @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "20") int pageSize, String enterpriseId) {
        Page<MemberWechatLogDTO> page = new Page<>(currentPage, pageSize);
        // 时间默认一个月
        if (beginTime == null || endTime == null) {
            Calendar start = Calendar.getInstance();
            start.add(Calendar.MONTH, -3);
            beginTime = start.getTime();
            endTime = new Date();
        }
        beginTime = DateUtil.getStartTimeOfDay(beginTime);
        endTime = DateUtil.getEndTimeOfDay(endTime);
        page = wechatMarketingService.memberWechatLogPage(enterpriseId, memberId, contentType, beginTime, endTime,
                page);
        return RestResponse.successResult(page);
    }

    @RequestMapping("/member/marketing-count")
    @ResponseBody
    public RestResponse<Map<String,Integer>> marketingCount(String memberId, String enterpriseId) {
        //1 待使用 2已使用 3已过期
        Page<WechatCard> page = new Page<WechatCard>();
        page.setPageSize(Integer.MAX_VALUE);
        page.setCurrentPage(1);
        page = this.cardExportService.getMemgerCouponByStatus(memberId, 1, page);
        int memberCouponCount = page.getTotalCount();
        // 时间默认一个月
        Calendar start = Calendar.getInstance();
        Date endTime = start.getTime();
        start.add(Calendar.MONTH, -3);
        Date beginTime = start.getTime();
        // ecm
        RestResponse<Object> ecmRep = this.memberEcmLogPage(memberId, "", null, beginTime, endTime, 1, 1, enterpriseId);
        Page<MemberEcmLogDTO> ecmPage = (Page<MemberEcmLogDTO>) ecmRep.getResult();
        // card
        RestResponse<Object> cardRep = this.memberCardLogPage(memberId, "", "", beginTime, endTime, null, null, 1, 1,
                enterpriseId);
        Page<MemberCardLogDTO> cardPage = (Page<MemberCardLogDTO>) cardRep.getResult();
        // sms
        RestResponse<Object> smsRep = this.memberSmsLogPage(memberId, null, beginTime, endTime, 1, 1, -1, enterpriseId);
        Page<MemberSmsLogDTO> smsPage = (Page<MemberSmsLogDTO>) smsRep.getResult();
        // wechat
        RestResponse<Object> wechatRep = this.memberWechatLogPage(memberId, null, beginTime, endTime, 1, 1,
                enterpriseId);
        Page<MemberWechatLogDTO> wechatPage = (Page<MemberWechatLogDTO>) wechatRep.getResult();

        // AI营销
        ServiceResponse<Page<AiMemberLogListDTO>> aiMemberLogRes = aiMemberLogApiService.pageAiMemberMarketingLog(
                memberId, null, Lists.newArrayList(0, 1, 6, 8), null, null, new BasePageInfo());
        Map<String,Integer> map = new HashMap<>();
        map.put("ecm", ecmPage.getTotalCount()) ;
        map.put("sms", smsPage.getTotalCount()) ;
        map.put("coupon", cardPage.getTotalCount()) ;
        map.put("wechat", wechatPage.getTotalCount()) ;
        map.put("ai", aiMemberLogRes.getResult().getTotalCount()) ;
        map.put("memberCouponCount", memberCouponCount) ;
        return RestResponse.successResult(map);
    }

    @RequestMapping("/member/page-ai-member-log")
    @ResponseBody
    public RestResponse<Object> pageAiMemberMarketingLog(String memberId, String planName, String aiStartTime,
            String aiEndTime, @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "20") int pageSize) {
        Calendar start = Calendar.getInstance();
        Date endTime = start.getTime();
        start.add(Calendar.MONTH, -3);
        Date beginTime = start.getTime();
        PageQo pageQo = new PageQo() ;
        pageQo.setPageNum(currentPage);
        pageQo.setPageSize(pageSize);
        ServiceResponse<Page<AiMemberLogListDTO>> res = aiMemberLogApiService.pageAiMemberMarketingLog(memberId,
                planName, Lists.newArrayList(0, 1, 6, 8), DateUtil.dateToStr(beginTime, "yyyy-MM-dd"), DateUtil.dateToStr(endTime, "yyyy-MM-dd"), pageQo.getBasePageInfo());
        if (res.isSuccess()) {
            Page<AiMemberLogListDTO> page = res.getResult();
            List<AiMemberLogListDTO> list = page.getResult();
            if (CollectionUtils.isEmpty(list)) {
                return RestResponse.successResult(res.getResult());
            }
            Map<String, Object> param = new HashMap<>();
            param.put("dict_type", "marketing_activity_scene");
            ServiceResponse<Page<JSONObject>> dictRes = customSettingApiService.page("tab_business_dict", param, 1, 20);
            List<JSONObject> dictList = dictRes.getResult().getResult();
            Map<String, String> dictCodeMapName = new HashMap<>();
            for (JSONObject jsonObject : dictList) {
                dictCodeMapName.put(jsonObject.getString("dict_code"), jsonObject.getString("dict_name"));
            }
            Page<AiMemberLogListVO> resultPage = EntityUtil.changeEntityByJSON(Page.class, page);
            List<AiMemberLogListVO> voList = new ArrayList<>();
            for (AiMemberLogListDTO dto : list) {
                AiMemberLogListVO vo = new AiMemberLogListVO();
                vo.setAiLogId(dto.getAiLogId());
                vo.setAiTime(dto.getAiTime());
                vo.setPlanName(dto.getPlanName());
                vo.setAiTemplateName(dto.getAiTemplateName());
                Integer activityScene = dto.getActivityScene();
                if (activityScene == null) {
                    vo.setActivityScene(null);
                } else {
                    vo.setActivityScene(dictCodeMapName.get(activityScene.toString()));
                }
                voList.add(vo);
            }
            resultPage.setResult(voList);
            return RestResponse.successResult(resultPage);
        }
        return RestResponse.failure("9999", res.getMessage());
    }

    /**
     * 卡券记录-领取记录-来源明细
     *
     * @param page
     */
    private void cardReceiveTypeName(String enterpriseId, Page<MemberCardLogDTO> page) {
        List<MemberCardLogDTO> list = page.getResult();
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        Map<String, List<MemberCardLogDTO>> map = CollectionUtil.group(list, "receiveCode");
        Set<String> keySet = map.keySet();
        Iterator<String> it = keySet.iterator();
        Map<String, List<EcmPlanDTO>> ecmMap = new HashMap<>();
        Map<Long, GameDTO> newGameMap = new HashMap<>();
        Map<String, List<GameActivityDTO>> gameMap = new HashMap<>();
        Map<String, List<AchievementSystemDTO>> achievementMap = new HashMap<>();
        Map<String, List<CoupCardShelfDTO>> shelfMap = new HashMap<>();
        while (it.hasNext()) {
            String key = it.next();
            Set<String> ids = new HashSet<String>();
            Set<Long> longIds = new HashSet<Long>();
            if ("RECEIVE_003".equals(key)) {
                List<MemberCardLogDTO> _list = map.get("RECEIVE_003");
                for (MemberCardLogDTO _dto : _list) {
                    if (!StringUtil.isBlank(_dto.getRelationId())) {
                        ids.add(_dto.getRelationId());
                    }
                }
                if (CollectionUtils.isNotEmpty(ids)) {
                    List<EcmPlanDTO> ecmList = ecmPlanService.getEcmNameByIds(ids);
                    ecmMap = CollectionUtil.group(ecmList, "ecmPlanId");
                }
            }
            if ("RECEIVE_004".equals(key)) {

            }
            if ("RECEIVE_005".equals(key)) {
                List<MemberCardLogDTO> _list = map.get("RECEIVE_005");
                for (MemberCardLogDTO _dto : _list) {
                    if (!StringUtil.isBlank(_dto.getRelationId())) {
                        ids.add(_dto.getRelationId());
                    }
                }
                if (CollectionUtils.isNotEmpty(ids)) {
                    List<CoupCardShelfDTO> shelfList = this.couponCardService.getShelfNameByIds(ids);
                    shelfMap = CollectionUtil.group(shelfList, "shelfId");
                }

            }
            if ("RECEIVE_007".equals(key)) {
                List<MemberCardLogDTO> _list = map.get("RECEIVE_007");
                for (MemberCardLogDTO _dto : _list) {
                    if (!StringUtil.isBlank(_dto.getRelationId())) {
                        ids.add(_dto.getRelationId());
                    }
                }
                if (CollectionUtils.isNotEmpty(ids)) {
                    List<GameActivityDTO> gameList = gameService.listGameNameByRecordCodes(enterpriseId, ids);
                    gameMap = CollectionUtil.group(gameList, "gameActivityId");
                }
            }
            if ("RECEIVE_010".equals(key)) {
                List<MemberCardLogDTO> _list = map.get("RECEIVE_010");
                for (MemberCardLogDTO _dto : _list) {
                    if (!StringUtil.isBlank(_dto.getRelationId())) {
                        ids.add(_dto.getRelationId());
                    }
                }
                if (CollectionUtils.isNotEmpty(ids)) {
                    List<AchievementSystemDTO> achievementList = achievementService.getNameByIds(ids);
                    achievementMap = CollectionUtil.group(achievementList, "achievementSystemId");
                }
            }
            if ("RECEIVE_026".equals(key)) {
                List<MemberCardLogDTO> _list = map.get("RECEIVE_026");
                for (MemberCardLogDTO _dto : _list) {
                    if (!StringUtil.isBlank(_dto.getRelationId())) {
                        longIds.add(Long.parseLong(_dto.getRelationId()));
                    }
                }
                if (CollectionUtils.isNotEmpty(longIds)) {
                    ServiceResponse<List<GameDTO>> gameList = gameApiService.getGameList(Lists.newArrayList(longIds),
                            enterpriseId);
                    List<GameDTO> result = gameList.getResult();
                    if (CollectionUtils.isNotEmpty(result)) {
                        newGameMap = result.stream().collect(Collectors.toMap(GameDTO::getGameId, v -> v));
                    }
                }
            }
        }
        for (int i = 0; i < list.size(); i++) {
            MemberCardLogDTO c = list.get(i);
            if (org.apache.commons.lang3.StringUtils.isNotBlank(c.getRelationId())) {
                if ("RECEIVE_003".equals(c.getReceiveCode())) {
                    List<EcmPlanDTO> ecmList = ecmMap.get(c.getRelationId());
                    if (CollectionUtils.isNotEmpty(ecmList)) {
                        c.setReceiveTypeExcel(ecmList.get(0).getEcmPlanName());
                    }
                }
                if ("RECEIVE_004".equals(c.getReceiveCode())) {
                    // 门店展架-门店名称
                    c.setReceiveTypeExcel(c.getStoreName());
                }
                if ("RECEIVE_005".equals(c.getReceiveCode())) {
                    List<CoupCardShelfDTO> referList = shelfMap.get(c.getRelationId());
                    if (CollectionUtils.isNotEmpty(referList)) {
                        c.setReceiveTypeExcel(referList.get(0).getShelfName());
                    }
                }
                if ("RECEIVE_007".equals(c.getReceiveCode())) {
                    List<GameActivityDTO> referList = gameMap.get(c.getRelationId());
                    if (CollectionUtils.isNotEmpty(referList)) {
                        c.setReceiveTypeExcel(referList.get(0).getGameName());
                    }
                }
                if ("RECEIVE_010".equals(c.getReceiveCode())) {
                    List<AchievementSystemDTO> referList = achievementMap.get(c.getRelationId());
                    if (CollectionUtils.isNotEmpty(referList)) {
                        c.setReceiveTypeExcel(referList.get(0).getAchievementName());
                    }
                }
                if ("RECEIVE_026".equals(c.getReceiveCode())) {
                    GameDTO gameDTO = newGameMap.get(Long.parseLong(c.getRelationId()));
                    if (gameDTO != null) {
                        c.setReceiveTypeExcel(gameDTO.getGameName());
                    }
                }
            }
        }
    }
}
