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

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.gic.enterprise.api.constant.EnterpriseServiceEnum;
import com.gic.haoban.manage.api.dto.StaffClerkRelationDTO;
import com.gic.haoban.manage.api.dto.WxEnterpriseQwDTO;
import com.gic.haoban.manage.api.enums.NoticeMessageTypeEnum;
import com.gic.haoban.manage.api.enums.content.MaterialReportType;
import com.gic.haoban.manage.api.service.StaffApiService;
import com.gic.haoban.manage.api.util.notify.NoticeMessageUtil;
import com.gic.haoban.manage.service.config.Config;
import com.gic.haoban.manage.service.entity.TabHaobanClerkMainStoreRelated;
import com.gic.haoban.manage.service.pojo.bo.content.context.MaterialReportContext;
import com.gic.haoban.manage.service.service.ClerkMainStoreRelatedService;
import com.gic.haoban.manage.service.service.StaffClerkRelationService;
import com.gic.haoban.manage.service.util.DrawImageUtils;
import com.gic.wechat.api.dto.qywx.QywxNewsArticleMessageDTO;
import com.gic.wechat.api.dto.qywx.QywxNewsSendMessageDTO;
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.Collections;
import java.util.List;
import java.util.Optional;

/**
 * @Author MUSI
 * @Date 2023/3/24 4:11 PM
 * @Description
 * @Version 素材周报/月报组装
 **/

@Slf4j
@Component
public class WeekMonthReportBuilder {
    @Autowired
    private StaffClerkRelationService staffClerkRelationService;
    @Autowired
    private ClerkMainStoreRelatedService clerkMainStoreRelatedService;
    @Autowired
    private WeekMonthDataAdaptor weekMonthDataAdaptor;
    @Autowired
    private Config config;
    @Autowired
    private StaffApiService staffApiService;


    /**
     * 柱状成员绑定的导购信息
     *
     * @param context
     */
    public void buildStaffRelationClerk(MaterialReportContext context) {
        if (StringUtils.isAnyBlank(context.getStaffId(), context.getEnterpriseId())) {
            log.info("参数异常 staffId:{}, enterpriseId:{}", context.getStaffId(), context.getEnterpriseId());
            return;
        }

        List<StaffClerkRelationDTO> staffClerkRelations =
                staffClerkRelationService.listBindCodeByStaffId(Collections.singletonList(context.getEnterpriseId()), context.getStaffId());
        if (CollectionUtils.isEmpty(staffClerkRelations)) {
            log.info("成员未关联导购 staffId:{}, enterpriseId:{}", context.getStaffId(), context.getEnterpriseId());
            return;
        }
        context.setStaffClerkRelations(staffClerkRelations);
    }

    /**
     * 填充该成员的主门店
     *
     * @param context
     */
    public void fillMainStore(MaterialReportContext context) {
        if (CollectionUtils.isEmpty(context.getStaffClerkRelations())) {
            log.info("不存在成员与导购的关联关系 staffId: {}", context.getStaffId());
            return;
        }
        if (context.getStaffClerkRelations().size() == 1) {
            StaffClerkRelationDTO staffClerkRelationDTO = context.getStaffClerkRelations().get(0);
            if (staffClerkRelationDTO.getClerkType() != null && staffClerkRelationDTO.getClerkType() == 2) {
                log.info("成员clerkId:{}, staffId: {} 为区经角色", staffClerkRelationDTO.getClerkId(), staffClerkRelationDTO.getStaffId());
                // 区经无主门店
                context.setClerkId(staffClerkRelationDTO.getClerkId());
                // 是区经角色
                context.setManager(true);
                return;
            }
        }
        log.info("成员{}为导购角色", context.getStaffId());
        context.setManager(false);
        // 获取成员主门店
        TabHaobanClerkMainStoreRelated mainStoreInfo = clerkMainStoreRelatedService.getMainStoreByStaffId(context.getStaffId(), context.getStaffInfo().getWxEnterpriseId());
        if (mainStoreInfo != null) {
            context.setMainStoreId(mainStoreInfo.getStoreId());
            Optional<StaffClerkRelationDTO> mainClerkInfo = context.getStaffClerkRelations()
                    .stream()
                    .filter(item -> StringUtils.equals(item.getStoreId(), mainStoreInfo.getStoreId()))
                    .findFirst();
            if (!mainClerkInfo.isPresent()) {
                log.info("成员{}的主门店{}不在当前企业{}的绑定关系中", context.getStaffId(), context.getMainStoreId(), context.getEnterpriseId());
                return;
            }
            // 成员在主门店时的clerkId
            context.setClerkId(mainClerkInfo.get().getClerkId());
        }
    }

