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

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.clerk.api.dto.AuthorizedUser;
import com.gic.commons.util.EntityUtil;
import com.gic.commons.util.PageHelperUtils;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.enterprise.api.service.EnterpriseWxaLinkService;
import com.gic.haoban.base.api.common.pojo.dto.WebLoginDTO;
import com.gic.haoban.common.utils.AuthWebRequestUtil;
import com.gic.haoban.manage.api.dto.chat.*;
import com.gic.haoban.manage.api.dto.qdto.chat.ChatHmSearchQDTO;
import com.gic.haoban.manage.api.enums.chat.ChatActivityRewardEnum;
import com.gic.haoban.manage.api.qdto.chat.GroupChatActivityQDTO;
import com.gic.haoban.manage.api.qdto.chat.GroupChatActivitySearchQDTO;
import com.gic.haoban.manage.api.service.chat.GroupChatActivityApiService;
import com.gic.haoban.manage.api.service.chat.GroupChatHmApiService;
import com.gic.haoban.manage.web.log.LogRecordAfterGroupChatActivityServiceImpl;
import com.gic.haoban.manage.web.log.LogRecordUserServiceImpl;
import com.gic.haoban.manage.web.qo.chat.GroupChatActivitySaveQO;
import com.gic.haoban.manage.web.qo.chat.GroupChatActivitySearchQO;
import com.gic.haoban.manage.web.utils.CreatorUtils;
import com.gic.haoban.manage.web.vo.MemberLabelVO;
import com.gic.haoban.manage.web.vo.MemberTagGroupVO;
import com.gic.haoban.manage.web.vo.chat.GroupChatActivityVO;
import com.gic.haoban.manage.web.vo.chat.GroupChatHmVO;
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.marketing.api.dto.card.CardStockAndInvalidDTO;
import com.gic.marketing.api.service.CouponCardService;
import com.gic.member.tag.api.dto.MemberTagDTO;
import com.gic.member.tag.api.dto.MemberTagGroupDTO;
import com.gic.member.tag.api.dto.MemberTagItemDTO;
import com.gic.member.tag.api.service.MemberTagApiService;
import com.gic.member.tag.api.service.MemberTagGroupApiService;
import com.gic.web.common.utils.SessionContextUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
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.*;

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

/**
 * 社群活动
 */
@RestController
@RequestMapping("/chat")
public class GroupChatActivityController {

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

    @Autowired
    private GroupChatActivityApiService groupChatActivityApiService;
    @Autowired
    private CouponCardService couponCardService;
    @Autowired
    private MemberTagGroupApiService memberTagGroupService;
    @Autowired
    private GroupChatHmApiService groupChatHmApiService;

    @Autowired
    private EnterpriseWxaLinkService enterpriseWxaLinkService ;
    @Autowired
    private MemberTagApiService memberTagApiService;

    /**
     * 社群活动分页查询
     *
     * @param search search
     * @return RestResponse
     */
    @RequestMapping("/page-activity")
    @ResponseBody
    public RestResponse<Page<GroupChatActivityVO>> queryByPage(@RequestBody GroupChatActivitySearchQO search) {
        WebLoginDTO user = AuthWebRequestUtil.getLoginUser();
        List<String> creatorIdList = CreatorUtils.getCreatorIdList(search.getShowSelfFlag());
        GroupChatActivitySearchQDTO activitySearchQDTO = EntityUtil.changeEntityNew(GroupChatActivitySearchQDTO.class, search);
        activitySearchQDTO.setCreatorIdList(creatorIdList);
        activitySearchQDTO.setWxEnterpriseId(user.getWxEnterpriseId());
        BasePageInfo basePageInfo = search.getBasePageInfo();
        ServiceResponse<Page<GroupChatActivityDTO>> response = groupChatActivityApiService.pageActivity(user.getEnterpriseId(),activitySearchQDTO,basePageInfo);
        if (!response.isSuccess()) {
            return RestResponse.failure(response.getCode(), response.getMessage());
        }
        Page<GroupChatActivityDTO> result = response.getResult();
        Page<GroupChatActivityVO> ret = PageHelperUtils.changePageToCurrentPage(result, GroupChatActivityVO.class);
        return RestResponse.successResult(ret);
    }

    /**
     * 社群活动详情查询
     *
     * @param chatActivityId 主键ID
     * @return RestResponse
     */
    @RequestMapping("detail-activity")
    @ResponseBody
    public RestResponse<GroupChatActivityVO> detailActivity(Long chatActivityId) {
        WebLoginDTO user = AuthWebRequestUtil.getLoginUser();
        ServiceResponse<GroupChatActivityDTO> response = groupChatActivityApiService.getActivityDetail(user.getEnterpriseId(),chatActivityId);
        if (!response.isSuccess()) {
            return RestResponse.failure(response.getCode(), response.getMessage());
        }
        GroupChatActivityVO result = EntityUtil.changeEntityNew(GroupChatActivityVO.class, response.getResult());
        buildActivityExtend(result);
        return RestResponse.successResult(result);
    }

