package com.gic.haoban.manage.service.service.content.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gic.commons.util.UniqueIdUtils;
import com.gic.enterprise.api.dto.EnterpriseDTO;
import com.gic.enterprise.api.service.EnterpriseService;
import com.gic.haoban.manage.api.dto.WxEnterpriseQwDTO;
import com.gic.haoban.manage.api.dto.content.report.MaterialReportDTO;
import com.gic.haoban.manage.api.enums.NoticeMessageTypeEnum;
import com.gic.haoban.manage.api.enums.content.MaterialReportType;
import com.gic.haoban.manage.service.config.Config;
import com.gic.haoban.manage.service.entity.TabHaobanStaff;
import com.gic.haoban.manage.service.pojo.bo.NoticeMessageBO;
import com.gic.haoban.manage.service.pojo.bo.content.context.MaterialReportContext;
import com.gic.haoban.manage.service.service.StaffService;
import com.gic.haoban.manage.service.service.WxEnterpriseService;
import com.gic.haoban.manage.service.service.content.MaterialReportService;
import com.gic.haoban.manage.service.service.content.adaptor.WeekMonthReportBuilder;
import com.gic.haoban.manage.service.service.message.NoticeMessageHandler;
import com.gic.haoban.manage.service.service.notify.NoticeMessageService;
import com.gic.haoban.manage.service.util.ApolloUtils;
import com.gic.message.center.api.subscribe.model.NoticeMessageForm;
import com.gic.wechat.api.dto.qywx.QywxNewsArticleMessageDTO;
import com.gic.wechat.api.dto.qywx.QywxNewsSendMessageDTO;
import com.gic.wechat.api.service.qywx.QywxSuiteApiService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author MUSI
 * @Date 2023/3/24 3:59 PM
 * @Description
 * @Version
 **/

@Slf4j
@Component
public class MaterialReportServiceImpl implements MaterialReportService {

    @Autowired
    private NoticeMessageService noticeMessageService;
    @Autowired
    private WeekMonthReportBuilder weekMonthReportBuilder;
    @Autowired
    private QywxSuiteApiService qywxSuiteApiService;
    @Autowired
    private WxEnterpriseService wxEnterpriseService;
    @Autowired
    private EnterpriseService enterpriseService;
    @Autowired
    private StaffService staffService;
    @Autowired
    private Config config;

    @Autowired
    private NoticeMessageHandler noticeMessageHandler;


