package com.rongwei.bscommon.sys.service.impl;

import com.rongwei.bscommon.sys.dao.EquipmentDisposeDao;
import com.rongwei.bscommon.sys.service.*;
import com.rongwei.bscommon.sys.utils.ExceptionUtils;
import com.rongwei.bsentity.domain.AspCheckItemsAreaDo;
import com.rongwei.bsentity.domain.EquDisposalRequestDo;
import com.rongwei.bsentity.dto.EquipmentDisposeDTO;
import com.rongwei.rwadmincommon.system.domain.SysUserDo;
import com.rongwei.rwcommon.base.R;
import com.rongwei.rwcommon.vo.MailDo;
import com.rongwei.safecommon.fegin.CXCommonFeginClient;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author shangmi
 * @title EquipmentArchivesServiceImpl
 * @date 2024/1/16 14:19
 * @description 设备档案
 */
@Service
public class EquipmentArchivesServiceImpl implements EquipmentArchivesService {

    private final String[] HANDLING_TYPE = {"10","20"};

    private final String[] OBJECT_TYPE = {"1","3"};

    @Autowired
    private AspCheckItemsService aspCheckItemsService;

    @Autowired
    private EquFrockListService equFrockListService;

    @Autowired
    private EquMaintenanceScheduleService maintenanceScheduleService;

    @Autowired
    private EquLubricationPlanService lubricationPlanService;

    @Autowired
    private AspCheckItemsAreaService checkItemsAreaService;

    @Autowired
    private EquipmentSendNotifyService sendNotifyService;

    @Autowired
    private EquipmentDisposeDao equipmentDisposeDao;

    @Autowired
    private CXCommonFeginClient cxCommonFeginClient;

    /**
     * 更新设备库
     *
     * @param equipmentDisposeDTO
     * @return {@link R}
     * @date 2024/1/16 17:43
     * @author shangmi
     *
     */

    @Override
    public R updateEquipmentData(EquipmentDisposeDTO equipmentDisposeDTO) {
        Date newDate = new Date();
        //处置状态  报废/移交
        boolean isState = HANDLING_TYPE[0].equals(equipmentDisposeDTO.getState());
        //对象类型  设备/工装
        boolean isObject = OBJECT_TYPE[0].equals(equipmentDisposeDTO.getObjectType());
        if (isState){
            //更新停用状态
            String equipmentId = equipmentDisposeDTO.getEquipmentId();
            if (isObject) {
                aspCheckItemsService.updateStateById(equipmentId,newDate);
                lubricationPlanService.updateStateByEquId(equipmentId);

                //设备报废审批通过生成一条提醒任务
                try {
                    sendNotifyService.equScrapAuditNotify(equipmentDisposeDTO);
                }catch (Exception e){
                    ExceptionUtils.printExceptionDetail(e,"发送设备报废审批通过提醒异常");
                }
            } else {
                equFrockListService.updateStateById(equipmentId,newDate);
            }
            maintenanceScheduleService.updateStateByEquId(equipmentId);

        }else {
            //修改组织结构
            if (isObject) {
                AspCheckItemsAreaDo checkItemsArea = checkItemsAreaService.getByDeptName(equipmentDisposeDTO.getRollInPlantId(), equipmentDisposeDTO.getRollInDept());
                aspCheckItemsService.updateSiteById(equipmentDisposeDTO,checkItemsArea);
            } else {
                equFrockListService.updateSiteById(equipmentDisposeDTO);
            }
        }
        return R.ok();
    }

