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

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rongwei.bscommon.sys.dao.CommonDao;
import com.rongwei.bscommon.sys.dao.EquOverhaulPlanningTasksMapperDao;
import com.rongwei.bscommon.sys.service.EquOverhaulPlanningTasksService;
import com.rongwei.bscommon.sys.service.EquipmentSendNotifyService;
import com.rongwei.bscommon.sys.utils.*;
import com.rongwei.bsentity.domain.EquOverhaulPlanningTasksDo;
import com.rongwei.bsentity.domain.EquOverhaulPlanningTasksVo;
import com.rongwei.rwadmincommon.system.domain.SysDictDo;
import com.rongwei.rwadmincommon.system.service.SysDictService;
import com.rongwei.rwadmincommon.system.vo.SysOrganizationVo;
import com.rongwei.rwadmincommon.system.vo.SysUserVo;
import com.rongwei.rwcommon.base.R;
import com.rongwei.rwcommon.utils.SecurityUtil;
import com.rongwei.rwcommon.utils.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.rongwei.safecommon.utils.SaveConstans.FileName.PLANNING_TASK_FILE_NAME;

/**
 * <p>
 * 设备子系统——大修计划任务 服务实现类
 * </p>
 *
 * @author fpy
 * @since 2023-12-20
 */
@Service
public class EquOverhaulPlanningTasksServiceImpl extends ServiceImpl<EquOverhaulPlanningTasksMapperDao, EquOverhaulPlanningTasksDo> implements EquOverhaulPlanningTasksService {

    @Autowired
    private EquOverhaulPlanningTasksService equOverhaulPlanningTasksService;

    @Autowired
    private EquipmentSendNotifyService equipmentSendNotifyService;

    @Autowired
    private EquOverhaulPlanningTasksMapperDao equOverhaulPlanningTasksMapperDao;

    @Autowired
    private CommonDao commonDao;

    @Autowired
    private SysDictService sysDictService;