    private void buildActivityExtend(GroupChatActivityVO activityVO) {
        if (activityVO == null) {
            return;
        }
        List<Long> hmIdList = new ArrayList<>();
        Long joinChatHmId = activityVO.getJoinChatHmId();
        if (joinChatHmId != null) {
            hmIdList.add(joinChatHmId);
        }
        //构建卡券map
        List<String> couponIdList = GroupChatActivityRewardBaseDTO.mapConvert(activityVO.getRewardMap()).stream()
                .filter(x -> Objects.equals(x.getRewardType(), ChatActivityRewardEnum.COUPON.value))
                .map(GroupChatActivityRewardBaseDTO::getRewardValue)
                .flatMap(rewardValue -> Arrays.stream(rewardValue.split(",")))
                .distinct().collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(couponIdList)) {
            Map<String, CardStockAndInvalidDTO> couponMap = couponCardService.getCardInvalidList(couponIdList);
            activityVO.setCouponMap(couponMap);
        }
        //构建会员分组map
        List<Map<String, Object>> memberWeightViewList = Lists.newArrayList();
        List<GroupChatActivityJoinDTO> joinList = activityVO.getJoinList();
        if (CollectionUtils.isNotEmpty(joinList)) {
            for (GroupChatActivityJoinDTO joinDTO : joinList) {
                Map<String, Object> memberWeightView = Maps.newHashMap();
                Integer memberType = joinDTO.getMemberType();
                // 会员信息
                if (Objects.equals(memberType,0)) {
                    // 查询人群筛选器搜索条件主键ID
                    memberWeightView.put("searchId", "GROUP_CHAT_SEARCH_ID_" + joinDTO.getChatActivityId() + "-" + joinDTO.getIndex());
                } else if (Objects.equals(memberType,1)) {
                    // 会员分组
                    memberWeightView.put("tagGroupList", listMemberTagGroupInfoByGroupIds(joinDTO.getFilterJson()));
                }
                memberWeightViewList.add(memberWeightView);
                activityVO.setMemberWeightViewList(memberWeightViewList);
                Long chatHmId = joinDTO.getChatHmId();
                if (chatHmId != null) {
                    hmIdList.add(chatHmId);
                }
            }
        }
        //构建活码map
        if (CollectionUtils.isNotEmpty(hmIdList)) {
            ChatHmSearchQDTO hmSearchQDTO = new ChatHmSearchQDTO();
            hmSearchQDTO.setEnterpriseId(activityVO.getEnterpriseId());
            hmSearchQDTO.setWxEnterpriseId(activityVO.getWxEnterpriseId());
            hmSearchQDTO.setChatHmIdList(hmIdList);
            BasePageInfo basePageInfo = new BasePageInfo();
            basePageInfo.setPageNum(1);
            basePageInfo.setPageSize(1000);
            ServiceResponse<Page<GroupChatHmDTO>> pageResp = this.groupChatHmApiService.listPage(hmSearchQDTO, basePageInfo);
            if (pageResp.isSuccess() && pageResp.getResult() != null && CollectionUtils.isNotEmpty(pageResp.getResult().getResult())) {
                List<GroupChatHmDTO> chatHmList = pageResp.getResult().getResult();
                Map<String, GroupChatHmVO> chatHmMap = chatHmList.stream().map(x -> EntityUtil.changeEntityNew(GroupChatHmVO.class, x))
                        .collect(Collectors.toMap(k -> String.valueOf(k.getChatHmId()), v -> v, (e, x) -> e));
                activityVO.setChatHmMap(chatHmMap);
            }
        }
        //构建标签回显
        String labelJson = activityVO.getLabelJson();
        if (StringUtils.isNotBlank(labelJson)) {
            String id = JSONObject.parseObject(labelJson).getString("id");
            List<MemberLabelVO> memberLabelList = getMemberLabelList(id);
            if (CollectionUtils.isNotEmpty(memberLabelList)) {
                Map<String, MemberLabelVO> labelMap = memberLabelList.stream().collect(Collectors.toMap(MemberLabelVO::getLabelValueId, v -> v, (e, x) -> e));
                activityVO.setLabelMap(labelMap);
            }
        }
    }
    public List<MemberTagGroupVO> listMemberTagGroupInfoByGroupIds(String tagGroupIds) {

        List<MemberTagGroupVO> result = new ArrayList<>();
        if (StringUtils.isBlank(tagGroupIds)) {
            return result;
        }

        String[] tagGroupIdArr = tagGroupIds.split(",");
        if (ArrayUtils.isEmpty(tagGroupIdArr)) {
            return result;
        }

        List<MemberTagGroupDTO> memberTagGroupDTOList = memberTagGroupService.findListByIds(
                new ArrayList<>(Arrays.asList(tagGroupIdArr)));
        if (CollectionUtils.isNotEmpty(memberTagGroupDTOList)) {

            for (MemberTagGroupDTO memberTagGroupDTO : memberTagGroupDTOList) {
                MemberTagGroupVO memberTagGroupVO = new MemberTagGroupVO();
                memberTagGroupVO.setGroupName(memberTagGroupDTO.getGroupName());
                memberTagGroupVO.setMemberTagGroupId(memberTagGroupDTO.getMemberTagGroupId());
                memberTagGroupVO.setEffectiveStatus(memberTagGroupDTO.getEffectiveStatus());
                memberTagGroupVO.setIsRealTime(memberTagGroupDTO.getIsRealTime());
                memberTagGroupVO.setFixedType(memberTagGroupDTO.getFixedType());
                result.add(memberTagGroupVO);
            }
        }

        return result;
    }

    private List<MemberLabelVO> getMemberLabelList(String memberTags) {
        if (StringUtils.isBlank(memberTags)) {
            return null;
        }
        List<String> list = new ArrayList<>();
        String[] arr = memberTags.split(",");
        for (int i = 0; i < arr.length; i++) {
            String s = arr[i];
            if (StringUtils.isNotBlank(s)) {
                list.add(s);
            }
        }
        List<MemberLabelVO> memberLabelVOList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(list)) {
            for (String memberLabelId : list) {
                MemberTagItemDTO tagItem = this.memberTagApiService.findMemberTagItem(memberLabelId);
                if (null != tagItem) {
                    String tagId = tagItem.getTagId();
                    MemberTagDTO tag = this.memberTagApiService.getMemberTagById(tagId);
                    MemberLabelVO vo = new MemberLabelVO();
                    vo.setLabelName(tag.getTagName());
                    vo.setLabelValueName(tagItem.getTagItemName());
                    vo.setLabelValueStatus(tagItem.getStatus());
                    if(tagItem.getStatus()!=0) {
                        vo.setLabelValueStatus(1);
                    }
                    vo.setLabelValueId(memberLabelId);
                    vo.setLabelId(tagId);
                    memberLabelVOList.add(vo);
                }
            }
        }
        return memberLabelVOList;
    }

    /**
     * 社群活动终止
     *
     * @param chatActivityId 主键ID
     * @return RestResponse
     */
    @RequestMapping("stop-activity")
    @ResponseBody
    @GicLogRecord(value = "【${#activityName}+${#chatActivityId}】活动被终止"
            , category = GicLogRecordCategoryEnum.HB_QHM_ACTIVITY
            , optType = GicLogRecordOptTypeEnum.HB_1005_03
            , optPage = "营销-社群营销-社群邀请有礼"
            , userFunc = LogRecordUserServiceImpl.class)
    public RestResponse<Void> stopActivity(Long chatActivityId) {
        AuthorizedUser user = SessionContextUtils.getLoginUser();
        ServiceResponse<GroupChatActivityDTO> response = groupChatActivityApiService.stopActivity(user.getEnterpriseId(),chatActivityId);
        if (!response.isSuccess()) {
            GicLogRecordEvaluationContext.noWriteLog();
            return RestResponse.failure(response.getCode(), response.getMessage());
        }
        GicLogRecordEvaluationContext.putAttribute("activityName", response.getResult().getActivityName());
        GicLogRecordEvaluationContext.putAttribute("chatActivityId", chatActivityId);
        return RestResponse.successResult();
    }

    /**
     * 社群活动删除
     *
     * @param chatActivityId 主键ID
     * @return RestResponse
     */
    @RequestMapping("del-activity")
    @ResponseBody
    @GicLogRecord(value = "【${#activityName}+${#chatActivityId}】活动被删除"
            , category = GicLogRecordCategoryEnum.HB_QHM_ACTIVITY
            , optType = GicLogRecordOptTypeEnum.HB_1005_02
            , optPage = "营销-社群营销-社群邀请有礼"
            , userFunc = LogRecordUserServiceImpl.class)
    public RestResponse<Void> delActivity(Long chatActivityId) {
        WebLoginDTO user = AuthWebRequestUtil.getLoginUser();
        ServiceResponse<GroupChatActivityDTO> response = groupChatActivityApiService.getActivityDetail(user.getEnterpriseId(),chatActivityId);
        if (!response.isSuccess()) {
            GicLogRecordEvaluationContext.noWriteLog();
            return RestResponse.failure(response.getCode(), response.getMessage());
        }
        ServiceResponse<Void> delResponse = groupChatActivityApiService.delActivity(user.getEnterpriseId(),chatActivityId);
        if (!delResponse.isSuccess()) {
            GicLogRecordEvaluationContext.noWriteLog();
            return RestResponse.failure(delResponse.getCode(), delResponse.getMessage());
        }
        GicLogRecordEvaluationContext.putAttribute("activityName", response.getResult().getActivityName());
        GicLogRecordEvaluationContext.putAttribute("chatActivityId", chatActivityId);
        return RestResponse.successResult();
    }

    /**
     * 社群活动保存
     *
     * @param activitySaveQO
     * @return RestResponse
     */
    @GicLogRecord(value = ""
            , category = GicLogRecordCategoryEnum.HB_QHM_ACTIVITY
            , optType = GicLogRecordOptTypeEnum.HB_1005_01
            , optPage = "营销-社群营销-社群邀请有礼"
            , userFunc = LogRecordUserServiceImpl.class
            ,afterFunc = LogRecordAfterGroupChatActivityServiceImpl.class)
    @RequestMapping("save-activity")
    @ResponseBody
    public RestResponse<String> saveActivity(@RequestBody GroupChatActivitySaveQO activitySaveQO) {
        WebLoginDTO user = AuthWebRequestUtil.getLoginUser();
        if (activitySaveQO.getChatActivityId() != null) {
            ServiceResponse<GroupChatActivityDTO> oldResponse = groupChatActivityApiService.getActivityDetailCache(user.getEnterpriseId(),activitySaveQO.getChatActivityId());
            if (!oldResponse.isSuccess()) {
                return RestResponse.failure(oldResponse.getCode(), oldResponse.getMessage());
            }
            GicLogRecordEvaluationContext.putAttribute("oldActivityDTO", oldResponse.getResult());
        }
        GroupChatActivityQDTO activityQDTO = EntityUtil.changeEntityNew(GroupChatActivityQDTO.class, activitySaveQO);
        activityQDTO.setWxEnterpriseId(user.getWxEnterpriseId());
        activityQDTO.setEnterpriseId(user.getEnterpriseId());
        activityQDTO.setCreatorId(user.getClerkId());
        activityQDTO.setCreatorName(user.getClerkName());
        ServiceResponse<Long> response = groupChatActivityApiService.saveActivity(activityQDTO);
        if (!response.isSuccess()) {
            GicLogRecordEvaluationContext.noWriteLog();
            return RestResponse.failure(response.getCode(), response.getMessage());
        }
        if (activitySaveQO.getChatActivityId() != null) {
            ServiceResponse<GroupChatActivityDTO> newResponse = groupChatActivityApiService.getActivityDetailCache(user.getEnterpriseId(),activitySaveQO.getChatActivityId());
            if (!newResponse.isSuccess()) {
                return RestResponse.failure(newResponse.getCode(), newResponse.getMessage());
            }
            GicLogRecordEvaluationContext.putAttribute("newActivityDTO", newResponse.getResult());
        }
        return RestResponse.successResult(String.valueOf(response.getResult()));
    }


    /**
     * 获取社群活动二维码
     *
     * @param chatActivityId
     * @return
     */
    @RequestMapping("get-group-chat-activity-qrcode")
    @ResponseBody
    public RestResponse<Object> getGroupChatActivityQrcode(@RequestParam Long chatActivityId) {
        AuthorizedUser user = SessionContextUtils.getLoginUser();
        String enterpriseId = user.getEnterpriseId();
        ServiceResponse<GroupChatActivityDTO> activityDetailResult = groupChatActivityApiService.getActivityDetail(enterpriseId, chatActivityId);
        if (activityDetailResult.isSuccess() || Objects.isNull(activityDetailResult.getResult())) {
            return RestResponse.failure("9999", "活动不存在或者活动已删除");
        }
        JSONObject param = new JSONObject();
        JSONObject activityIdParam = new JSONObject();
        activityIdParam.put("activityId", chatActivityId);
        param.put("params", activityIdParam);
        param.put("id", "group_chat_activity");
        Map<String, Object> wxaLinkAndQrCode = enterpriseWxaLinkService.getWxaLinkAndQrCode(enterpriseId, param.toJSONString());
        Map<String, String> map = new HashMap<>();
        map.put("link", wxaLinkAndQrCode.get("link").toString());
        map.put("url", wxaLinkAndQrCode.get("url").toString());
        return RestResponse.successResult(map);
    }
}
