package com.ruoyi.project.pssr.controller;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.ExcelUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
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.framework.web.page.TableDataInfo;
import com.ruoyi.project.pssr.domain.*;
import com.ruoyi.project.pssr.mapper.TPssrTorchvocMapper;
import com.ruoyi.project.pssr.service.*;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysUserService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * 火炬，VOC系统Controller
 *
 * @author ssy
 * @date 2024-09-18
 */
@RestController
@RequestMapping("/pssr/torchvoc")
public class TPssrTorchvocController extends BaseController {

    @Autowired
    private ITPssrFileService tPssrFileService;

    @Autowired
    private ITPssrTurndownService tPssrTurndownService;
    @Autowired
    private ITPssrTorchvocService tPssrTorchvocService;

    @Autowired
    private ITPssrApproveService tPssrApproveService;

    @Autowired
    private ITPssrSubcontentService tPssrSubcontentService;

    @Autowired
    private ITPssrBlindService tPssrBlindService;

    @Resource
    private TPssrTorchvocMapper tPssrTorchvocMapper;
    @Autowired
    private ISysUserService sysUserService;
    private String forShort = "hbss";

    /**
     * 查询火炬，VOC系统列表
     */
    @PreAuthorize("@ss.hasPermi('pssr:torchvoc:list')")
    @GetMapping("/list")
    public TableDataInfo list(TPssrTorchvoc tPssrTorchvoc) {
        try {
            TPssrApprove approve = tPssrApproveService.selectTPssrApproveBySubId(tPssrTorchvoc.getSubId());
            if (approve != null) {
                ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
                TaskService taskService = processEngine.getTaskService();
                Task task = processEngine.getTaskService()//获取任务service
                        .createTaskQuery()//创建查询对象
                        .taskAssignee(getUserId().toString())
                        .processInstanceId(approve.getProcessId()).singleResult();
                if (task != null) {
                    if (task.getName().equals("确认人1")){
                        tPssrTorchvoc.setConfirm1(getUserId().toString());
                    }else if (task.getName().equals("确认人2")){
                       tPssrTorchvoc.setConfirm2(getUserId().toString());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("待办确认人查询报错：{}",e.getMessage());
        }
        startPage();
        List<TPssrTorchvoc> list = tPssrTorchvocService.selectTPssrTorchvocList(tPssrTorchvoc);
        list.forEach(item -> {
            
            List<TPssrFile> tPssrFiles = tPssrFileService.selectTPssrFileListByItem(item.getSubId(), item.getId(), forShort);
            item.setFileList(tPssrFiles);
            item.setFileNum((long) tPssrFiles.size());
            if (item.getApproveStatus() != 2)
                item.setReason(tPssrTurndownService.selectTPssrTurndownByItem(item.getSubId(), item.getId(), "hbss"));
        });
        return getDataTable(list);
    }

    /**
     * 导出火炬，VOC系统列表
     */
    @PreAuthorize("@ss.hasPermi('pssr:torchvoc:export')")
    @Log(title = "火炬，VOC系统", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TPssrTorchvoc tPssrTorchvoc) {
        List<TPssrTorchvoc> list = tPssrTorchvocService.selectTPssrTorchvocList(tPssrTorchvoc);
        if (list.size() != 0) {
            return AjaxResult.success(exportTmpl(list, tPssrTorchvoc.getTorchvocType()));
        } else {
            return AjaxResult.error("暂无可导出数据");
        }
    }

    public String exportTmpl(List<TPssrTorchvoc> list, String torchvocType) {
        OutputStream out = null;
        String filename = null;
        try {
            String tempUrl = ""; // 模板文件
            if ("1".equals(torchvocType)) {
                tempUrl = "static/word/pssr/hbsshj.xlsx";
            } else {
                tempUrl = "static/word/pssr/hbssvoc.xlsx";
            }
            InputStream is = null;
            is = Thread.currentThread().getContextClassLoader().getResourceAsStream(tempUrl);
            XSSFWorkbook wb = null;
            wb = new XSSFWorkbook(is);
            XSSFSheet sheet = wb.getSheetAt(0);

            //填充数据
            int rowIndex = 2;
            int num = 1;

            Row originalRow = sheet.getRow(2);
            Cell originalcell = originalRow.getCell(0);
            // 获取单元格样式
            CellStyle originalStyle = originalcell.getCellStyle();

            for (TPssrTorchvoc t : list) {
                Row row = sheet.createRow(rowIndex);
                row.setHeight((short) 800);
                row.createCell(0).setCellValue(num);
                row.createCell(1).setCellValue(t.getContent());
                row.createCell(2).setCellValue(t.getProcedureStatus());
                row.createCell(3);
                row.createCell(4);
                try {
                    SysUser sysUser1 = sysUserService.selectUserById(Long.valueOf(t.getConfirm1()));
                    SysUser sysUser2 = sysUserService.selectUserById(Long.valueOf(t.getConfirm2()));
                    String confirm1 =  sysUser1.getSignUrl();
                    String confirm2 =  sysUser2.getSignUrl();
                    ExcelUtils.insertPicture(wb, sheet, confirm1, row.getRowNum(), 3, 1, 1);
                    ExcelUtils.insertPicture(wb, sheet, confirm2, row.getRowNum(), 4, 1, 1);
                } catch (Exception e) {

                }
                row.createCell(5).setCellValue(DateUtils.dateTime(t.getConfirmationDate()));
                row.createCell(6).setCellValue(t.getRemarks());

                //渲染样式
                for (int i = 0; i < 7; i++) {
                    row.getCell(i).setCellStyle(originalStyle);
                }
                num++;
                rowIndex++;
            }
            if ("1".equals(torchvocType)) {
                filename = "PSSR_18_环保设施_火炬"  + ".xlsx";
            } else {
                filename = "PSSR_18_环保设施_VOC"  + ".xlsx";
            }
            out = new FileOutputStream(ExcelUtil.getAbsoluteFile(filename));
            wb.write(out);
            wb.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return filename;
    }

    /**
     * 获取火炬，VOC系统详细信息
     */
    @PreAuthorize("@ss.hasPermi('pssr:torchvoc:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        TPssrTorchvoc item = tPssrTorchvocService.selectTPssrTorchvocById(id);
        
            List<TPssrFile> tPssrFiles = tPssrFileService.selectTPssrFileListByItem(item.getSubId(), item.getId(), forShort);
            item.setFileList(tPssrFiles);
            item.setFileNum((long) tPssrFiles.size());
            if (item.getApproveStatus() != 2)
                item.setReason(tPssrTurndownService.selectTPssrTurndownByItem(item.getSubId(), item.getId(), "hbss"));
        return AjaxResult.success(item);
    }

    /**
     * 新增火炬，VOC系统
     */
    @PreAuthorize("@ss.hasPermi('pssr:torchvoc:add')")
    @Log(title = "火炬，VOC系统", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TPssrTorchvoc tPssrTorchvoc) {
        if (StringUtils.isNotEmpty(tPssrTorchvoc.getConfirm1())&&tPssrTorchvoc.getConfirm1().equals(tPssrTorchvoc.getConfirm2())) {
            return AjaxResult.error("确认人不能为同一人，请重新选择！");
        }
        tPssrTorchvoc.setApproveStatus(0L);
        return toAjax(tPssrTorchvocService.insertTPssrTorchvoc(tPssrTorchvoc));
    }

    /**
     * 修改火炬，VOC系统
     */
    @PreAuthorize("@ss.hasPermi('pssr:torchvoc:edit')")
    @Log(title = "火炬，VOC系统", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TPssrTorchvoc tPssrTorchvoc) {
        TPssrTorchvoc entity = tPssrTorchvocService.selectTPssrTorchvocById(tPssrTorchvoc.getId());
        if (entity.getApproveStatus() != 1 && entity.getApproveStatus() != 0) {
            return  AjaxResult.error("当前状态不可修改！");
        }
        if (tPssrTorchvoc.getConfirm1().equals(tPssrTorchvoc.getConfirm2())){
            return AjaxResult.error("确认人不能为同一人，请重新选择！");
        }
        tPssrFileService.updateFileRelevance(tPssrTorchvoc.getFileIds(), "hbss", tPssrTorchvoc.getId(), tPssrTorchvoc.getSubId());
        return toAjax(tPssrTorchvocService.updateTPssrTorchvoc(tPssrTorchvoc));
    }

    /**
     * 修改火炬，VOC系统
     */
    @PreAuthorize("@ss.hasPermi('pssr:torchvoc:edit')")
    @Log(title = "火炬，VOC系统", businessType = BusinessType.UPDATE)
    @PutMapping("/editBatch")
    public AjaxResult editb(@RequestBody TPssrTorchvoc tPssrTorchvoc) {
        if (tPssrTorchvoc.getConfirm1().equals(tPssrTorchvoc.getConfirm2())){
            return AjaxResult.error("确认人不能为同一人，请重新选择！");
        }
        return toAjax(tPssrTorchvocMapper.updateTPssrTorchvocByIds(tPssrTorchvoc));
    }
    /**
     * 删除火炬，VOC系统
     */
    @PreAuthorize("@ss.hasPermi('pssr:torchvoc:remove')")
    @Log(title = "火炬，VOC系统", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tPssrTorchvocService.deleteTPssrTorchvocByIds(ids));
    }


    /**
     * 确认火炬，VOC系统
     */
    @PreAuthorize("@ss.hasPermi('pssr:torchvoc:edit')")
    @Log(title = "火炬，VOC系统", businessType = BusinessType.UPDATE)
    @PutMapping("/confirmTorchvoc")
    public AjaxResult confirmTorchvoc(@RequestBody TPssrTorchvoc tPssrTorchvoc) {
        long queryStatus = 0;
        long approveStatus = 0;
        Date date = null;
        TPssrTorchvoc lock = new TPssrTorchvoc();
        if (tPssrTorchvoc.getTaskType() == 4) {
            //拆锁确认
            queryStatus = 1;
            approveStatus = 3;
            lock.setConfirm1(getUserId().toString());
            date = new Date();
        } else if (tPssrTorchvoc.getTaskType() == 5) {
            //上锁确认
            queryStatus = 3;
            approveStatus = 2;
            lock.setConfirm2(getUserId().toString());
            date = new Date();
        }
        // 修改状态
        if (tPssrTorchvoc.getIds() != null && tPssrTorchvoc.getIds().length > 0) {
            for (Long id : tPssrTorchvoc.getIds()) {
                TPssrTorchvoc item = tPssrTorchvocService.selectTPssrTorchvocById(id);
                item.setApproveStatus(approveStatus);
                if (queryStatus == 3) {
                    if ("火炬系统检修时所加装的盲板已拆除。".equals(item.getContent())) {
                        TPssrBlind tPssrBlind = new TPssrBlind();
                        tPssrBlind.setSubId(item.getSubId());
                        TPssrBlind blind = tPssrBlindService.selectTPssrBlindList(tPssrBlind).get(0);
                        item.setConfirmationDate(blind.getInstallDate());
                    } else {
                        item.setConfirmationDate(date);
                    }
                }
                tPssrTorchvocService.updateTPssrTorchvoc(item);
            }
        } else {
            lock.setSubId(tPssrTorchvoc.getSubId());
            lock.setApproveStatus(queryStatus);
            lock.setTorchvocType(tPssrTorchvoc.getTorchvocType());
            for (TPssrTorchvoc item : tPssrTorchvocService.selectTPssrTorchvocList(lock)) {
                if (queryStatus == 3) {
                    if ("火炬系统检修时所加装的盲板已拆除。".equals(item.getContent())) {
                        //查询当前检查内容数据
                        TPssrSubcontent subcontent = tPssrSubcontentService.selectTPssrSubcontentById(item.getSubId());
                        //根据主表id查询盲板数据
                        TPssrSubcontent pssrSubcontent = new TPssrSubcontent();
                        pssrSubcontent.setForShort("mb");
                        pssrSubcontent.setAboveallId(subcontent.getAboveallId());
                        TPssrSubcontent tPssrSubcontent = tPssrSubcontentService.selectTPssrSubcontentList(pssrSubcontent).get(0);
                        //设置确认时间为盲板的确认时间
                        TPssrBlind tPssrBlind = new TPssrBlind();
                        tPssrBlind.setSubId(tPssrSubcontent.getId());
                        TPssrBlind blind = tPssrBlindService.selectTPssrBlindList(tPssrBlind).get(0);
                        item.setConfirmationDate(blind.getInstallDate());
                    } else {
                        item.setConfirmationDate(date);
                    }
                }
                item.setApproveStatus(approveStatus);
                tPssrTorchvocService.updateTPssrTorchvoc(item);
            }
        }
        //查询当前待审批的确认人
        TPssrTorchvoc entity = new TPssrTorchvoc();
        entity.setSubId(tPssrTorchvoc.getSubId());
        entity.setApproveStatus(queryStatus);
        for (TPssrTorchvoc item : tPssrTorchvocService.selectTPssrTorchvocList(entity)) {
            if (tPssrTorchvoc.getTaskType() == 4) {
                if (item.getConfirm1().equals(getUserId().toString())) {
                    return AjaxResult.success();
                }
            } else if (tPssrTorchvoc.getTaskType() == 5) {
                if (item.getConfirm2().equals(getUserId().toString())) {
                    return AjaxResult.success();
                }
            }
        }

        //无待审批任务结束当前用户流程

        // 因为流程关系所以approve一定会有且只有一条数据
        TPssrApprove tPssrApprove = tPssrApproveService.selectTPssrApproveBySubId(tPssrTorchvoc.getSubId());
        TPssrApproveController.handleConfirmApprove(tPssrApprove, getUserId().toString());
        return AjaxResult.success();

    }

    /**
     * 驳回火炬，VOC系统
     */
    @PutMapping("/turnDownTorchvoc")
    public AjaxResult turnDownTorchvoc(@RequestBody List<TPssrTorchvoc> tPssrTorchvoc) {
        if (CollectionUtils.isNotEmpty(tPssrTorchvoc)) {
            String userId = getUserId().toString();
            Long subId = tPssrTorchvoc.get(0).getSubId();
            // 修改已选择数据的状态
            for (TPssrTorchvoc item : tPssrTorchvoc) {
                TPssrTorchvoc blind = new TPssrTorchvoc();
                blind.setId(item.getId());
                blind.setApproveStatus(1L);
                blind.setUpdatedate(new Date());
                blind.setUpdaterCode(getUserId().toString());
                tPssrTorchvocService.updateTPssrTorchvoc(blind);
                // 新增驳回原因数据
                TPssrTurndown turndown = new TPssrTurndown();
                turndown.setForShort(forShort);
                turndown.setSubId(item.getSubId());
                turndown.setItemId(item.getId());
                turndown.setReason(item.getReason());
                turndown.setCreatedate(new Date());
                turndown.setCreaterCode(getUserId().toString());
                tPssrTurndownService.insertTPssrTurndown(turndown);
            }
            // 查询当前流程
            TPssrApprove approve = tPssrApproveService.selectTPssrApproveBySubId(subId);

            ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
            TaskService taskService = processEngine.getTaskService();
            Task task = processEngine.getTaskService()//获取任务service
                    .createTaskQuery()//创建查询对象
                    .taskAssignee(userId)
                    .processInstanceId(approve.getProcessId()).singleResult();
            String taskId = task.getId();

            // 驳回 查询所有待审批的人员
            TPssrTorchvoc blind = new TPssrTorchvoc();
            blind.setSubId(subId);
            blind.setApproveStatus(1L);
            Set<String> installer = new HashSet<>();
            Set<String> remover = new HashSet<>();
            for (TPssrTorchvoc item : tPssrTorchvocService.selectTPssrTorchvocList(blind)) {

                // 安装人员
                installer.add(item.getConfirm1());

                //拆除人员
                remover.add(item.getConfirm2());
            }


            //处理流程节点
            Map<String, Object> param = new HashMap<>();
            param.put("condition", 1);
            param.put("confirmUsers1", new ArrayList<>(installer));
            param.put("confirmUsers2", new ArrayList<>(remover));
            //认领任务
            processEngine.getTaskService().claim(taskId, userId);
            taskService.addComment(taskId, approve.getProcessId(), "驳回");
            taskService.complete(taskId, param);

            // 修改审批表和sub表
            approve.setApproveStatus(1L);
            approve.setUpdatedate(new Date());
            approve.setUpdaterCode(getUserId().toString());
            tPssrApproveService.updateTPssrApprove(approve);

            TPssrSubcontent subcontent = new TPssrSubcontent();
            subcontent.setId(approve.getSubId());
            subcontent.setApproveStatus(1L);
            subcontent.setUpdatedate(new Date());
            subcontent.setUpdaterCode(getUserId().toString());
            tPssrSubcontentService.updateTPssrSubcontent(subcontent);
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }
}