    @Override
    public R importEquOverhaulPlanningTasks(MultipartFile file) {
        try {
            // 查询所有工厂数据
            List<SysOrganizationVo> factoryList = commonDao.getAllFactoryNameAndId();
            SysUserVo currentUser = CommonUtils.getCurrentUser();
            StringBuilder allStrBuilder = new StringBuilder();
            Sheet sheet = new XSSFWorkbook(file.getInputStream()).getSheetAt(0);
            int lastRowNum = sheet.getLastRowNum();
            List<EquOverhaulPlanningTasksDo> equOverhaulPlanningTasksDos = new ArrayList<>();
            for (int i = 1; i <= lastRowNum; i++) {
                StringBuilder stringBuilder = new StringBuilder();
                String taskNumber = "";
                String factoryId = currentUser.getOrganizationDoList().get(0).getFullpid().split(",")[1];
                List<SysOrganizationVo> resultList = factoryList.stream().filter(p -> p.getId().equals(factoryId)).collect(Collectors.toList());
                String factory = resultList.get(0).getFullname();
                EquOverhaulPlanningTasksDo equOverhaulPlanningTasksDo = new EquOverhaulPlanningTasksDo();
                Row row = sheet.getRow(i);
                if (ExcelUtils.isRowEmpty(row)){
                    continue;
                }
                String year = row.getCell(0) == null ? "" : row.getCell(0).toString().trim();
                String dept = row.getCell(1) == null ? "" : row.getCell(1).toString().trim();
                String equName = row.getCell(2) == null ? "" : row.getCell(2).toString().trim();
                String equNumber = row.getCell(3) == null ? "" : row.getCell(3).toString().trim();
                String repairReason = row.getCell(4) == null ? "" : row.getCell(4).toString().trim();
                Date planStartDate = row.getCell(5) == null ? null : DateUtils.importExcelFormatExcel((XSSFCell) row.getCell(5));
                Date planEndDate = row.getCell(6) == null ? null : DateUtils.importExcelFormatExcel((XSSFCell) row.getCell(6));
                String repairProgramme = row.getCell(7) == null ? "" : row.getCell(7).toString().trim();
                String isDangerous = row.getCell(8) == null ? "" : row.getCell(8).toString().trim();
                String isOutsourcing = row.getCell(9) == null ? "" : row.getCell(9).toString().trim();
                String header = row.getCell(10) == null ? "" : row.getCell(10).toString().trim();
                String others = row.getCell(11) == null ? "" : row.getCell(11).toString().trim();
                String taskStatus = row.getCell(12) == null ? "" : row.getCell(12).toString().trim();
                if (StringUtils.isBlank(year)){
                    stringBuilder.append("年度必填");
                }else {
                    year = StringUtil.formatDecimal(year);
                }
                if (StringUtils.isBlank(equName)){
                    stringBuilder.append("设备名称必填");
                }
                if (StringUtils.isBlank(equNumber)){
                    stringBuilder.append("设备编号必填");
                }
                if (StringUtil.isNotBlank(stringBuilder)) {
                    allStrBuilder.append("第").append(i + 1).append("行").append(stringBuilder).append("<br>");
                }else {
                    equOverhaulPlanningTasksDo.setId(SecurityUtil.getUUID())
                            .setYear(year)
                            .setTasknumber(taskNumber)
                            .setBelongfactory(factory)
                            .setEquipmentworkshop(dept)
                            .setEquipment(equName)
                            .setEquipmentnumber(equNumber)
                            .setRepairpreason(repairReason)
                            .setPlanstarttime(planStartDate)
                            .setPlanendtime(planEndDate)
                            .setIsdangerousoperations(isDangerous)
                            .setIsoutsourcing(isOutsourcing)
                            .setRepairhead(header)
                            .setOtherrepairengineer(others)
                            .setTenantid(factoryId)
                            .setRepairillustrate(repairProgramme)
                            .setTaskstatus(taskStatus);
                    equOverhaulPlanningTasksDos.add(equOverhaulPlanningTasksDo);
                }
            }
            String errMsg = allStrBuilder.toString();
            if (StringUtils.isNotBlank(errMsg)){
                return R.error(errMsg);
            }else {
                if (equOverhaulPlanningTasksDos.size()>0){
                    equOverhaulPlanningTasksService.saveOrUpdateBatch(equOverhaulPlanningTasksDos);
                }
            }
        } catch (IOException e) {
            ExceptionUtils.printExceptionDetail(e,"大修计划任务导入异常");
        }
        return R.ok();
    }