    @Override
    public R sendEmail(Map<String, Object> myObject) {
        String type = (String) myObject.get("TYPE");//'1'为发起流程 or 退回重新发起流程、'2'流程中的节点
        if ("1".equals(type)){
            String id = (String) myObject.get("FORMID");
            EquDisposalRequestDo equDisposalRequestDo = equipmentDisposeDao.selectById(id);
            String mssmanagerid = equDisposalRequestDo.getMssmanagerid();//安全部部长id
            String workshop = equDisposalRequestDo.getWorkshop();//使用部门名称、车间
            String equipmentname = equDisposalRequestDo.getEquipmentName();//设备名称
            String equipmentnumber = equDisposalRequestDo.getEquipmentNumber();//设备编号

            //抄送人 id 数组处理
            String[] strArray = mssmanagerid.split(",");
            List<SysUserDo> emais = equipmentDisposeDao.selectEmailList(strArray);
            StringBuilder sb = new StringBuilder();
            for (SysUserDo user : emais) {
                // 从 SysUserDo 对象中获取邮件地址，并添加到字符串构建器中
                String emailAddress = user.getEmail();
                sb.append(emailAddress).append(",");
            }
            // 移除最后一个逗号
            if (sb.length() > 0) {
                sb.deleteCharAt(sb.length() - 1);
            }
            String[] filteredEmailArray = Arrays.stream(sb.toString().split(","))
                    .map(String::trim) // 去除每个邮件地址的前后空白
                    .filter(email -> !email.isEmpty()) // 过滤掉空字符串
                    .toArray(String[]::new); // 收集为字符串数组

            if (filteredEmailArray.length > 0) {
                MailDo mailDo = new MailDo();
                mailDo.setReceiveEmail(filteredEmailArray);
                mailDo.setNeedTransReceive(false);
                mailDo.setCcEmail(new String[]{});
                mailDo.setSubject("设备处置流程审批任务提醒");
                String content = "尊敬的各位领导，" +
                        "<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
                        "您有一个" + workshop + "的 " + equipmentname + "（" + equipmentnumber + "） 的设备处置审批任务，请及时到创新智慧工厂平台中的个人工作台中进行任务审批，若是未找到对应审批任务，则为某个领导已审批完成。可在对应APP端或者PC端进行任务审批" +
                        "<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
                        "系统登录地址： http://192.168.100.77/#/passport/login";
                mailDo.setContent(content);
                // 发送邮件
                R r = cxCommonFeginClient.sendHtmlMail(mailDo);
            } else {
                return R.error("汇报对象邮箱不能为空");
            }

        }else if ("2".equals(type)){
//            逻辑如下： 在流程的每个节点审批通过后 给下个环节的审批人员 发送 邮件提醒的功能
//            提醒信息： 尊敬的各位领导，您有一个【车间】的【设备名称（设备编号）】的设备处置审批任务，请及时到创新智慧工厂平台中的个人工作台中进行任务审批，若是未找到对应审批任务，则为某个领导已审批完成。可在对应APP端或者PC端进行任务审批
//            系统登录地址： 把内部的登录地址弄上
//            需发送邮件的提醒人：取下个环节的对应审批人，然后去重， 之后给这些人员发送邮件，没有邮箱的就不发送
//            注意：只发邮件，不生成提醒信息。
            String taskname = (String) myObject.get("taskname");
            String formId = (String) myObject.get("formId");
            //根据 formId 在EquipmentDisposeDTO 中获取数据
            EquDisposalRequestDo equDisposalRequestDo = equipmentDisposeDao.selectById(formId);
            String workshop = equDisposalRequestDo.getWorkshop();//使用部门名称、车间
            String equipmentname = equDisposalRequestDo.getEquipmentName();//设备名称
            String equipmentnumber = equDisposalRequestDo.getEquipmentNumber();//设备编号

            String recipient = "";
            if ("安全部".equals(taskname)){
                recipient = equDisposalRequestDo.getMtqmanagerid();
            } else if ("技质部".equals(taskname)) {
                recipient = equDisposalRequestDo.getEqumanagerid();
            } else if ("设备部".equals(taskname)) {
                recipient = equDisposalRequestDo.getWdmanagerid();
            } else if ("仓储部".equals(taskname)) {
                recipient = equDisposalRequestDo.getVicepresidentid();
            } else if ("副总经理".equals(taskname)) {
                recipient = equDisposalRequestDo.getGeneralmanagerid();
            } else if ("总经理".equals(taskname)) {
                recipient = equDisposalRequestDo.getFinanceofficeid();
            }
            String[] strArray = recipient.split(",");
            List<SysUserDo> emais = equipmentDisposeDao.selectEmailList(strArray);
            StringBuilder sb = new StringBuilder();
            for (SysUserDo user : emais) {
                // 从 SysUserDo 对象中获取邮件地址，并添加到字符串构建器中
                String emailAddress = user.getEmail();
                sb.append(emailAddress).append(",");
            }
            // 移除最后一个逗号
            if (sb.length() > 0) {
                sb.deleteCharAt(sb.length() - 1);
            }
            String[] filteredEmailArray = Arrays.stream(sb.toString().split(","))
                    .map(String::trim) // 去除每个邮件地址的前后空白
                    .filter(email -> !email.isEmpty()) // 过滤掉空字符串
                    .toArray(String[]::new); // 收集为字符串数组
            if (filteredEmailArray.length > 0) {
                MailDo mailDo = new MailDo();
                mailDo.setReceiveEmail(filteredEmailArray);
                mailDo.setNeedTransReceive(false);
                mailDo.setCcEmail(new String[]{});
                mailDo.setSubject("设备处置流程审批任务提醒");
                String content = "尊敬的各位领导，" +
                        "<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
                        "您有一个" + workshop + "的 " + equipmentname + "（" + equipmentnumber + "） 的设备处置审批任务，请及时到创新智慧工厂平台中的个人工作台中进行任务审批，若是未找到对应审批任务，则为某个领导已审批完成。可在对应APP端或者PC端进行任务审批" +
                        "<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
                        "系统登录地址： http://192.168.100.77/#/passport/login";
                mailDo.setContent(content);
                // 发送邮件
                R r = cxCommonFeginClient.sendHtmlMail(mailDo);
            } else {
                return R.error("汇报对象邮箱不能为空");
            }
        }
        return R.ok();
    }
}