    /**
     * 素材周报/月报
     *
     * @param enterpriseId
     */
    @Override
    public void handlerMaterialReport(MaterialReportDTO materialReportDTO) {
        String enterpriseId = materialReportDTO.getEnterpriseId();
        String staffId = materialReportDTO.getStaffId();
        Integer reportType = materialReportDTO.getReportType();
        List<String> rightMenuCodeList = materialReportDTO.getRightMenuCodeList();

        EnterpriseDTO enterpriseDTO = enterpriseService.getEnterpriseById(enterpriseId);
        if (enterpriseDTO == null) {
            log.info("企业信息不存在 enterpriseId:{}", enterpriseId);
            return;
        }
        TabHaobanStaff staffInfo = staffService.selectById(staffId);
        if (staffInfo == null) {
            log.info("成员不存在 {}", staffId);
            return;
        }
        MaterialReportContext context = MaterialReportContext.builder()
                .enterpriseId(enterpriseId)
                .factoryCode(enterpriseDTO.getFactoryCode())
                .staffId(staffId)
                .staffInfo(staffInfo)
                .reportType(reportType)
                .rightMenuCodeList(rightMenuCodeList)
                .build();
        // 获取成员关联的导购
        weekMonthReportBuilder.buildStaffRelationClerk(context);
        if (CollectionUtils.isEmpty(context.getStaffClerkRelations())) {
            log.info("处理成员周报月报数据, 成员{}未绑定导购", staffId);
            return;
        }
        // 判断是区经还是 店长/导购 填充主门店
        weekMonthReportBuilder.fillMainStore(context);
        // 获取素材数据
        weekMonthReportBuilder.buildMaterialReportData(context);
        // 保存小程序消息
        List<NoticeMessageBO> noticeMessageBos = context.buildNotifyMessageBos();

        if (!ApolloUtils.useMessageCenter()){
            log.info("消息中心-走老版消息通知");
            /*消息中心修改此处*/
            if (CollectionUtils.isNotEmpty(noticeMessageBos)) {
                noticeMessageService.addNoticeMessageBatch(noticeMessageBos);
            }
        }

        if (StringUtils.isBlank(context.getClerkId())) {
            log.info("成员{}在企业{}中不存在主门店, 不推送企微应用消息", staffId, enterpriseId);
            if (ApolloUtils.useMessageCenter()) {
                noticeMessageService.addNoticeMessageBatch(noticeMessageBos);
            }
            return;
        }


        // 发送企微消息
        WxEnterpriseQwDTO qwDTO = this.wxEnterpriseService.getQwInfo(staffInfo.getWxEnterpriseId());
        QywxNewsSendMessageDTO newsSendMessageDTO = weekMonthReportBuilder.buildQywxNewsMessage(context, qwDTO);
        if (newsSendMessageDTO == null) {
            log.info("构建企业应用消息异常 clerkId:{}m staffId: {}", context.getClerkId(), context.getStaffId());
            return;
        }
        log.info("发送企业图文消息参数{}", JSON.toJSONString(newsSendMessageDTO));

        if (!ApolloUtils.useMessageCenter()){
            log.info("消息中心-走老版消息通知");
            /*消息中心修改此处*/
            boolean result = qywxSuiteApiService.sendMessage(qwDTO.getThirdCorpid(), qwDTO.getSelf3thSecret(), newsSendMessageDTO,qwDTO.isSelf(),qwDTO.getUrlHost());
            log.info("成员{}发送素材企微使用报告结果 {}", staffId, result);
            return;
        } else {
            Map<String, String> variableMap = new HashMap<>();
            QywxNewsArticleMessageDTO qywxNewsArticleMessageDTO = newsSendMessageDTO.getArticleMessages().get(0);
            variableMap.put("image", qywxNewsArticleMessageDTO.getPicurl());
            variableMap.put("page", qywxNewsArticleMessageDTO.getPagepath());
            variableMap.put("templateTitle", qywxNewsArticleMessageDTO.getTitle());
            variableMap.put("templateDescription", qywxNewsArticleMessageDTO.getDescription());
            variableMap.put("haobanNoticeMessageList", JSONObject.toJSONString(noticeMessageBos));
            NoticeMessageTypeEnum noticeMessageTypeEnum = null;
            if (MaterialReportType.WEEK.getCode().equals(context.getReportType())) {
                noticeMessageTypeEnum = NoticeMessageTypeEnum.MATERIAL_REPORT_NOTIFY_WEEK;
            } else if (MaterialReportType.MONTH.getCode().equals(context.getReportType())) {
                noticeMessageTypeEnum = NoticeMessageTypeEnum.MATERIAL_REPORT_NOTIFY_MONTH;
            }

            if (ObjectUtil.isNull(noticeMessageTypeEnum)){
                log.info("枚举不存在 context:{}", JSONObject.toJSONString(context));
                return;
            }
            noticeMessageHandler.sendMessage(NoticeMessageForm.builder()
                    .messageCode(noticeMessageTypeEnum.getMessageCode())
                    .mqRouterCode(noticeMessageTypeEnum.getRouterCode())
                    .businessId("-1")
                    .createTime(new Date())
                    .enterpriseId(context.getEnterpriseId())
                    .uniqueKey(UniqueIdUtils.uniqueLongHex())
                    .userIdList(context.getClerkId() == null ? new ArrayList<>() : Collections.singletonList(context.getClerkId()))
                    .variableMap(variableMap).build());
        }



        /*boolean result = qywxSuiteApiService.sendMessage(qwDTO.getThirdCorpid(), qwDTO.getSelf3thSecret(), newsSendMessageDTO,qwDTO.isSelf(),qwDTO.getUrlHost());
        log.info("成员{}发送素材企微使用报告结果 {}", staffId, result);*/
    }
}