    @Override
    public R sendPlanTaskNotify(HttpServletResponse response) {
        List<SysDictDo> taskByType = sysDictService.getDictsByType("task_state");
        List<SysDictDo> ynByType = sysDictService.getDictsByType("srm_yn");
        List<EquOverhaulPlanningTasksVo> equOverhaulPlanningTasksDos = equOverhaulPlanningTasksMapperDao.selectAllOverdueTaskQuantity();
        if (equOverhaulPlanningTasksDos.size()>0){
            //提前删除大修任务超期提醒
            equipmentSendNotifyService.deletePlanningTasksNotify();
        }
        for (EquOverhaulPlanningTasksVo planningTasksVo:equOverhaulPlanningTasksDos){
            if (planningTasksVo.getTaskquantity()>0){
                List<EquOverhaulPlanningTasksVo> tasksVos = equOverhaulPlanningTasksMapperDao.selectTasksByFactoryId(planningTasksVo.getTenantid());
                try {
                    // 读取模板文件
                    TemplateExportParams params = new TemplateExportParams("template/大修任务超期未完成.xlsx",0);
                    Map<String, Object> dataMap = new HashMap<>(16);
                    List<Map<String,Object>> dataList = new ArrayList<>();
                    List<String> workShopUserIds = new ArrayList<>();
                    // 发送人
                    List<String> userId = new ArrayList<>();
                    for (EquOverhaulPlanningTasksVo equLubricationTaskDetailVo : tasksVos) {
                        if (StringUtils.isNotBlank(equLubricationTaskDetailVo.getEquipmentworkshopid())){
                            workShopUserIds.add("'"+equLubricationTaskDetailVo.getEquipmentworkshopid()+"'");
                        }
                        String taskStatus = "";
                        if (org.apache.commons.lang.StringUtils.isNotBlank(equLubricationTaskDetailVo.getTaskstatus())) {
                            taskStatus = taskByType.stream().filter(dictDo -> equLubricationTaskDetailVo.getTaskstatus().contains(dictDo.getValue()))
                                    .map(SysDictDo::getName).collect(Collectors.joining(","));
                            equLubricationTaskDetailVo.setTaskstatus(taskStatus);
                        }
                        String isHaltRepair = "";
                        if (org.apache.commons.lang.StringUtils.isNotBlank(equLubricationTaskDetailVo.getIshaltrepair())) {
                            isHaltRepair = ynByType.stream().filter(dictDo -> equLubricationTaskDetailVo.getIshaltrepair().contains(dictDo.getValue()))
                                    .map(SysDictDo::getName).collect(Collectors.joining(","));
                            equLubricationTaskDetailVo.setIshaltrepair(isHaltRepair);
                        }
                        String isOutSourcing = "";
                        if (org.apache.commons.lang.StringUtils.isNotBlank(equLubricationTaskDetailVo.getIsoutsourcing())) {
                            isOutSourcing = ynByType.stream().filter(dictDo -> equLubricationTaskDetailVo.getIsoutsourcing().contains(dictDo.getValue()))
                                    .map(SysDictDo::getName).collect(Collectors.joining(","));
                            equLubricationTaskDetailVo.setIsoutsourcing(isOutSourcing);
                        }
                        equLubricationTaskDetailVo.setShowPlanStartTime(TimeUtils.month2DateStr(equLubricationTaskDetailVo.getPlanstarttime()));
                        equLubricationTaskDetailVo.setShowPlanEndTime(TimeUtils.month2DateStr(equLubricationTaskDetailVo.getPlanendtime()));
                        dataList.add(JSONObject.parseObject(JSONObject.toJSONString(equLubricationTaskDetailVo), Map.class));
                    }
                    dataMap.put("list",dataList);
                    Workbook workbook = ExcelExportUtil.exportExcel(params,dataMap);
                    String fileItemId = ExcelUtils.workBookCommonUpload(workbook,  PLANNING_TASK_FILE_NAME.split("\\.")[0], "."+ PLANNING_TASK_FILE_NAME.split("\\.")[1]);
                    List<String> useDeptRoleUserIds = commonDao.getRoleUserIds("'lczg','wms'","so.id in ("+ workShopUserIds.stream().distinct().collect(Collectors.joining(","))+")");
                    List<String> factoryRoleUserIds = commonDao.getRoleUserIds("'hoed','edms'", "(so.FULLPID like '," + planningTasksVo.getTenantid() + "%' or so.ID='" + planningTasksVo.getTenantid() + "')");
                    if (useDeptRoleUserIds.size() > 0 && factoryRoleUserIds.size() > 0) {
                        userId = Stream.of(useDeptRoleUserIds, factoryRoleUserIds).flatMap(Collection::stream).distinct().collect(Collectors.toList());
                    } else if (useDeptRoleUserIds.size() == 0) {
                        userId = factoryRoleUserIds;
                    } else {
                        userId = useDeptRoleUserIds.stream().distinct().collect(Collectors.toList());
                    }
                    try {
                        equipmentSendNotifyService.sendPlanningTasksNotify(planningTasksVo.getBelongfactory(),planningTasksVo.getTaskquantity(), planningTasksVo.getId(),userId,fileItemId);
                    }catch (Exception e){
                        ExceptionUtils.printExceptionDetail(e,"发送消息异常");
                    }
                }catch (Exception e){
                    ExceptionUtils.printExceptionDetail(e,"读取模板异常");
                }
            }
        }
        return R.ok();
    }
}
