package com.ruoyi.project.intact.controller;

import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.project.approve.damain.DevTask;
import com.ruoyi.project.intact.domain.*;
import com.ruoyi.project.intact.mapper.TApproveMaintenanceMapper;
import com.ruoyi.project.intact.service.*;
import com.ruoyi.project.sems.domain.*;
import com.ruoyi.project.sems.his.domain.*;
import com.ruoyi.project.system.domain.SysUser;
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.apache.poi.ss.formula.functions.T;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
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 2022-06-27
 */
@RestController
@RequestMapping("/intact/maintenance")
public class TApproveMaintenanceController extends BaseController
{
    @Autowired
    private ITApproveMaintenanceService tApproveMaintenanceService;
    @Autowired
    private TApproveMaintenanceMapper maintenanceMapper;

    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private TaskService taskService;

    @Autowired
    private ITIntactGylService gylService;
    @Autowired
    private ITIntactYsjService ysjService;
    @Autowired
    private ITIntactGjService gjService;
    @Autowired
    private ITIntactPumpService pumpService;
    @Autowired
    private ISysUserService sysUserService;

    @RequestMapping("/hisApprovelist")
    public AjaxResult hisApprovelist(@RequestParam Map<String, Object> params) {
        String sql = params.get("devId") + " in (SELECT REGEXP_SUBSTR (DEV_ID, '[^,]+', 1,rownum) from dual connect by rownum<=LENGTH (DEV_ID) - LENGTH (regexp_replace(DEV_ID, ',', ''))+1 ) ";
        if (StringUtils.isNotEmpty((String) params.get("devType"))){
            sql+=" and dev_type="+params.get("devType")+" ";
        }
        if (StringUtils.isNotEmpty((String) params.get("createyear"))){
            sql+=" and to_char(creattime,'yyyy')= "+params.get("createyear")+" ";
        }
        List<TApproveMaintenance> list = maintenanceMapper.selectList(new QueryWrapper<TApproveMaintenance>().apply(sql).orderByDesc("CREATTIME")
        );
        for (TApproveMaintenance t : list
        ) {
            SysUser userEntity = sysUserService.selectUserById(t.getUserId());
            t.setUserName(userEntity.getNickName());
        }
        return AjaxResult.success(list);
    }

    /**
     * 查询设备完整性维修申请列表
     */
    @PreAuthorize("@ss.hasPermi('intact:maintenance:list')")
    @GetMapping("/list")
    public TableDataInfo list(TApproveMaintenance tApproveMaintenance)
    {
        startPage();
        List<TApproveMaintenance> list = tApproveMaintenanceService.selectTApproveMaintenanceList(tApproveMaintenance);
        for (TApproveMaintenance tApprove : list) {
            String[] ids;
            ids = tApprove.getDevId().split(",");
            List<Object> devList = new ArrayList<>();
            switch (Integer.parseInt(tApprove.getDevType().toString())) {
                case 1:
                    for (String i : ids
                    ) {
                        TIntactGyl gylEntity = gylService.getById(i);
                        devList.add(gylEntity);
                    }
                    break;
                case 2:
                    for (String i : ids
                    ) {
                        TIntactYsj ysjEntity = ysjService.getById(i);
                        devList.add(ysjEntity);
                    }
                    break;
            case 3:
                for (String i : ids
                ) {
                    TIntactGj gjEntity = gjService.getById(i);
                    devList.add(gjEntity);
                }
                break;
            case 4:
                for (String i : ids
                ) {
                    TIntactPump pumpEntity = pumpService.getById(i);
                    devList.add(pumpEntity);
                }
                break;
                default:
                    break;
            }
            tApprove.setDevList(devList);
        }
        return getDataTable(list);
    }

