package com.ruoyi.project.sems.his.controller;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.alibaba.fastjson.JSON;
import com.github.stuxuhai.jpinyin.PinyinFormat;
import com.github.stuxuhai.jpinyin.PinyinHelper;
import com.ruoyi.common.sendEmail.IMailService;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.security.service.TokenService;
import com.ruoyi.project.approve.damain.DevTask;
import com.ruoyi.project.sems.domain.*;
import com.ruoyi.project.sems.his.domain.*;
import com.ruoyi.project.sems.his.service.*;
import com.ruoyi.project.sems.service.*;
import com.ruoyi.project.system.service.ISysUserService;
import org.activiti.engine.*;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;

/**
 * 特种设备变更申请Controller
 *
 * @author ruoyi
 * @date 2021-09-02
 */
@RestController
@RequestMapping("sems/his/modify")
public class TApproveSpecModifyController extends BaseController
{
    @Autowired
    private ITApproveSpecModifyService tApproveSpecModifyService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private ITSpecdevDtService tSpecdevDtService;
    @Autowired
    private ITSpecdevDzsbService tSpecdevDzsbService;
    @Autowired
    private ITSpecdevGlService tSpecdevGlService;
    @Autowired
    private ITSpecdevYlgdService tSpecdevYlgdService;
    @Autowired
    private ITSpecdevYlrqService tSpecdevYlrqService;
    @Autowired
    private ITSpecdevCcService tSpecdevCcService;
    @Autowired
    private ITApproverFileService tApproverFileService;
    @Autowired
    private ITSpechiYlrqService tSpechiYlrqService;
    @Autowired
    private ITSpechiYlgdService tSpechiYlgdService;
    @Autowired
    private ITSpechiGlService tSpechiGlService;
    @Autowired
    private ITSpechiDzsbService tSpechiDzsbService;
    @Autowired
    private ITSpechiCcService tSpechiCcService;
    @Autowired
    private ITSpechiDtService tSpechiDtService;
    @Autowired
    private ITSpecCheckService tSpecCheckService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IMailService mailService;
    @Autowired
    private TSpechiCcController tSpechiCcController;
    @Autowired
    private TSpechiDtController tSpechiDtController;
    @Autowired
    private TSpechiGlController tSpechiGlController;
    @Autowired
    private TSpechiDzsbController tSpechiDzsbController;
    @Autowired
    private TSpechiYlrqController tSpechiYlrqController;
    @Autowired
    private TSpechiYlgdController tSpechiYlgdController;
    /**
     * 查询特种设备变更申请列表
     */
    @GetMapping("/list")
    public TableDataInfo list(TApproveSpecModify tApproveSpecModify)
    {
        startPage();
        List<TApproveSpecModify> list = tApproveSpecModifyService.selectTApproveSpecModifyList(tApproveSpecModify);
        return getDataTable(list);
    }

    /**
     * 导出特种设备变更申请列表
     */
    @Log(title = "特种设备变更申请", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TApproveSpecModify tApproveSpecModify)
    {
        List<TApproveSpecModify> list = tApproveSpecModifyService.selectTApproveSpecModifyList(tApproveSpecModify);
        ExcelUtil<TApproveSpecModify> util = new ExcelUtil<TApproveSpecModify>(TApproveSpecModify.class);
        return util.exportExcel(list, "modify");
    }

