package com.ruoyi.project.production.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.stuxuhai.jpinyin.PinyinException;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.sendEmail.IMailService;
import com.ruoyi.common.thread.Trainning.MeetingInvitationMailThread;
import com.ruoyi.common.thread.sai.SaiApplyMailThread;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.file.ExcelUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.interceptor.annotation.RepeatSubmit;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.security.service.TokenService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.PageDomain;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.framework.web.page.TableSupport;
import com.ruoyi.project.approve.damain.DevTask;
import com.ruoyi.project.plant.domain.TStaffmgr;
import com.ruoyi.project.plant.service.ITStaffmgrService;
import com.ruoyi.project.process.domain.TMoc;
import com.ruoyi.project.production.controller.vo.SaiApplyExportVO;
import com.ruoyi.project.production.controller.vo.SaiApplyQueryVO;
import com.ruoyi.project.production.domain.TSaiApply;
import com.ruoyi.project.production.domain.TSaiApproveFile;
import com.ruoyi.project.production.domain.TSaiCategory;
import com.ruoyi.project.production.mapper.TSaiApplyMapper;
import com.ruoyi.project.production.service.ITSaiApplyService;
import com.ruoyi.project.production.service.ITSaiApproveFileService;
import com.ruoyi.project.production.service.ITSaiCategoryService;
import com.ruoyi.project.sems.domain.TApproverFile;
import com.ruoyi.project.system.domain.*;
import com.ruoyi.project.system.mapper.SysDeptMapper;
import com.ruoyi.project.system.mapper.SysUserMapper;
import com.ruoyi.project.system.service.ISysDeptService;
import com.ruoyi.project.system.service.ISysDictTypeService;
import com.ruoyi.project.system.service.ISysMessageService;
import com.ruoyi.project.system.service.ISysUserService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.Email;
import javax.validation.constraints.Size;
import java.io.IOException;
import java.sql.Array;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * SAI开项管理Controller
 *
 * @author ruoyi
 * @date 2023-03-15
 */
@RestController
@RequestMapping("/production/apply")
public class TSaiApplyController extends BaseController
{
    @Autowired
    private ITSaiApplyService tSaiApplyService;

    @Autowired
    private TSaiApplyMapper tSaiApplyMapper;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;

    @Autowired
    private ITSaiApproveFileService saiApproveFileService;

    @Autowired
    private ITStaffmgrService staffmgrService;

    @Autowired
    private ISysMessageService sysMessageService;

    @Autowired
    private IMailService mailService;

    @Autowired
    private ITSaiCategoryService tSaiCategoryService;

    //四个班组当年提交的SAI数量（图）
    @PreAuthorize("@ss.hasPermi('production:apply:list')")
    @GetMapping("/teamAnalysis")
    public AjaxResult teamAnalysis()
    {
        List<TSaiApply> list = tSaiApplyMapper.selectTeamAnalysis();
        return AjaxResult.success(list);
    }

    //个人提交数量数据分析图（图）
    @PreAuthorize("@ss.hasPermi('production:apply:list')")
    @GetMapping("/personalAnalysis")
    public AjaxResult personalAnalysis()
    {
        List<TSaiApply> list = tSaiApplyMapper.selectPersonalAnalysis();
        return AjaxResult.success(list);
    }

    /**
     * 查询SAI开项管理列表
     */
    @PreAuthorize("@ss.hasPermi('production:apply:list')")
    @GetMapping("/list")
    public TableDataInfo list(SaiApplyQueryVO tSaiApply)
    {
        tSaiApply.setCurrentUser(getUserId());
        tSaiApply.setSpecialRole(this.isSpecialRole());
        startPage();
        List<TSaiApply> list = tSaiApplyService.selectTSaiApplyList(tSaiApply);
        return getDataTable(list);
    }

    /**
     * 当前登录用户是否为特殊角色（供SAI功能展示使用）
     *
     * @return 是否为特殊角色
     */
    private boolean isSpecialRole() {
        boolean isSpecialRole = false;
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        List<SysRole> roles = user.getRoles();
        for (SysRole role : roles) {
            Long roleId = role.getRoleId();
            if (roleId.toString().equals("23140")) {
                isSpecialRole = true;
            }
        }
        return isSpecialRole;
    }

