package com.ruoyi.project.ehs.controller;

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

import com.alibaba.fastjson.JSON;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.domain.SysUserRole;
import com.ruoyi.project.system.service.ISysUserService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.runtime.ProcessInstance;
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.project.ehs.domain.TApproveAccident;
import com.ruoyi.project.ehs.service.ITApproveAccidentService;
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-03-01
 */
@RestController
@RequestMapping("/ehs/approveaccident")
public class TApproveAccidentController extends BaseController
{
    @Autowired
    private ITApproveAccidentService tApproveAccidentService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 任务申请
     */
    @PostMapping("/save")
    public AjaxResult save(@RequestBody TApproveAccident tApprove) {
        try {
            logger.info("任务申请" + JSON.toJSONString(tApprove));
            Long userid = getUserId();
            //审批编号
            Date dt = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
            String data = sdf.format(dt) + userid;
            tApprove.setApproveNo(data);
            tApprove.setRecorderId(userid);
            //事件初步分类
            List<Long> sortList = tApprove.getSortList();
            String accidentSort = "";
            for (int i = 0; i < sortList.size(); i++) {
                if (i == 0) {
                    accidentSort = sortList.get(i).toString();
                }else {
                    accidentSort = accidentSort + "," + sortList.get(i).toString();
                }
            }
            tApprove.setAccidentSort(accidentSort);
            logger.info("tApprove:" + tApprove);
            tApproveAccidentService.insertTApproveAccident(tApprove);

            Map<String, Object> variables = new HashMap<>();
            //确认动作实行人确认
            Long confirmoneId = null;
            Long deptId = sysUserService.selectUserById(userid).getDeptId();
            List<SysUser> deptPerson = sysUserService.selectUserByDept(deptId);
            for (SysUser s : deptPerson) {
                SysUserRole userRole = sysUserService.selectRoleByUserId(s.getUserId());
                if (userRole.getRoleId() == 100) {
                    confirmoneId = userRole.getUserId();
                }
            }
            /*暂时定为记录人部门经理*/
            tApprove.setConfirmoneId(confirmoneId);
            //审批人员设置
            variables.put("recorder", userid);
            //初始化会签人员
            List<Long> confirmlist = new ArrayList<>();
            confirmlist.add(confirmoneId);
            //条件表达式方法 一定要序列号
            variables.put("confirmlist", confirmlist);

            long bussniseeKey = tApprove.getId();
            logger.info("bussniseeKey:" + bussniseeKey);
            Authentication.setAuthenticatedUserId(userid.toString());
            //采用key来启动流程定义并设置流程变量，返回流程实例
            ProcessInstance pi = runtimeService.startProcessInstanceByKey("accidentProcess", String.valueOf(bussniseeKey), variables);

            logger.info("流程部署id：" + pi.getDeploymentId());
            logger.info("流程定义id：" + pi.getProcessDefinitionId());
            logger.info("流程实例id：" + pi.getProcessInstanceId());
            logger.info("流程定义对象：" + pi.getProcessVariables());
            tApprove.setProcessId(Long.parseLong(pi.getProcessInstanceId()));
            logger.info("tApprove:" + tApprove);
            tApproveAccidentService.updateTApproveAccident(tApprove);
        }catch (Exception e) {
            logger.info("e:" + e);
        }
        return AjaxResult.success("申请成功");
    }

    /**
     * 查询事件申请列表
     */
    @PreAuthorize("@ss.hasPermi('ehs:approveaccident:list')")
    @GetMapping("/list")
    public TableDataInfo list(TApproveAccident tApproveAccident)
    {
        startPage();
        List<TApproveAccident> list = tApproveAccidentService.selectTApproveAccidentList(tApproveAccident);
        return getDataTable(list);
    }

    /**
     * 导出事件申请列表
     */
    @PreAuthorize("@ss.hasPermi('ehs:approveaccident:export')")
    @Log(title = "事件申请", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TApproveAccident tApproveAccident)
    {
        List<TApproveAccident> list = tApproveAccidentService.selectTApproveAccidentList(tApproveAccident);
        ExcelUtil<TApproveAccident> util = new ExcelUtil<TApproveAccident>(TApproveAccident.class);
        return util.exportExcel(list, "approveaccident");
    }

    /**
     * 获取事件申请详细信息
     */
    @PreAuthorize("@ss.hasPermi('ehs:approveaccident:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tApproveAccidentService.selectTApproveAccidentById(id));
    }

    /**
     * 新增事件申请
     */
    @PreAuthorize("@ss.hasPermi('ehs:approveaccident:add')")
    @Log(title = "事件申请", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TApproveAccident tApproveAccident)
    {
        return toAjax(tApproveAccidentService.insertTApproveAccident(tApproveAccident));
    }

    /**
     * 修改事件申请
     */
    @PreAuthorize("@ss.hasPermi('ehs:approveaccident:edit')")
    @Log(title = "事件申请", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TApproveAccident tApproveAccident)
    {
        return toAjax(tApproveAccidentService.updateTApproveAccident(tApproveAccident));
    }

    /**
     * 删除事件申请
     */
    @PreAuthorize("@ss.hasPermi('ehs:approveaccident:remove')")
    @Log(title = "事件申请", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tApproveAccidentService.deleteTApproveAccidentByIds(ids));
    }
}