    /**
     * 周报/月报 数据
     *
     * @param context
     */
    public void buildMaterialReportData(MaterialReportContext context) {
        // 获取该导购/店长/区经 的周报/月报数据
        if (StringUtils.isBlank(context.getClerkId())) {
            log.info("成员{} 默认主门店的clerkId不存在 不发送应用消息", context.getStaffId());
            return;
        }
        String clerkId = context.getClerkId();
        String enterpriseId = context.getEnterpriseId();
        WeekMonthDataAdaptor.MaterialDataResult materialDataResult;

        String bizDate = this.calcBizDate(context.getReportType());
        context.setBizDate(bizDate);
        if (StringUtils.isBlank(context.getMainStoreId())) {
            // 区经
            List<String> storeIds = this.queryClerkStoreIds(clerkId, context.getStaffInfo().getWxEnterpriseId());
            materialDataResult = weekMonthDataAdaptor.queryAreaReportData(context, storeIds, bizDate);
        } else {
            String mainStoreId = context.getMainStoreId();
            materialDataResult = weekMonthDataAdaptor.queryClerkReportData(context, mainStoreId, bizDate);
        }
        log.info("获取成员海报数据 clerkId:{}, data: {}", clerkId, JSON.toJSONString(materialDataResult));
        if (materialDataResult == null) {
            materialDataResult = WeekMonthDataAdaptor.MaterialDataResult.buildEmpty();
        }
        DrawImageUtils.DrawBkgImg templatePath = getDrawBkgImg(context);
        if (templatePath == null) {
            return;
        }
        // 生成图片地址
        String url = DrawImageUtils.drawImage(context.getFactoryCode(),
                StringUtils.isBlank(materialDataResult.getFirstValue())?"0":materialDataResult.getFirstValue(),
                StringUtils.isBlank(materialDataResult.getSecondValue())?"0":materialDataResult.getSecondValue(),
                templatePath);
        context.setMaterialReportUrl(url);
    }

    private static DrawImageUtils.DrawBkgImg getDrawBkgImg(MaterialReportContext context) {
        boolean isWeek = MaterialReportType.WEEK.getCode().equals(context.getReportType());
        boolean hasMainStore = StringUtils.isNotBlank(context.getMainStoreId());
        List<String> rightMenuCodeList = context.getRightMenuCodeList();
        String key = (hasMainStore ? "CLERK" : "AREA") + (isWeek ? "_WEEK" : "_MONTH");
        if (rightMenuCodeList.size() > 1) {
            return DrawImageUtils.templateMap.get(key);
        }
        else if (rightMenuCodeList.contains(EnterpriseServiceEnum.POTENTIAL.getRightMenuCode())) {
            key = "POTENTIAL_" + key;
            return DrawImageUtils.templateMap.get(key);
        }
        else if (rightMenuCodeList.contains(EnterpriseServiceEnum.CONTENT.getRightMenuCode())) {
            key = "CONTENT_" + key;
            return DrawImageUtils.templateMap.get(key);
        }
        return null;
    }

    /**
     * 计算素材周报的周期
     * yyyy-biz
     *
     * @param reportType
     * @return
     */
    private String calcBizDate(Integer reportType) {
        String bizDate = null;
        if (MaterialReportType.WEEK.getCode().equals(reportType)) {
            // 周报
            bizDate = DateUtil.beginOfWeek(DateUtil.lastWeek()).toString("yyyy-MM-dd");

        } else {
            // 月报
            bizDate = DateUtil.beginOfMonth(DateUtil.lastMonth()).toString("yyyy-MM");
        }
        return bizDate;
    }

    /***
     * 构建企业微信消息
     *
     * @param context
     */
    public QywxNewsSendMessageDTO buildQywxNewsMessage(MaterialReportContext context, WxEnterpriseQwDTO wxEnterpriseQwDTO) {
        if (context.getStaffInfo() == null) {
            log.info("构建企业微信对象, 成员信息不存在 {}", JSON.toJSONString(context));
            return null;
        }
        String wxUserId = context.getStaffInfo().getWxUserId();
        if (wxEnterpriseQwDTO.needOpenUserId3th()) {
            wxUserId = context.getStaffInfo().getWxOpenUseId();
        }
        QywxNewsSendMessageDTO newsSendMessage = new QywxNewsSendMessageDTO();
        newsSendMessage.setAgentId(Integer.parseInt(wxEnterpriseQwDTO.getAgentId()));
        newsSendMessage.setUserIds(Collections.singletonList(wxUserId));
        QywxNewsArticleMessageDTO articleInfo = new QywxNewsArticleMessageDTO();
        articleInfo.setAppid(wxEnterpriseQwDTO.getHbWxaAppid());
        articleInfo.setTitle(context.getMessageTitle());
        articleInfo.setDescription(context.getMessageDesc());
        String extendParams = StringUtils.isNotBlank(context.getMainStoreId()) ? context.getMainStoreId() : context.getEnterpriseId();

        final NoticeMessageTypeEnum noticeMessageTypeEnum = MaterialReportType.WEEK.getCode().equals(context.getReportType()) ? NoticeMessageTypeEnum.MATERIAL_REPORT_NOTIFY_WEEK : NoticeMessageTypeEnum.MATERIAL_REPORT_NOTIFY_MONTH;
        articleInfo.setPagepath(NoticeMessageUtil.buildMiniAppUrl(noticeMessageTypeEnum, context.extendParams(extendParams)));
        articleInfo.setPicurl(context.getMaterialReportUrl());
        newsSendMessage.setArticleMessages(Collections.singletonList(articleInfo));
        return newsSendMessage;
    }


    /**
     * 查询区经角色下管辖的门店权限
     *
     * @param clerkId
     * @param wxEnterpriseId
     * @return
     */
    public List<String> queryClerkStoreIds(String clerkId, String wxEnterpriseId) {
        List<String> storeIds = staffApiService.getHaoBanStoreIdsRolesByClerkId(clerkId, wxEnterpriseId);
        if (CollectionUtils.isEmpty(storeIds)) {
            log.info("根据区经id查询管辖的门店为空 {} {}", clerkId, wxEnterpriseId);
            return Collections.singletonList("-100");
        }
        if (storeIds.size() == 1 && StringUtils.equals(storeIds.get(0), "-1")) {
            // 全部门店权限
            log.info("区经有全部门店权限 {}", clerkId);
            return Collections.emptyList();
        }
        return storeIds;
    }

}