    /**
     * 批量导入SAI开项管理列表
     */
    @PreAuthorize("@ss.hasPermi('production:apply:add')")
    @PostMapping("/importData")
    public AjaxResult importData(@RequestParam("file") MultipartFile file) throws IOException
    {
        //获取操作人员ID
        Long userId = getUserId();
        //报错行数统计
        List<Integer> failRow =new ArrayList<Integer>();
        Workbook workbook = ExcelUtils.getWorkBook(file);
        Sheet sheet = workbook.getSheetAt(0);
        List<TSaiApply> list = new ArrayList<TSaiApply>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // 字典查询
        List<SysDictData> saiApplyStatusDict = iSysDictTypeService.selectDictDataByType("SAI_APPLY_STATUS");
        List<SysDictData> teamDivideDict = iSysDictTypeService.selectDictDataByType("TEAM_DIVIDE");
        // 部门列表
        List<SysDept> deptList = deptService.selectDeptList(new SysDept());
        // 用户列表
        List<SysUser> userList = userService.selectUserList(new SysUser());
        int rowNum = sheet.getPhysicalNumberOfRows();
        int failNumber = 0;
        for (int i = 2; i <= rowNum; i++) {
            try {
                logger.info("读取行数：" + i);
                Row row = sheet.getRow(i);
                int cellNum = row.getLastCellNum();
                TSaiApply entity = new TSaiApply();
                entity.setCreateTime(new Date());
                entity.setCreateBy(userId.toString());
                entity.setDeptId(103L);
                for (int j = 0; j < cellNum; j++) {
                    Cell cell = row.getCell(j);
                    //  cell.setCellType(CellType.STRING);
                    String cellValue = ExcelUtils.getCellValue(cell);
                    String applicantName = "";
                    String handlerName = "";
                    String executorName = "";
                    logger.info("cellValue:" + cellValue);
                    if (j == 0) {
                        entity.setDescription(cellValue);
                    } else if (j == 1) {
                        for (SysDictData sysDictData : saiApplyStatusDict) {
                            if (sysDictData.getDictLabel().equals(cellValue.trim())) {
                                entity.setApplyStatus(Long.valueOf(sysDictData.getDictValue()));
                            }
                        }
                    } else if (j == 2) {
                        if (cellValue != "" && cellValue != null) {
                            for (SysDept sysDept : deptList) {
                                if (cellValue.equals(sysDept.getDeptName())) {
                                    entity.setApplicantDept(sysDept.getDeptId().toString());
                                }
                            }
                        }
                    } else if (j == 3) {
                        for (SysDictData sysDictData : teamDivideDict) {
                            if (sysDictData.getDictLabel().equals(cellValue.trim())) {
                                entity.setApplicantTeam(sysDictData.getDictValue());
                            }
                        }
                    } else if (j == 4) {
                        applicantName = cellValue;
                    } else if (j == 5) {
                        handlerName = cellValue;
                    } else if (j == 6) {
                        executorName = cellValue;
                    } else if (j == 7) {
                        if (cellValue.length() > 3) {
                            entity.setApplyDate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                        }
                    } else if (j == 8) {
                        if (cellValue.length() > 3) {
                            entity.setEstimateFinishDate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                        }
                    } else if (j == 9) {
                        if (cellValue.length() > 3) {
                            entity.setActualFinishDate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                        }
                    } else if (j == 10) {
                        if (cellValue != "" && cellValue != null) {
                            entity.setIsRecorded(cellValue == "是" ? 1L : 0L);
                        }
                    } else if (j == 11) {
                        entity.setRecordNo(cellValue);
                    }
                    for (SysUser sysUser : userList) {
                        if (applicantName != "" && applicantName != null) {
                            if (applicantName.equals(sysUser.getNickName())) {
                                entity.setApplicant(sysUser.getUserId().toString());
                            }
                        }
                        if (handlerName != "" && handlerName != null) {
                            if (handlerName.equals(sysUser.getNickName())) {
                                entity.setHandler(sysUser.getUserId().toString());
                            }
                        }
                        if (executorName != "" && executorName != null) {
                            if (executorName.equals(sysUser.getNickName())) {
                                entity.setExecutor(sysUser.getUserId().toString());
                            }
                        }
                    }
                }
                logger.info("entity:" + entity);
                list.add(entity);
            }catch (Exception e){
                failNumber++;
                failRow.add(i+1);
            }
        }
        int successNumber = 0;
        int failNum = 0;
        for (TSaiApply t : list
        ) {
            failNum++;
            try {
                tSaiApplyService.insertTSaiApply(t);
                successNumber++;
            }catch (Exception e){
                failNumber++;
                logger.info("e:" + e);
                failRow.add(failNum+1);
            }
        }
        logger.info("list:" + JSON.toJSONString(list));
        logger.info("successNumber:" +String.valueOf(successNumber));
        logger.info("failNumber:" +String.valueOf(failNumber));
        logger.info("failRow:" +String.valueOf(failRow));
        return AjaxResult.success(String.valueOf(successNumber), failRow);
    }