    /**
     * 获取特种设备变更申请详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tApproveSpecModifyService.selectTApproveSpecModifyById(id));
    }

    /**
     * 获取特种设备变更申请详细信息
     */
    @GetMapping(value = "info/{id}")
    public AjaxResult info(@PathVariable("id") Long id)
    {
        TApproveSpecModify tApprove = tApproveSpecModifyService.selectTApproveSpecModifyById(id);
        String[] ids;
        ids = tApprove.getDevId().split(",");
        CopyOnWriteArrayList<Object> devList = new CopyOnWriteArrayList<>();
        //线程池
        ExecutorService executorService = Executors.newFixedThreadPool(30);
        final CountDownLatch latch = new CountDownLatch(ids.length); //相同线程数量的计数

        switch (Integer.parseInt(tApprove.getDevType().toString())) {
            case 1:
                for (String i : ids
                ) {
                    executorService.execute(() -> {
                        try {
                            TSpecdevYlrq ylrqEntity = tSpecdevYlrqService.getById(i);
                            devList.add(ylrqEntity);
                        } catch (Exception e) {
                            logger.info("e:" + e);
                        } finally {
                            latch.countDown(); //线程计数
                        }
                    });
                }
                break;
            case 2:
                for (String i : ids
                ) {
                    executorService.execute(() -> {
                        try {
                            TSpecdevYlgd ylgdEntity = tSpecdevYlgdService.getById(i);
                            devList.add(ylgdEntity);
                        } catch (Exception e) {
                            logger.info("e:" + e);
                        } finally {
                            latch.countDown(); //线程计数
                        }
                    });
                }
                break;
            case 3:
                for (String i : ids
                ) {
                    executorService.execute(() -> {
                        try {
                            TSpecdevDzsb dzsbEntity = tSpecdevDzsbService.getById(i);
                            devList.add(dzsbEntity);
                        } catch (Exception e) {
                            logger.info("e:" + e);
                        } finally {
                            latch.countDown(); //线程计数
                        }
                    });

                }
                break;
            case 4:
                for (String i : ids
                ) {
                    executorService.execute(() -> {
                        try {
                            TSpecdevGl glEntity = tSpecdevGlService.getById(i);
                            devList.add(glEntity);
                        } catch (Exception e) {
                            logger.info("e:" + e);
                        } finally {
                            latch.countDown(); //线程计数
                        }
                    });

                }
                break;
            case 5:
                for (String i : ids
                ) {
                    executorService.execute(() -> {
                        try {
                            TSpecdevDt dtEntity = tSpecdevDtService.getById(i);
                            devList.add(dtEntity);
                        } catch (Exception e) {
                            logger.info("e:" + e);
                        } finally {
                            latch.countDown(); //线程计数
                        }
                    });

                }
                break;
            case 6:
                for (String i : ids
                ) {
                    executorService.execute(() -> {
                        try {
                            TSpecdevCc ccEntity = tSpecdevCcService.getById(i);
                            devList.add(ccEntity);
                        } catch (Exception e) {
                            logger.info("e:" + e);
                        } finally {
                            latch.countDown(); //线程计数
                        }
                    });

                }
                break;
            case 7:
                for (String i : ids
                ) {
//                        TOtherTankEntity tankEntity = tOtherTankService.getById(i);
//                        devList.add(tankEntity);
                }
        }
        try {
            latch.await(); //线程计数完毕后继续执行
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executorService.shutdown();
        tApprove.setDevList(devList);
        return AjaxResult.success(tApprove);
    }

    /**
     * 新增特种设备变更申请
     */
    @Log(title = "特种设备变更申请", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TApproveSpecModify tApproveSpecModify)
    {
        Long userid = getUserId();
        tApproveSpecModify.setUserId(userid);
//        tApproveSpecModify.setApNo(tApproveSpecModify.getHisId().toString());
        //审批编号
        Date dt = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
        String data = sdf.format(dt) + userid;
        tApproveSpecModify.setApNo(data);
        //获取操作日志参数
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        String userName =loginUser != null? loginUser.getUsername(): "";
        String operType = getOperType(Integer.parseInt(tApproveSpecModify.getApproveType().toString()));
        //
        Authentication.setAuthenticatedUserId(userid.toString());
        tApproveSpecModifyService.insertTApproveSpecModify(tApproveSpecModify);
        long bussniseeKey = tApproveSpecModify.getId();
        String[] ids;
        ids = tApproveSpecModify.getDevId().split(",");
        switch (Integer.parseInt(tApproveSpecModify.getDevType().toString())){
            case 1:
                for (String i : ids
                ) {
                    TSpecdevYlrq ylrqEntity = tSpecdevYlrqService.getById(i);
                    ylrqEntity.setApproveStatus(tApproveSpecModify.getApproveType()+ 19);
                    ylrqEntity.setApproveTime(new Date());
                    tSpecdevYlrqService.updateById(ylrqEntity);
                }
                new Thread(() -> {
                    tSpechiYlrqController.addOperLog(ids,userName,new Date() , operType + "-申请" );
                },"特种设备操作日志").start();
                break;
            case 2:
                for (String i : ids
                ) {
                    TSpecdevYlgd ylgdEntity = tSpecdevYlgdService.getById(i);
                    ylgdEntity.setApproveStatus(tApproveSpecModify.getApproveType() + 19);
                    ylgdEntity.setApproveTime(new Date());
                    tSpecdevYlgdService.updateById(ylgdEntity);
                }
                new Thread(() -> {
                    tSpechiYlgdController.addOperLog(ids,userName,new Date() , operType + "-申请" );
                },"特种设备操作日志").start();
                break;
            case 3:
                for (String i : ids
                ) {
                    TSpecdevDzsb dzsbEntity = tSpecdevDzsbService.getById(i);
                    dzsbEntity.setApproveStatus(tApproveSpecModify.getApproveType()+ 19);
                    dzsbEntity.setApproveTime(new Date());
                    tSpecdevDzsbService.updateById(dzsbEntity);
                }
                new Thread(() -> {
                    tSpechiDzsbController.addOperLog(ids,userName,new Date() , operType + "-申请" );
                },"特种设备操作日志").start();
                break;
            case 4:
                for (String i : ids
                ) {
                    TSpecdevGl glEntity = tSpecdevGlService.getById(i);
                    glEntity.setApproveStatus(tApproveSpecModify.getApproveType()+ 19);
                    glEntity.setApproveTime(new Date());
                    tSpecdevGlService.updateById(glEntity);
                }
                new Thread(() -> {
                    tSpechiGlController.addOperLog(ids,userName,new Date() , operType + "-申请" );
                },"特种设备操作日志").start();
                break;
            case 5:
                for (String i : ids
                ) {
                    TSpecdevDt dtEntity = tSpecdevDtService.getById(i);
                    dtEntity.setApproveStatus(tApproveSpecModify.getApproveType()+ 19);
                    dtEntity.setApproveTime(new Date());
                    tSpecdevDtService.updateById(dtEntity);
                }
                new Thread(() -> {
                    tSpechiDtController.addOperLog(ids,userName,new Date() , operType + "-申请" );
                },"特种设备操作日志").start();
                break;
            case 6:
                for (String i : ids
                ) {
                    TSpecdevCc ccEntity = tSpecdevCcService.getById(i);
                    ccEntity.setApproveStatus(tApproveSpecModify.getApproveType()+ 19);
                    ccEntity.setApproveTime(new Date());
                    tSpecdevCcService.updateById(ccEntity);
                }
                new Thread(() -> {
                    tSpechiCcController.addOperLog(ids,userName,new Date() , operType + "-申请" );
                },"特种设备操作日志").start();
                break;
    }
        //开始工作流、监听
        Map<String, Object> variables = new HashMap<>();
        variables.put("applyUser", userid.toString());
        variables.put("wxjlusers", tApproveSpecModify.getWxjl());
        //采用key来启动流程定义并设置流程变量，返回流程实例
        ProcessInstance pi = runtimeService.startProcessInstanceByKey("modifySpecProcess", String.valueOf(bussniseeKey), variables);
        logger.info("流程部署id：" + pi.getDeploymentId());
        logger.info("流程定义id：" + pi.getProcessDefinitionId());
        logger.info("流程实例id：" + pi.getProcessInstanceId());
        tApproveSpecModify.setProcessId(pi.getProcessInstanceId());
        new Thread(() -> {
            sendMail(tApproveSpecModify , String.valueOf(tApproveSpecModify.getWxjl()));
        },"发送邮件").start();
        return AjaxResult.success();
    }

    /**
     * 审核处理
     */
    @Log(title = "特种设备审核处理", businessType = BusinessType.UPDATE)
    @PutMapping("/handle")
    public AjaxResult handle(@RequestBody DevTask devTask) {
        //流程审批意见
        String symbol= "";
        if (devTask.getComment() != "") {
            symbol = "，";
        }
        //使用任务服务完成任务(提交任务)
        String taskId = devTask.getTaskId();
        // 使用任务id,获取任务对象，获取流程实例id
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        //利用任务对象，获取流程实例id
        String processInstancesId = task.getProcessInstanceId();
        TApproveSpecModify tApproveSpecModify = tApproveSpecModifyService.selectTApproveSpecModifyById(Long.parseLong(devTask.getBusinessKey()));
        //获取操作日志参数
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        String userName =loginUser != null? loginUser.getUsername(): "";
        String operType = getOperType(Integer.parseInt(tApproveSpecModify.getApproveType().toString()));
        if (devTask.getCondition().equals("1")) {
            devTask.setComment("通过" + symbol + devTask.getComment());
            String[] ids;
            ids = tApproveSpecModify.getDevId().split(",");
            switch (Integer.parseInt(tApproveSpecModify.getDevType().toString())){
                case 1://修改压力容器台账
                    for (String i : ids
                    ) {
                        TSpecdevYlrq ylrqEntity = tSpecdevYlrqService.getById(i);
                        ylrqEntity.setApproveStatus(0l);
                        tSpecdevYlrqService.updateById(ylrqEntity);
                        //修改
                        if (tApproveSpecModify.getApproveType() == 1) {
                            logger.info(JSON.toJSONString(tApproveSpecModify));
                            TSpechiYlrq hientity = tSpechiYlrqService.selectTSpechiYlrqById(Long.parseLong(tApproveSpecModify.getDevId()));
                            logger.info(JSON.toJSONString(hientity));
                            tSpecdevYlrqService.updateTSpecdevYlrqByHi(hientity);
                        }else if (tApproveSpecModify.getApproveType() == 3){
                            //新增
                        }else {
                            tSpecdevYlrqService.deleteTSpecdevYlrqById(Long.parseLong(i));
                        }
                    }
                    new Thread(() -> {
                        tSpechiYlrqController.addOperLog(ids,userName,new Date() , operType + "-通过" );
                    },"特种设备操作日志").start();
                    break;
                case 2://修改压力管道台账
                    for (String i : ids
                    ) {
                        TSpecdevYlgd ylgdEntity = tSpecdevYlgdService.getById(i);
                        ylgdEntity.setApproveStatus(0l);
                        tSpecdevYlgdService.updateById(ylgdEntity);
                        //修改
                        if (tApproveSpecModify.getApproveType() == 1) {
                            TSpechiYlgd hientity = tSpechiYlgdService.selectTSpechiYlgdById(Long.parseLong(tApproveSpecModify.getDevId()));
                            tSpecdevYlgdService.updateTSpecdevYlgdByHi(hientity);
                        }else if (tApproveSpecModify.getApproveType() == 3){
                            //新增
                        }else {
                            tSpecdevYlgdService.deleteTSpecdevYlgdById(Long.parseLong(i));
                        }
                    }
                    new Thread(() -> {
                        tSpechiYlgdController.addOperLog(ids,userName,new Date() , operType + "-通过" );
                    },"特种设备操作日志").start();
                    break;
                case 3://修改吊装设备台账
                    for (String i : ids
                    ) {
                        TSpecdevDzsb dzsbEntity = tSpecdevDzsbService.getById(i);
                        dzsbEntity.setApproveStatus(0l);
                        tSpecdevDzsbService.updateById(dzsbEntity);

                        if (tApproveSpecModify.getApproveType() == 1){
                            TSpechiDzsb hientity = tSpechiDzsbService.selectTSpechiDzsbById(Long.parseLong(tApproveSpecModify.getDevId()));
                            tSpecdevDzsbService.updateTSpecdevDzsbByHi(hientity);
                        } else if (tApproveSpecModify.getApproveType() == 3){
                            //新增
                        }else {
                            tSpecdevDzsbService.deleteTSpecdevDzsbById(Long.parseLong(i));
                        }
                    }
                    new Thread(() -> {
                        tSpechiDzsbController.addOperLog(ids,userName,new Date() , operType + "-通过" );
                    },"特种设备操作日志").start();
                    break;
                case 4://修改锅炉台账
                    for (String i : ids
                    ) {
                        TSpecdevGl glEntity = tSpecdevGlService.getById(i);
                        glEntity.setApproveStatus(0l);
                        tSpecdevGlService.updateById(glEntity);

                        if (tApproveSpecModify.getApproveType() == 1){
                            TSpechiGl hientity = tSpechiGlService.selectTSpechiGlById(Long.parseLong(tApproveSpecModify.getDevId()));
                            tSpecdevGlService.updateTSpecdevGlByHi(hientity);
                        }else if (tApproveSpecModify.getApproveType() == 3){
                            //新增
                        } else {
                            tSpecdevGlService.deleteTSpecdevGlById(Long.parseLong(i));
                        }
                    }
                    new Thread(() -> {
                        tSpechiGlController.addOperLog(ids,userName,new Date() , operType + "-通过" );
                    },"特种设备操作日志").start();
                    break;
                case 5://修改电梯台账
                    for (String i : ids
                    ) {
                        TSpecdevDt dtEntity = tSpecdevDtService.getById(i);
                        dtEntity.setApproveStatus(0l);
                        tSpecdevDtService.updateById(dtEntity);
                        if (tApproveSpecModify.getApproveType() == 1){
                            TSpechiDt hientity = tSpechiDtService.selectTSpechiDtById(Long.parseLong(tApproveSpecModify.getDevId()));
                            tSpecdevDtService.updateTSpecdevDtByHi(hientity);
                        }else if (tApproveSpecModify.getApproveType() == 3){
                            //新增
                        } else {
                            tSpecdevDtService.deleteTSpecdevDtById(Long.parseLong(i));
                        }
                    }
                    new Thread(() -> {
                        tSpechiDtController.addOperLog(ids,userName,new Date() , operType + "-通过" );
                    },"特种设备操作日志").start();
                    break;
                case 6://修改叉车台账
                    for (String i : ids
                    ) {
                        TSpecdevCc ccEntity = tSpecdevCcService.getById(i);
                        ccEntity.setApproveStatus(0l);
                        tSpecdevCcService.updateById(ccEntity);

                        if (tApproveSpecModify.getApproveType() == 1){
                            TSpechiCc hientity = tSpechiCcService.selectTSpechiCcById(Long.parseLong(tApproveSpecModify.getDevId()));
                            tSpecdevCcService.updateTSpecdevCcByHi(hientity);
                        } else if (tApproveSpecModify.getApproveType() == 3){
                            //新增
                        }else {
                            tSpecdevCcService.deleteTSpecdevCcById(Long.parseLong(i));
                        }
                    };
                    new Thread(() -> {
                        tSpechiCcController.addOperLog(ids,userName,new Date() , operType + "-通过" );
                    },"特种设备操作日志").start();
                    break;
            }
        }else if (devTask.getCondition().equals("0")) {
            devTask.setComment("未通过" + symbol + devTask.getComment());
            String[] ids;
            ids = tApproveSpecModify.getDevId().split(",");
            switch (Integer.parseInt(tApproveSpecModify.getDevType().toString())){
                case 1:
                    for (String i : ids
                    ) {
                        if (tApproveSpecModify.getApproveType() == 3){
                            //新增
                            tSpecdevYlrqService.deleteTSpecdevYlrqById(Long.parseLong(i));
                        }else {
                            TSpecdevYlrq ylrqEntity = tSpecdevYlrqService.getById(i);
                            ylrqEntity.setApproveStatus(0l);
                            tSpecdevYlrqService.updateById(ylrqEntity);
                        }
                    }
                    new Thread(() -> {
                        tSpechiYlrqController.addOperLog(ids,userName,new Date() , operType + "-未通过" );
                    },"特种设备操作日志").start();
                    break;
                case 2:
                    for (String i : ids
                    ) {
                        if (tApproveSpecModify.getApproveType() == 3){
                            //新增
                            tSpecdevYlgdService.deleteTSpecdevYlgdById(Long.parseLong(i));
                        }else {
                            TSpecdevYlgd ylgdEntity = tSpecdevYlgdService.getById(i);
                            ylgdEntity.setApproveStatus(0l);
                            tSpecdevYlgdService.updateById(ylgdEntity);
                        }
                    }
                    new Thread(() -> {
                        tSpechiYlgdController.addOperLog(ids,userName,new Date() , operType + "-未通过" );
                    },"特种设备操作日志").start();
                    break;
                case 3:
                    for (String i : ids
                    ) {
                        if (tApproveSpecModify.getApproveType() == 3){
                            //新增
                            tSpecdevDzsbService.deleteTSpecdevDzsbById(Long.parseLong(i));
                        }else {
                            TSpecdevDzsb dzsbEntity = tSpecdevDzsbService.getById(i);
                            dzsbEntity.setApproveStatus(0l);
                            tSpecdevDzsbService.updateById(dzsbEntity);
                        }

                    }
                    new Thread(() -> {
                        tSpechiDzsbController.addOperLog(ids,userName,new Date() , operType + "-未通过" );
                    },"特种设备操作日志").start();
                    break;
                case 4:
                    for (String i : ids
                    ) {
                        if (tApproveSpecModify.getApproveType() == 3){
                            //新增
                            tSpecdevGlService.deleteTSpecdevGlById(Long.parseLong(i));
                        }else {
                            TSpecdevGl glEntity = tSpecdevGlService.getById(i);
                            glEntity.setApproveStatus(0l);
                            tSpecdevGlService.updateById(glEntity);
                        }
                    }
                    new Thread(() -> {
                        tSpechiGlController.addOperLog(ids,userName,new Date() , operType + "-未通过" );
                    },"特种设备操作日志").start();
                    break;
                case 5:
                    for (String i : ids
                    ) {
                        if (tApproveSpecModify.getApproveType() == 3){
                            //新增
                            tSpecdevDtService.deleteTSpecdevDtById(Long.parseLong(i));
                        }else {
                            TSpecdevDt dtEntity = tSpecdevDtService.getById(i);
                            dtEntity.setApproveStatus(0l);
                            tSpecdevDtService.updateById(dtEntity);
                        }
                    }
                    new Thread(() -> {
                        tSpechiDtController.addOperLog(ids,userName,new Date() , operType + "-未通过" );
                    },"特种设备操作日志").start();
                    break;
                case 6:
                    for (String i : ids
                    ) {
                        if (tApproveSpecModify.getApproveType() == 3){
                            //新增
                            tSpecdevCcService.deleteTSpecdevCcById(Long.parseLong(i));
                        }else {
                            TSpecdevCc ccEntity = tSpecdevCcService.getById(i);
                            ccEntity.setApproveStatus(0l);
                            tSpecdevCcService.updateById(ccEntity);
                        }
                    };
                    new Thread(() -> {
                        tSpechiCcController.addOperLog(ids,userName,new Date() , operType + "-未通过" );
                    },"特种设备操作日志").start();
                    break;
            }
        }
        logger.info("特种设备审核：" + processInstancesId);
        Map<String, Object> param = new HashMap<>();
        param.put("condition", devTask.getCondition());
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = processEngine.getTaskService();
        //认领任务
        processEngine.getTaskService()//
                .claim(taskId, getUserId().toString());
//        Authentication.setAuthenticatedUserId("cmc"); // 添加批注时候的审核人
        taskService.addComment(taskId, processInstancesId, devTask.getComment());
        //业务监听处理
//        tApproveService.handleApprove(task ,devTask);
        taskService.complete(taskId, param);
     return AjaxResult.success();
    }

    /**
     * 修改特种设备变更申请
     */
    @Log(title = "特种设备变更申请", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TApproveSpecModify tApproveSpecModify)
    {
        return toAjax(tApproveSpecModifyService.updateTApproveSpecModify(tApproveSpecModify));
    }

    /**
     * 删除特种设备变更申请
     */
    @PreAuthorize("@ss.hasPermi('his:modify:remove')")
    @Log(title = "特种设备变更申请", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tApproveSpecModifyService.deleteTApproveSpecModifyByIds(ids));
    }