    /**
     * 导出设备完整性维修申请列表
     */
    @PreAuthorize("@ss.hasPermi('intact:maintenance:export')")
    @Log(title = "设备完整性维修申请", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TApproveMaintenance tApproveMaintenance)
    {
        List<TApproveMaintenance> list = tApproveMaintenanceService.selectTApproveMaintenanceList(tApproveMaintenance);
        ExcelUtil<TApproveMaintenance> util = new ExcelUtil<TApproveMaintenance>(TApproveMaintenance.class);
        return util.exportExcel(list, "maintenance");
    }

    /**
     * 获取设备完整性维修申请详细信息
     */
    @PreAuthorize("@ss.hasPermi('intact:maintenance:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tApproveMaintenanceService.selectTApproveMaintenanceById(id));
    }

    /**
     * 获取特种设备变更申请详细信息
     */
    @GetMapping(value = "info/{id}")
    public AjaxResult info(@PathVariable("id") Long id)
    {
        TApproveMaintenance tApprove = tApproveMaintenanceService.selectTApproveMaintenanceById(id);
        String[] ids;
        ids = tApprove.getDevId().split(",");
        List<Object> devList = new ArrayList<>();
        switch (Integer.parseInt(tApprove.getDevType().toString())) {
            case 1:
                for (String i : ids
                ) {
                    TIntactGyl gylEntity = gylService.getById(i);
                    devList.add(gylEntity);
                }
                break;
            case 2:
                for (String i : ids
                ) {
                    TIntactYsj ysjEntity = ysjService.getById(i);
                    devList.add(ysjEntity);
                }
                break;
            case 3:
                for (String i : ids
                ) {
                    TIntactGj gjEntity = gjService.getById(i);
                    devList.add(gjEntity);
                }
                break;
            case 4:
                for (String i : ids
                ) {
                    TIntactPump pumpEntity = pumpService.getById(i);
                    devList.add(pumpEntity);
                }
                break;
            default:
                break;
        }
        tApprove.setDevList(devList);
        return AjaxResult.success(tApprove);
    }