    /**
     * 导出SAI开项管理列表
     */
    @PreAuthorize("@ss.hasPermi('production:apply:export')")
    @Log(title = "SAI开项管理", businessType = BusinessType.EXPORT)
    @PutMapping("/export")
    public AjaxResult export(@RequestBody SaiApplyQueryVO tSaiApply)
    {
        List<SysUser> userList = userService.selectUserList(new SysUser());
        Map<Long, String> nameMap = new HashMap<Long, String>();
        Map<Long, String> staffIdMap = new HashMap<Long, String>();
        for (SysUser sysUser : userList) {
            nameMap.put(sysUser.getUserId(), sysUser.getNickName());
            staffIdMap.put(sysUser.getUserId(), sysUser.getStaffId());
        }
        // 实体类集合
        List<TSaiApply> list = tSaiApplyService.selectTSaiApplyList(tSaiApply);
        // 导出VO集合
        List<SaiApplyExportVO> exportVOList = new ArrayList<>();
        // 字典查询
        List<SysDictData> saiApplyStatusDict = iSysDictTypeService.selectDictDataByType("SAI_APPLY_STATUS");
        List<SysDictData> teamDivideDict = iSysDictTypeService.selectDictDataByType("TEAM_DIVIDE");
        List<SysDictData> saiUnsafeStatusDict = iSysDictTypeService.selectDictDataByType("SAI_UNSAFE_STATUS");
        List<SysDictData> saiUnsafeActionDict = iSysDictTypeService.selectDictDataByType("SAI_UNSAFE_ACTION");
        List<TSaiCategory> tSaiCategories = tSaiCategoryService.selectTSaiCategoryList(null);
        Map<Long, String> categoryMap = tSaiCategories.stream().collect(Collectors.toMap(TSaiCategory::getSaiCategoryId, TSaiCategory::getSaiCategoryName));
        int no = 0;  // 序号
        for (TSaiApply entity : list) {
            no++;
            // 复制属性
            SaiApplyExportVO vo = new SaiApplyExportVO();
            vo.setNo(no + "");
            vo.setPlantName(entity.getApplicantDeptName());
            vo.setStaffName(entity.getApplicantName());
            vo.setStaffId(staffIdMap.get(Long.parseLong(entity.getApplicant())));
            vo.setApplyDate(entity.getApplyDate());
//            vo.setMonth((entity.getApplyDate().getMonth() + 1) + "");
//            vo.setDate(entity.getApplyDate().getDate()+ "");
            for (SysDictData sysDictData : teamDivideDict) {
                if (sysDictData.getDictValue().equals(entity.getApplicantTeam() + "")) {
                    vo.setStaffTeam(sysDictData.getDictLabel());
                }
            }
            for (SysDictData sysDictData : saiUnsafeStatusDict) {
                if (sysDictData.getDictValue().equals(entity.getUnsafeStatus() + "")) {
                    vo.setUnsafeStatus(sysDictData.getDictLabel());
                }
            }
            for (SysDictData sysDictData : saiUnsafeActionDict) {
                if (sysDictData.getDictValue().equals(entity.getUnsafeAction() + "")) {
                    vo.setUnsafeAction(sysDictData.getDictLabel());
                }
            }
            vo.setDescription(entity.getDescription());
            vo.setReaction(entity.getReaction());
            vo.setExecutor(entity.getExecutorName());
            vo.setEstimateFinishDate(entity.getEstimateFinishDate());
            vo.setActualFinishDate(entity.getActualFinishDate());
            Long isRecorded = entity.getIsRecorded();
            if (isRecorded != null) {
                vo.setIsRecorded(isRecorded == 1L ? "是" : "否");
            }
            String inspectors = entity.getInspectors();
            if (inspectors != null && !"".equals(inspectors) && !"null".equals(inspectors)) {
                if (inspectors.indexOf(",") != -1) {
                    String[] split = inspectors.split(",");
                    String inspectorName = "";
                    for (int i = 0; i < split.length; i++) {
                        if (split[i] != null && !"null".equals(split[i])) {
                            inspectorName += nameMap.get(Long.parseLong(split[i]));
                            if (i < split.length - 1) {
                                inspectorName += ",";
                            }
                        }
                    }
                    vo.setInspectors(inspectorName);
                } else {
                    vo.setInspectors(nameMap.get(Long.parseLong(inspectors)));
                }
            }
            vo.setValidateDate(entity.getActualFinishDate());
            for (SysDictData sysDictData : saiApplyStatusDict) {
                if (sysDictData.getDictValue().equals(entity.getApplyStatus() + "")) {
                    vo.setApplyStatus(sysDictData.getDictLabel());
                }
            }
            vo.setRemarks(entity.getRemarks());
            vo.setRemark(null);
            vo.setSaiLevel(entity.getSaiLevel());
            for (Long key : categoryMap.keySet()) {
                if (key.toString().equals(entity.getCategory())) {
                    vo.setCategory(categoryMap.get(key));
                }
            }
            exportVOList.add(vo);
        }
        ExcelUtil<SaiApplyExportVO> util = new ExcelUtil<SaiApplyExportVO>(SaiApplyExportVO.class);
        return util.exportExcel(exportVOList, "SAI开项管理数据");
    }

