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

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
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.Date;
import java.util.List;
import java.util.Optional;

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

@Slf4j
@Component
public class MaterialReportBuilder {
    @Autowired
    private StaffClerkRelationService staffClerkRelationService;
    @Autowired
    private ClerkMainStoreRelatedService clerkMainStoreRelatedService;
    @Autowired
    private MaterialDataAdaptor materialDataAdaptor;
    @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("成员clerId:{}, staffId: {} 为区经角色", staffClerkRelationDTO.getClerkId(), staffClerkRelationDTO.getStaffId());
                // 区经无主门店
                context.setClerkId(staffClerkRelationDTO.getClerkId());
                return;
            }
        }
        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());
                return;
            }
            // 成员在主门店时的clerkId
            context.setClerkId(mainClerkInfo.get().getClerkId());
        }
    }

    /**
     * 周报/月报 数据
     *
     * @param context
     */
    public void buildMaterialReportData(MaterialReportContext context) {
        // 获取该导购/店长/区经 的周报/月报数据
        String clerkId = context.getClerkId();
        String enterpriseId = context.getEnterpriseId();
        MaterialDataAdaptor.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 = materialDataAdaptor.queryAreaReportData(enterpriseId, clerkId, storeIds, context.getReportType(), bizDate);
        } else {
            String mainStoreId = context.getMainStoreId();
            materialDataResult = materialDataAdaptor.queryClerkReportData(enterpriseId, clerkId, mainStoreId, context.getReportType(), bizDate);
        }
        log.info("获取成员海报数据 clerkId:{}, data: {}", clerkId, JSON.toJSONString(materialDataResult));
        if (materialDataResult == null) {
            materialDataResult = MaterialDataAdaptor.MaterialDataResult.buildEmpty();
        }
        DrawImageUtils.DrawBkgImg templatePath = null;
        if (MaterialReportType.WEEK.getCode().equals(context.getReportType())) {
            if (StringUtils.isBlank(context.getMainStoreId())) {
                templatePath = DrawImageUtils.DrawBkgImg.AREA_WEEK_BKG;
            } else {
                templatePath = DrawImageUtils.DrawBkgImg.CLERK_WEEK_BKG;
            }
        } else {
            if (StringUtils.isBlank(context.getMainStoreId())) {
                templatePath = DrawImageUtils.DrawBkgImg.AREA_MONTH_BKG;
            } else {
                templatePath = DrawImageUtils.DrawBkgImg.CLERK_MONTH_BKG;
            }
        }
        // 生成图片地址
        String url = DrawImageUtils.drawImage(context.getFactoryCode(), materialDataResult.getFirstValue(), materialDataResult.getSecondValue(), templatePath);
        context.setMaterialReportUrl(url);
    }

    /**
     * 计算素材周报的周期
     * 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");
            bizDate = DateUtil.beginOfWeek(new Date()).toString("yyyy-MM-dd");

        } else {
            // 月报
            //bizDate = DateUtil.beginOfMonth(DateUtil.lastMonth()).toString("yyyy-MM");
            bizDate = DateUtil.beginOfMonth(new Date()).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(config.getAppid());
        articleInfo.setTitle(context.getMessageTitle());
        articleInfo.setDescription(context.getMessageDesc());
        articleInfo.setPagepath(NoticeMessageUtil.buildMiniAppUrl(NoticeMessageTypeEnum.MATERIAL_REPORT_NOTIFY, context.extendParams(context.getMainStoreId())));
        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;
    }

}
