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.TPssrLightingMapper;
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.*;

/**
 * 照明Controller
 *
 * @author ssy
 * @date 2024-09-18
 */
@RestController
@RequestMapping("/pssr/lighting")
public class TPssrLightingController extends BaseController {
    @Autowired
    private ITPssrFileService tPssrFileService;
    @Resource
    private TPssrLightingMapper tPssrLightingMapper;
    @Autowired
    private ITPssrTurndownService tPssrTurndownService;
    @Autowired
    private ITPssrLightingService tPssrLightingService;

    @Autowired
    private ITPssrApproveService tPssrApproveService;

    @Autowired
    private ITPssrSubcontentService tPssrSubcontentService;

    @Autowired
    private ISysUserService sysUserService;
    private String forShort = "zmdbr";

    /**
     * 查询照明列表
     */
    @PreAuthorize("@ss.hasPermi('pssr:lighting:list')")
    @GetMapping("/list")
    public TableDataInfo list(TPssrLighting tPssrLighting) {
        try {
            TPssrApprove approve = tPssrApproveService.selectTPssrApproveBySubId(tPssrLighting.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")){
                        tPssrLighting.setConfirm1(getUserId().toString());
                    }else if (task.getName().equals("确认人2")){
                       tPssrLighting.setConfirm2(getUserId().toString());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("待办确认人查询报错：{}",e.getMessage());
        }
        startPage();
        List<TPssrLighting> list = tPssrLightingService.selectTPssrLightingList(tPssrLighting);
        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(), "zmdbr"));
        });
        return getDataTable(list);
    }

    /**
     * 导出照明列表
     */
    @PreAuthorize("@ss.hasPermi('pssr:lighting:export')")
    @Log(title = "照明", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TPssrLighting tPssrLighting) {
        List<TPssrLighting> list = tPssrLightingService.selectTPssrLightingList(tPssrLighting);
        if (list.size() != 0) {
            return AjaxResult.success(exportTmpl(list, tPssrLighting.getLightingType()));
        } else {
            return AjaxResult.error("暂无可导出数据");
        }
    }

    public String exportTmpl(List<TPssrLighting> list, String LightingType) {
        OutputStream out = null;
        String filename = null;
        try {
            String tempUrl = ""; // 模板文件
            if ("1".equals(LightingType)) {
                tempUrl = "static/word/pssr/zm.xlsx";
            } else {
                tempUrl = "static/word/pssr/dbr.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 (TPssrLighting t : list) {
                Row row = sheet.createRow(rowIndex);
                row.setHeight((short) 800);
                row.createCell(0).setCellValue(num);
                row.createCell(1).setCellValue(t.getCheckContent());
                row.createCell(2).setCellValue(t.getCheckResult());
                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(LightingType)) {
                filename = "PSSR_28_照明"  + ".xlsx";
            } else {
                filename = "PSSR_28_电伴热"  + ".xlsx";
            }
            out = new FileOutputStream(ExcelUtil.getAbsoluteFile(filename));
            wb.write(out);
            wb.close();

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

    /**
     * 获取照明详细信息
     */
    @PreAuthorize("@ss.hasPermi('pssr:lighting:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        TPssrLighting item = tPssrLightingService.selectTPssrLightingById(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(), "zmdbr"));
        return AjaxResult.success(item);
    }

    /**
     * 新增照明
     */
    @PreAuthorize("@ss.hasPermi('pssr:lighting:add')")
    @Log(title = "照明", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TPssrLighting tPssrLighting) {
        if (StringUtils.isNotEmpty(tPssrLighting.getConfirm1())&&tPssrLighting.getConfirm1().equals(tPssrLighting.getConfirm2())) {
            return AjaxResult.error("确认人不能为同一人，请重新选择！");
        }
        tPssrLighting.setApproveStatus(0L);
        return toAjax(tPssrLightingService.insertTPssrLighting(tPssrLighting));
    }

    /**
     * 修改照明
     */
    @PreAuthorize("@ss.hasPermi('pssr:lighting:edit')")
    @Log(title = "照明", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TPssrLighting tPssrLighting) {
        TPssrLighting entity = tPssrLightingService.selectTPssrLightingById(tPssrLighting.getId());
        if (entity.getApproveStatus() != 1 && entity.getApproveStatus() != 0) {
            return  AjaxResult.error("当前状态不可修改！");
        }
        if (tPssrLighting.getConfirm1().equals(tPssrLighting.getConfirm2())){
            return AjaxResult.error("确认人不能为同一人，请重新选择！");
        }
        tPssrFileService.updateFileRelevance(tPssrLighting.getFileIds(), "zmdbr", tPssrLighting.getId(), tPssrLighting.getSubId());
        return toAjax(tPssrLightingService.updateTPssrLighting(tPssrLighting));
    }

    /**
     * 修改照明
     */
    @PreAuthorize("@ss.hasPermi('pssr:lighting:edit')")
    @Log(title = "照明", businessType = BusinessType.UPDATE)
    @PutMapping("/editBatch")
    public AjaxResult editb(@RequestBody TPssrLighting tPssrLighting) {
        if (tPssrLighting.getConfirm1().equals(tPssrLighting.getConfirm2())){
            return AjaxResult.error("确认人不能为同一人，请重新选择！");
        }
        return toAjax(tPssrLightingMapper.updateTPssrLightingByIds(tPssrLighting));
    }


    /**
     * 删除照明
     */
    @PreAuthorize("@ss.hasPermi('pssr:lighting:remove')")
    @Log(title = "照明", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tPssrLightingService.deleteTPssrLightingByIds(ids));
    }


    /**
     * 确认照明，电伴热
     */
    @PreAuthorize("@ss.hasPermi('pssr:lighting:edit')")
    @Log(title = "照明，电伴热", businessType = BusinessType.UPDATE)
    @PutMapping("/confirmLighting")
    public AjaxResult Lighting(@RequestBody TPssrLighting tPssrLighting) {
        long queryStatus = 0;
        long approveStatus = 0;
        Date date = null;
        TPssrLighting lock = new TPssrLighting();
        if (tPssrLighting.getTaskType() == 4) {
            //拆锁确认
            queryStatus = 1;
            approveStatus = 3;
            date = new Date();
            lock.setConfirm1(getUserId().toString());
        } else if (tPssrLighting.getTaskType() == 5) {
            //上锁确认
            queryStatus = 3;
            approveStatus = 2;
            date = new Date();
            lock.setConfirm2(getUserId().toString());
        }
        // 修改状态
        if (tPssrLighting.getIds() != null && tPssrLighting.getIds().length > 0) {
            for (Long id : tPssrLighting.getIds()) {
                TPssrLighting item = tPssrLightingService.selectTPssrLightingById(id);
                item.setApproveStatus(approveStatus);
                if (queryStatus == 3) {
                    item.setConfirmationDate(date);
                }
                tPssrLightingService.updateTPssrLighting(item);
            }
        } else {
            lock.setSubId(tPssrLighting.getSubId());
            lock.setApproveStatus(queryStatus);
            lock.setLightingType(tPssrLighting.getLightingType());
            for (TPssrLighting item : tPssrLightingService.selectTPssrLightingList(lock)) {
                if (queryStatus == 3) {
                    item.setConfirmationDate(date);
                }
                item.setApproveStatus(approveStatus);
                tPssrLightingService.updateTPssrLighting(item);
            }
        }
        //查询当前待审批的确认人
        TPssrLighting entity = new TPssrLighting();
        entity.setSubId(tPssrLighting.getSubId());
        entity.setApproveStatus(queryStatus);
        for (TPssrLighting item : tPssrLightingService.selectTPssrLightingList(entity)) {
            if (tPssrLighting.getTaskType() == 4) {
                if (item.getConfirm1().equals(getUserId().toString())) {
                    return AjaxResult.success();
                }
            } else if (tPssrLighting.getTaskType() == 5) {
                if (item.getConfirm2().equals(getUserId().toString())) {
                    return AjaxResult.success();
                }
            }
        }

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

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

    }

    /**
     * 驳回照明，电伴热
     */
    @PutMapping("/turnDownLighting")
    public AjaxResult turnDownLighting(@RequestBody List<TPssrLighting> tPssrLighting) {
        if (CollectionUtils.isNotEmpty(tPssrLighting)) {
            String userId = getUserId().toString();
            Long subId = tPssrLighting.get(0).getSubId();
            // 修改已选择数据的状态
            for (TPssrLighting item : tPssrLighting) {
                TPssrLighting blind = new TPssrLighting();
                blind.setId(item.getId());
                blind.setApproveStatus(1L);
                blind.setUpdatedate(new Date());
                blind.setUpdaterCode(getUserId().toString());
                tPssrLightingService.updateTPssrLighting(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();

            // 驳回 查询所有待审批的人员
            TPssrLighting blind = new TPssrLighting();
            blind.setSubId(subId);
            blind.setApproveStatus(1L);
            Set<String> installer = new HashSet<>();
            Set<String> remover = new HashSet<>();
            for (TPssrLighting item : tPssrLightingService.selectTPssrLightingList(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();
    }
}