    /**
     * 获取SAI开项管理详细信息
     */
//    @PreAuthorize("@ss.hasPermi('production:apply:query')")
    @GetMapping(value = "/{saiApplyId}")
    public AjaxResult getInfo(@PathVariable("saiApplyId") Long saiApplyId)
    {
        TSaiApply tSaiApply = tSaiApplyService.selectTSaiApplyById(saiApplyId);
        TSaiApproveFile tSaiApproveFile = new TSaiApproveFile();
        tSaiApproveFile.setApproveId(saiApplyId);
        tSaiApply.setFiles(saiApproveFileService.selectTSaiApproveFileList(tSaiApproveFile));
        return AjaxResult.success(tSaiApply);
    }

    /**
     * 新增SAI开项管理
     */
    @PreAuthorize("@ss.hasPermi('production:apply:add')")
    @Log(title = "SAI开项管理申请", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TSaiApply tSaiApply)
    {
        String userId = getUserId().toString();
        tSaiApply.setCreateTime(new Date());
        tSaiApply.setCreateBy(userId);
        tSaiApply.setDeptId(103L);
        tSaiApply.setApplyStatus(0);
        tSaiApply.setHandler(tSaiApply.getApplicant());
        tSaiApplyService.insertTSaiApply(tSaiApply);
        if (tSaiApply.getFiles().size() > 0) {
            for (TSaiApproveFile t : tSaiApply.getFiles()
            ) {
                t.setApproveId(tSaiApply.getSaiApplyId());
                saiApproveFileService.save(t);
            }
        }
        return AjaxResult.success();
    }

    /**
     * 保存并提交申请
     */
    @PreAuthorize("@ss.hasPermi('production:apply:add')")
    @Log(title = "SAI开项管理申请", businessType = BusinessType.INSERT)
    @PostMapping("/saveAndSubmitApply")
    public AjaxResult saveAndSubmitApply(@RequestBody TSaiApply tSaiApply)
    {
        if (tSaiApply.getSaiApplyId() != null) {
            this.edit(tSaiApply);
        } else {
            this.add(tSaiApply);
        }
        return AjaxResult.success(this.submit(tSaiApply.getSaiApplyId()));
    }

