package cn.estsh.i3plus.ext.mes.apiservice.serviceimpl.busi.bu3;

import cn.estsh.i3plus.ext.mes.api.busi.bu3.ISxProdDataPushNotifyStrategyFlagService;
import cn.estsh.i3plus.ext.mes.icloud.sdk.ICoreSysUserExtCloud;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesAssistOutAndEnter;
import cn.estsh.i3plus.ext.mes.pojo.model.bu3.SxPushDataNotifyParamAssistModel;
import cn.estsh.i3plus.ext.mes.pojo.model.bu3.SxPushDataNotifyParamModel;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtConstWords;
import cn.estsh.i3plus.pojo.base.bean.BaseResultBean;
import cn.estsh.i3plus.pojo.model.platform.PushDataNotifyModel;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

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

/**
 * @Description 援入援出邮件通知:本月所有未确认数据明细推送至担当和责任人
 * @author jiaqi.hou
 * @date 2023-08-16 16:43
 **/
@Slf4j
@Service
public class SxProdDataPushNotifyStrategyAssistTenService implements ISxProdDataPushNotifyStrategyFlagService {

    @Autowired
    private SxProdDataPushNotifyStrategyFileCommonService strategyFileCommonService;

    @Autowired
    private ICoreSysUserExtCloud iCoreSysUserExtCloud;

    @Override
    public List<PushDataNotifyModel> exec(PushDataNotifyModel data, SxPushDataNotifyParamModel pushParam, Object... obj) {

        log.info("援入援出邮件通知:本月所有未确认数据明细推送至担当和责任人 --- SxProdDataPushNotifyStrategyAssistTenService --- START --- DATA:{} --- THREAD:{}", JSONObject.toJSONString(data), Thread.currentThread().getName());

        SxPushDataNotifyParamAssistModel param = (SxPushDataNotifyParamAssistModel) pushParam;

        List<MesAssistOutAndEnter> dataDbList = (List<MesAssistOutAndEnter>) obj[0];
        if (CollectionUtils.isEmpty(dataDbList)) return null;

        //根据责任部门分组
        Map<String, List<MesAssistOutAndEnter>> ownerDeptMap = dataDbList.stream().filter(x -> !StringUtils.isEmpty(x.getOwnerDepartment()))
                .collect(Collectors.groupingBy(MesAssistOutAndEnter::getOwnerDepartment));

        List<PushDataNotifyModel> resultList = new ArrayList<>();

        String title;

        //获取用户邮箱
        Map<String,String> userEmailsMap;
        try {
            BaseResultBean baseResultBean = iCoreSysUserExtCloud.queryUserInOrg(pushParam.getOrganizeCode());
            if (!baseResultBean.success){
                log.info("邮件推送:本月所有未确认数据明细推送至担当和责任人 --- SxProdDataPushNotifyStrategyAssistTenService --- ERROR --- 获取用户邮箱失败 PARAMS:{} --- 原因:[{}] --- THREAD:{}", pushParam.getOrganizeCode(), baseResultBean.errorMsg, Thread.currentThread().getName());
                return null;
            }
            List<Map<String,Object>> userInfoList = (List<Map<String,Object>>) baseResultBean.getResultList();
            if (!CollectionUtils.isEmpty(userInfoList)){
                userEmailsMap = new HashMap<>();
                for (Map<String, Object> map : userInfoList) {
                    userEmailsMap.put(map.get(MesExtConstWords.USER_LOGIN_NAME).toString(),StringUtils.isEmpty(map.get("userEmail"))? "" : map.get("userEmail").toString());
                }
            }else {
                log.info("邮件推送:本月所有未确认数据明细推送至担当和责任人 --- SxProdDataPushNotifyStrategyAssistTenService --- ERROR --- 未查找到用户信息 PARAMS:{} --- THREAD:{}", pushParam.getOrganizeCode(), Thread.currentThread().getName());
                return null;
            }
        } catch (Exception e) {
            log.info("邮件推送:本月所有未确认数据明细推送至担当和责任人 --- SxProdDataPushNotifyStrategyAssistTenService --- ERROR --- 获取用户邮箱失败 PARAMS:{}  --- 原因:[{}] --- THREAD:{}", pushParam.getOrganizeCode(), e.getMessage(), Thread.currentThread().getName());
            return null;
        }

        PushDataNotifyModel resultData;
        String userEmails;
        for (Map.Entry<String, List<MesAssistOutAndEnter>> entry : ownerDeptMap.entrySet()) {
            userEmails = getUserNames(entry,userEmailsMap);
            if (StringUtils.isEmpty(userEmails)) continue;
            resultData = new PushDataNotifyModel();
            title = String.format("援入援出[%s]月责任部门[%s]明细报表",dataDbList.get(0).getInfluenceDate().substring(5, 7),entry.getKey());
            PushDataNotifyModel file = strategyFileCommonService.exec(data, pushParam, entry.getValue(), MesExtConstWords.SX_ASSIST_PUSH_NOTIFY_REPORT, title);
            List<String> dataList = new ArrayList<>();
            dataList.add(title+",详情见附件");
            resultData.addListMail(dataList)
                    .userNames(userEmails)
                    .fileId(file.getFileId())
                    .title(title);
            resultList.add(resultData);
        }
        log.info("援入援出邮件通知:本月所有未确认数据明细推送至担当和责任人 --- SxProdDataPushNotifyStrategyAssistTenService --- END --- DATA:{} --- THREAD:{}", JSONObject.toJSONString(data), Thread.currentThread().getName());

        return resultList;
    }

    private static String getUserNames(Map.Entry<String, List<MesAssistOutAndEnter>> entry, Map<String,String> userEmailsMap) {
        Set<String> resultSet = new HashSet<>();
        resultSet.addAll(entry.getValue().stream().map(MesAssistOutAndEnter::getTakeOn).filter(x -> !StringUtils.isEmpty(x)).collect(Collectors.toSet()));
        resultSet.addAll(entry.getValue().stream().map(MesAssistOutAndEnter::getPersonResponsible).filter(x -> !StringUtils.isEmpty(x)).collect(Collectors.toSet()));
        StringBuilder userEmails = new StringBuilder();
        Set<String> userLoginNameSet = new HashSet<>();
        for (String userLoginName : resultSet) {
            userLoginNameSet.addAll(Arrays.asList(userLoginName.split(",")));
        }
        for (String userLoginName : userLoginNameSet) {
            if (userEmailsMap.containsKey(userLoginName) && !StringUtils.isEmpty(userEmailsMap.get(userLoginName))) userEmails.append(userEmailsMap.get(userLoginName)).append(",");
        }
        if (StringUtils.isEmpty(userEmails.toString())) log.info("邮件推送:本月所有未确认数据明细推送至担当和责任人 --- SxProdDataPushNotifyStrategyAssistTenService --- ERROR --- 未查找到用户邮箱 --- 用户:[{}] --- THREAD:{}", resultSet, Thread.currentThread().getName());
        return org.apache.commons.lang3.StringUtils.isEmpty(userEmails) ? "" : userEmails.substring(0,userEmails.length()-1);
    }
}