    /**
     * 新增设备完整性维修申请
     */
//    @PreAuthorize("@ss.hasPermi('intact:maintenance:add')")
    @Log(title = "设备完整性维修申请", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TApproveMaintenance tApproveMaintenance)
    {
        Long userid = getUserId();
        tApproveMaintenance.setUserId(userid);
//        tApproveSpecModify.setApNo(tApproveSpecModify.getHisId().toString());
        //审批编号
        Date dt = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
        String data = sdf.format(dt) + userid;
        tApproveMaintenance.setApNo(data);
        //
        Authentication.setAuthenticatedUserId(userid.toString());
        tApproveMaintenanceService.insertTApproveMaintenance(tApproveMaintenance);
        long bussniseeKey = tApproveMaintenance.getId();
        String[] ids;
        ids = tApproveMaintenance.getDevId().split(",");
        switch (Integer.parseInt(tApproveMaintenance.getDevType().toString())){
            case 1:
                for (String i : ids
                ) {
                    TIntactGyl gylEntity = gylService.getById(i);
//                    gylEntity.setApproveStatus(tApproveMaintenance.getApproveType()+ 19);
                    gylEntity.setApproveTime(new Date());
                    gylService.updateById(gylEntity);
                }
                break;
            case 2:
                for (String i : ids
                ) {
                    TIntactYsj ysjEntity = ysjService.getById(i);
//                    ylgdEntity.setApproveStatus(tApproveSpecModify.getApproveType() + 19);
                    ysjEntity.setApproveTime(new Date());
                    ysjService.updateById(ysjEntity);
                }
                break;
            case 3:
                for (String i : ids
                ) {
                    TIntactGj gjEntity = gjService.getById(i);
//                    gjEntity.setApproveStatus(tApproveMaintenance.getApproveType()+ 19);
                    gjEntity.setApproveTime(new Date());
                    gjService.updateById(gjEntity);
                }
                break;
            case 4:
                for (String i : ids
                ) {
                    TIntactPump pumpEntity = pumpService.getById(i);
//                    pumpEntity.setApproveStatus(t.getApproveType()+ 19);
                    pumpEntity.setApproveTime(new Date());
                    pumpService.updateById(pumpEntity);
                }
                break;
            default:
                break;
        }
        //开始工作流、监听
        Map<String, Object> variables = new HashMap<>();
        variables.put("applyUser", userid.toString());
        variables.put("wxjlusers", tApproveMaintenance.getWxjl());
        //采用key来启动流程定义并设置流程变量，返回流程实例
        ProcessInstance pi = runtimeService.startProcessInstanceByKey("maintenance", String.valueOf(bussniseeKey), variables);
        logger.info("流程部署id：" + pi.getDeploymentId());
        logger.info("流程定义id：" + pi.getProcessDefinitionId());
        logger.info("流程实例id：" + pi.getProcessInstanceId());
        tApproveMaintenance.setProcessId(pi.getProcessInstanceId());
        tApproveMaintenanceService.updateTApproveMaintenance(tApproveMaintenance);
        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();
        TApproveMaintenance tApproveMaintenance = tApproveMaintenanceService.selectTApproveMaintenanceById(Long.parseLong(devTask.getBusinessKey()));
        if (devTask.getCondition().equals("1")) {
            devTask.setComment("通过" + symbol + devTask.getComment());
            tApproveMaintenance.setStatus(1L);
            tApproveMaintenance.setEnddate(new Date());
        }else if (devTask.getCondition().equals("0")) {
            devTask.setComment("未通过" + symbol + devTask.getComment());
            tApproveMaintenance.setStatus(2L);
            tApproveMaintenance.setEnddate(new Date());
        }
        String[] ids;
        ids = tApproveMaintenance.getDevId().split(",");
        switch (Integer.parseInt(tApproveMaintenance.getDevType().toString())){
            case 1://修改工业炉台账
                for (String i : ids
                ) {
                    TIntactGyl gylEntity = gylService.getById(i);
                    gylEntity.setApproveStatus(0L);
                    gylService.updateById(gylEntity);
                    tApproveMaintenanceService.updateTApproveMaintenance(tApproveMaintenance);
                }
                break;
            case 2://修改压缩机台账
                for (String i : ids
                ) {
                    TIntactYsj ysjEntity = ysjService.getById(i);
                    ysjEntity.setApproveStatus(0L);
                    ysjService.updateById(ysjEntity);
                    tApproveMaintenanceService.updateTApproveMaintenance(tApproveMaintenance);
                }
                break;
            case 3:
                for (String i : ids
                ) {
                    TIntactGj gjEntity = gjService.getById(i);
                    gjEntity.setApproveStatus(0L);
                    gjService.updateById(gjEntity);
                    tApproveMaintenanceService.updateTApproveMaintenance(tApproveMaintenance);
                }
                break;
            case 4:
                for (String i : ids
                ) {
                    TIntactPump pumpEntity = pumpService.getById(i);
                    pumpEntity.setApproveStatus(0L);
                    pumpService.updateById(pumpEntity);
                    tApproveMaintenanceService.updateTApproveMaintenance(tApproveMaintenance);
                }
                break;
            default:
                break;
        }
        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());
        taskService.addComment(taskId, processInstancesId, devTask.getComment());
        taskService.complete(taskId, param);
        return AjaxResult.success();
    }

    /**
     * 修改设备完整性维修申请
     */
    @PreAuthorize("@ss.hasPermi('intact:maintenance:edit')")
    @Log(title = "设备完整性维修申请", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TApproveMaintenance tApproveMaintenance)
    {
        return toAjax(tApproveMaintenanceService.updateTApproveMaintenance(tApproveMaintenance));
    }

    /**
     * 删除设备完整性维修申请
     */
    @PreAuthorize("@ss.hasPermi('intact:maintenance:remove')")
    @Log(title = "设备完整性维修申请", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tApproveMaintenanceService.deleteTApproveMaintenanceByIds(ids));
    }
}