    /**
     * SAI开项管理提交申请
     */
    @PreAuthorize("@ss.hasPermi('production:apply:edit')")
    @Log(title = "SAI开项管理申请", businessType = BusinessType.INSERT)
    @PutMapping(value = "/submit/{saiApplyId}")
    public AjaxResult submit(@PathVariable("saiApplyId") Long saiApplyId)
    {
        // 当前登录用户userId
        String userId = getUserId().toString();
        // SAI开项管理对象
        TSaiApply tSaiApply = tSaiApplyService.selectTSaiApplyById(saiApplyId);
        tSaiApply.setApplyStatus(1);
        Date date = new Date();
        date.setDate(date.getDate() + 7);
        tSaiApply.setEstimateFinishDate(date);
        tSaiApply.setAssessor("20276");
        tSaiApply.setHandler("20276");
        // 开始申请流程
        tSaiApply.setApNo(DateUtils.dateTimeNow() + userId);
        Authentication.setAuthenticatedUserId(userId);//设置当前申请人
        // 声明流程变量集合
        Map<String, Object> variables = new HashMap<>();
        variables.put("assessor", "20276");
        // 流程businessKey = SAI开项管理对象saiApplyId
        long businessKey = saiApplyId;
        // 采用key来启动流程定义并设置流程变量，返回流程实例
        ProcessInstance pi = runtimeService.startProcessInstanceByKey("saiApplyProcess", String.valueOf(businessKey), variables);
        logger.info("流程定义id：" + pi.getProcessDefinitionId());
        logger.info("流程实例id：" + pi.getProcessInstanceId());
        // SAI开项管理对象processId = 流程实例id
        tSaiApply.setProcessId(pi.getProcessInstanceId());
        // 标记taskId、TaskName
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        List<Task> list = processEngine.getTaskService()//获取任务service
                .createTaskQuery()//创建查询对象
                .taskCandidateOrAssigned("20276").list();
        for (Task task : list) {
            if (tSaiApply.getProcessId().equals(task.getProcessInstanceId())) {
                tSaiApply.setTaskId(task.getId());
                tSaiApply.setTaskName(task.getName());
            }
        }
        // 更新操作
        tSaiApplyService.updateTSaiApply(tSaiApply);
        return AjaxResult.success();
    }