    public void sendMail(TApproveSpecModify approveEntity ,String wxjl){
        //发送邮件
        try {
            String email = sysUserService.selectUserById(Long.parseLong(wxjl)).getEmail();
            String apNo = approveEntity.getApNo();
            logger.info("apNo:" + apNo);
            String username = sysUserService.selectUserById(Long.parseLong(wxjl)).getNickName();
            String usernameEN = PinyinHelper.convertToPinyinString(username, " ", PinyinFormat.WITHOUT_TONE);
            logger.info("email:" + email);
            logger.info("username:" + username);
            String devType = "";
            String devTypeEN = "";
            switch (Integer.parseInt(approveEntity.getDevType().toString())) {
                case 1:
                    devType = "压力容器";
                    devTypeEN = "Pressure Vessel";
                    break;
                case 2:
                    devType = "压力管道";
                    devTypeEN = "Pressure Pipeline";
                    break;
                case 3:
                    devType = "起重机械";
                    devTypeEN = "Lifting Equipment";
                    break;
                case 4:
                    devType = "锅炉";
                    devTypeEN = "Boiler";
                    break;
                case 5:
                    devType = "电梯";
                    devTypeEN = "Elevator";
                    break;
                case 6:
                    devType = "叉车";
                    devTypeEN = "Forklift";
                    break;
                case 7:
                    devType = "常压罐";
                    devTypeEN = "Tank";
                    break;
            }
            String approveType = "";
            String approveTypeEN = "";
            switch (Integer.parseInt(approveEntity.getApproveType().toString())) {
                case 1:
                    approveType = "修改";
                    approveTypeEN = "Change";
                    break;
                case 2:
                    approveType = "删除";
                    approveTypeEN = "Delete";
                    break;
                case 3:
                    approveType = "新增";
                    approveTypeEN = "Add";
                    break;
            }
            //写html开始内容
            String start = "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title></title></head><body><div style=\"background-color:#ECECEC; padding: 35px;\">" +
                    "<table cellpadding=\"0\" align=\"center\"" +
                    "style=\"width: 600px; margin: 0px auto; text-align: left; position: relative; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; font-size: 14px; font-family:微软雅黑, 黑体; line-height: 1.5; box-shadow: rgb(153, 153, 153) 0px 0px 5px; border-collapse: collapse; background-position: initial initial; background-repeat: initial initial;background:#fff;\">" +
                    "<tbody><tr><th valign=\"middle\" style=\"height: 25px; line-height: 25px; padding: 15px 35px; border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: #42a3d3; background-color: #49bcff; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 0px; border-bottom-left-radius: 0px;\">" +
                    "<font face=\"微软雅黑\" size=\"5\" style=\"color: rgb(255, 255, 255); \">特种设备信息管理系统 </font><font face=\"微软雅黑\" size=\"3\" style=\"color: rgb(255, 255, 255); \">Special Equipment Management System (SEMS)</font></th></tr>";
            //表html中间内容
            String prime = "";
            String center = "<tr><td><div style=\"padding:25px 35px 40px; background-color:#fff;\"><h2 style=\"margin: 5px 0px; \">" +
                    "<font color=\"#333333\" style=\"line-height: 20px; \"><font style=\"line-height: 22px; \" size=\"4\">" +
                    "亲爱的 username</font><br><font style=\"line-height: 22px; \" size=\"4\">" +
                    "Dear usernameEN</font></font></h2>" +
                    "<p>您有一个新的待办任务：<br>" +
                    "You have a new to-do task:<br>" +
                    "任务编号：<b>apNo</b><br>" +
                    "Task Number: <b>apNoEN</b><br>" +
                    "申请设备类型：<b>devType</b><br>" +
                    "Equipment Type: <b>devTypeEN</b><br>" +
                    "审批类型：<b>approveType</b><br>" +
                    "Application Category: <b>approveTypeEN</b><br>" +
                    "请登录<a href=\"https://cpms.basf-ypc.net.cn/cpms/index.html#/approve/pending\">特种设备信息管理系统</a>查看。<br>" +
                    "Please log in the <a href=\"https://cpms.basf-ypc.net.cn/cpms/index.html#/approve/pending\">SEMS</a> to handle it.</p>" +
                    "<p align=\"right\">date</p>" +
                    "<div style=\"width:700px;margin:0 auto;\">" +
                    "<div style=\"padding:10px 10px 0;border-top:1px solid #ccc;color:#747474;margin-bottom:20px;line-height:1.3em;font-size:12px;\">" +
                    "<p>此为系统邮件，请勿回复<br>This e-Mail is an automatic reminder sent by SEMS, please do not reply</p>" +
                    "</div></div></div></td></tr>";
            String one = center.replaceFirst("username", username);
            String two = one.replaceFirst("usernameEN", usernameEN);
            String three = two.replaceFirst("devType", devType);
            String four = three.replaceFirst("apNo", apNo);
            String five = four.replaceFirst("apNoEN", apNo);
            String six = five.replaceFirst("devTypeEN", devTypeEN);
            String seven = six.replaceFirst("approveType", approveType);
            String eight = seven.replaceFirst("approveTypeEN", approveTypeEN);
            String result = eight.replaceFirst("date", String.valueOf(new Date()));
            prime = prime + result;
            //写html结尾内容
            String end = "</tbody></table></div></body></html>";
            //拼接html
            String html = start + prime + end;
            logger.info("html:" + html);
            mailService.sendHtmlMail(email, "特种设备：您有一个新的待办任务 SEMS:You have a new to-do task (" + apNo + ")", html);
        }catch (Exception e) {
            logger.error("邮件发送失败" + JSON.toJSONString(e));
        }
    };

    public String getOperType(int type) {
        switch (type) {
            case 1:
                return "修改";
            case 2:
                return "删除";
            case 3:
                return "新增";
        }
        return "";
    }
}