    /**
     * SAI开项管理申请处理
     *
     * @param devTask
     * @return
     */
    @Log(title = "SAI开项管理申请处理", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping("/handle")
    public AjaxResult handle(@RequestBody DevTask devTask) throws PinyinException {
        //更新数据
        TSaiApply form = devTask.getSaiApply();
        //使用任务服务完成任务(提交任务)
        String taskId = devTask.getSaiApply().getTaskId();
        // 使用任务id,获取任务对象，获取流程实例id
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        //利用任务对象，获取流程实例id
        String processInstancesId = task.getProcessInstanceId();
        // 声明流程变量集合
        Map<String, Object> param = new HashMap<>();
        String condition = devTask.getCondition();
        param.put("condition", condition);
        // 下一任务执行人userId
        String nextHandler = null;
        // 审批意见
        String comment = "";
        switch (condition) {
            case "0":
                comment = "取消";
                break;
            case "1":
                comment = "通过";
                break;
            case "2":
                comment = "驳回";
                break;
        }
        // 根据实例名判断当前流程节点
        switch (task.getName()) {
            case "评估":
                if ("1".equals(condition)) {
                    form.setApplyStatus(2);
                    String executor = form.getExecutor();
                    if (!"20276".equals(form.getExecutor())) {
                        executor = form.getExecutor() + ",20276";
                    }
                    param.put("executor", executor);
                    nextHandler = form.getExecutor();
                    form.setHandler(form.getExecutor());
                } else {
                    form.setApplyStatus(5);
                    form.setDelFlag("9");
                    form.setTaskId(null);
                    form.setTaskName(null);
                    nextHandler = null;
                    form.setHandler(null);
                }
                break;
            case "执行":
                form.setApplyStatus(3);
                param.put("inspectors", form.getInspectors());
                nextHandler = form.getInspectors();
                form.setHandler(form.getInspectors());
                break;
            case "验收":
                if ("1".equals(condition)) {
                    form.setApplyStatus(4);
                    form.setActualFinishDate(new Date());
                    form.setTaskId(null);
                    form.setTaskName(null);
                    nextHandler = null;
                    form.setHandler(null);
                } else {
                    form.setApplyStatus(2);
                    nextHandler = form.getExecutor();
                    form.setHandler(form.getExecutor());
                }
                // 拼接审批意见字符串
                comment += "," + form.getRemarks();
                break;
        }
        devTask.setComment(comment);
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = processEngine.getTaskService();
        //认领任务
        processEngine.getTaskService()
                .claim(taskId, getUserId().toString());
        taskService.addComment(taskId, processInstancesId, devTask.getComment());
        taskService.complete(taskId, param);
        Task nextHandlerTask = null;
        // 标记taskId、TaskName
        if (nextHandler != null) {
            List<Task> list = processEngine.getTaskService()//获取任务service
                    .createTaskQuery()//创建查询对象
                    .taskCandidateOrAssigned(nextHandler.indexOf(",") == -1 ? nextHandler: nextHandler.substring(0, nextHandler.indexOf(","))).list();
            for (Task t : list) {
                if (form.getProcessId().equals(t.getProcessInstanceId())) {
                    form.setTaskId(t.getId());
                    form.setTaskName(t.getName());
                    nextHandlerTask = t;
                }
            }
        }
        if (nextHandler != null) {
            String[] split = null;
            if (nextHandler.indexOf(",") != -1) {
                split = nextHandler.split(",");
            } else {
                split = new String[1];
                split[0] = nextHandler;
            }
            for (int i = 0; i < split.length; i++) {
                if (!split[i].equals("20276")) {    // 张力飞不发邮件
                    SysUser sysUser = userService.selectUserById(Long.parseLong(split[i]));
                    String staffId = sysUser.getStaffId();
                    String loginName = sysUser.getUserName();
                    TStaffmgr staffmgr = staffmgrService.selectTStaffmgrByStaffId(staffId);
                    String staffName = staffmgr.getName();
                    String email = sysUser.getEmail();
                    if (email != null) {
                        // 系统通知
                        SysMessage message = new SysMessage();
                        message.setUserId(Long.parseLong(split[i]));
                        message.setMsgTitle("您有一条系统消息");
                        message.setMsgContent("您有一条SAI开项申请消息待查看");
                        // 发送邮件
//                        email = "lihui@seashoreept.com";
                        SaiApplyMailThread saiApplyMailThread = new SaiApplyMailThread(
                                mailService, sysMessageService, message, email, nextHandlerTask, form, staffName, loginName);
                        Thread thread = new Thread(saiApplyMailThread);
                        thread.start();
                    }
                }
            }
        }
        //任务完成更新数据
        tSaiApplyService.updateTSaiApply(form);
        return AjaxResult.success();
    }

    /**
     * 修改SAI开项管理
     */
    @PreAuthorize("@ss.hasPermi('production:apply:edit')")
    @Log(title = "SAI开项管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TSaiApply tSaiApply)
    {
        String userId = getUserId().toString();
        tSaiApply.setUpdateBy(userId);
        tSaiApply.setUpdateTime(new Date());

        long applyStatus = tSaiApply.getApplyStatus();
        switch (applyStatus + "") {
            case "0":
                tSaiApply.setHandler(tSaiApply.getApplicant());
                break;
            case "1":
                tSaiApply.setHandler("20276");
                break;
            case "2":
                tSaiApply.setHandler(tSaiApply.getExecutor());
                break;
            case "3":
                tSaiApply.setHandler(tSaiApply.getInspectors());
                break;
            case "4":
                tSaiApply.setHandler(null);
                break;
            case "5":
                tSaiApply.setHandler(null);
                break;
        }

        TSaiApproveFile tSaiApproveFile = new TSaiApproveFile();
        tSaiApproveFile.setApproveId(tSaiApply.getSaiApplyId());
        List<TSaiApproveFile> tSaiApproveFiles = saiApproveFileService.selectTSaiApproveFileList(tSaiApproveFile);
        for (TSaiApproveFile saiApproveFile : tSaiApproveFiles) {
            saiApproveFileService.deleteTSaiApproveFileById(saiApproveFile.getId());
        }

        if (tSaiApply.getFiles().size() > 0) {
            for (TSaiApproveFile t : tSaiApply.getFiles()
            ) {
                t.setApproveId(tSaiApply.getSaiApplyId());
                saiApproveFileService.save(t);
            }
        }
        return toAjax(tSaiApplyService.updateTSaiApply(tSaiApply));
    }

    /**
     * 删除SAI开项管理
     */
    @PreAuthorize("@ss.hasPermi('production:apply:remove')")
    @Log(title = "SAI开项管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{saiApplyIds}")
    public AjaxResult remove(@PathVariable Long[] saiApplyIds)
    {
        return toAjax(tSaiApplyService.deleteTSaiApplyByIds(saiApplyIds));
    }
}
