package com.ruoyi.project.pssr.controller;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.ExcelUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
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.config.RuoYiConfig;
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.TPssrApprove;
import com.ruoyi.project.pssr.domain.TPssrProgramme;
import com.ruoyi.project.pssr.domain.TPssrSubcontent;
import com.ruoyi.project.pssr.domain.TPssrTurndown;
import com.ruoyi.project.pssr.mapper.TPssrProgrammeMapper;
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 org.springframework.web.multipart.MultipartFile;

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/programme")
public class TPssrProgrammeController extends BaseController {
    @Resource
     private TPssrProgrammeMapper tPssrProgrammeMapper;
    @Autowired
    private ITPssrFileService tPssrFileService;

    @Autowired
    private ITPssrTurndownService tPssrTurndownService;
    @Autowired
    private ITPssrProgrammeService tPssrProgrammeService;

    @Autowired
    private ITPssrApproveService tPssrApproveService;

    @Autowired
    private ITPssrSubcontentService tPssrSubcontentService;

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


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

    /**
     * 导出开工方案列表
     */
    @PreAuthorize("@ss.hasPermi('pssr:programme:export')")
    @Log(title = "开工方案", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TPssrProgramme tPssrProgramme) {
        List<TPssrProgramme> list = tPssrProgrammeService.selectTPssrProgrammeList(tPssrProgramme);
        if (list.size() != 0) {
            return AjaxResult.success(exportTmpl(list));
        } else {
            return AjaxResult.error("暂无可导出数据");
        }
    }

    public String exportTmpl(List<TPssrProgramme> list) {
        OutputStream out = null;
        String filename = null;
        try {
            String tempUrl = "static/word/pssr/kgfa.xlsx"; // 模板文件
            InputStream is = null;
            is = Thread.currentThread().getContextClassLoader().getResourceAsStream(tempUrl);
            XSSFWorkbook wb = null;
            wb = new XSSFWorkbook(is);
            XSSFSheet sheet = wb.getSheetAt(0);

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

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

            for (TPssrProgramme t : list) {
                Row row = sheet.createRow(rowIndex);
                row.setHeight((short) 800);
                row.createCell(0).setCellValue(num);
                row.createCell(1).setCellValue(t.getUnit());
                row.createCell(2).setCellValue(t.getFileName());
                row.createCell(3).setCellValue(t.getWriteDone());
                row.createCell(4).setCellValue(t.getCheckDone());
                row.createCell(5).setCellValue(t.getTrainDone());
                row.createCell(6);
                row.createCell(7);
                try {
                    SysUser sysUser = sysUserService.selectUserById(Long.valueOf(t.getConfirm1()));
                    SysUser sysUser2 = sysUserService.selectUserById(Long.valueOf(t.getConfirm2()));
                    String confirm1 = sysUser.getSignUrl();
                    String confirm2 = sysUser2.getSignUrl();
                    ExcelUtils.insertPicture(wb, sheet, confirm1, row.getRowNum(), 6, 1, 1);
                    ExcelUtils.insertPicture(wb, sheet, confirm2, row.getRowNum(), 7, 1, 1);
                } catch (Exception e) {

                }
                row.createCell(8).setCellValue(t.getRemarks());


                //渲染样式
                for (int i = 0; i < 9; i++) {
                    row.getCell(i).setCellStyle(originalStyle);
                }
                num++;
                rowIndex++;
            }
            filename = "PSSR_02_开工方案"  + ".xlsx";
            out = new FileOutputStream(ExcelUtil.getAbsoluteFile(filename));
            wb.write(out);
            wb.close();

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

    /**
     * 获取开工方案详细信息
     */
    @PreAuthorize("@ss.hasPermi('pssr:programme:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tPssrProgrammeService.selectTPssrProgrammeById(id));
    }

    /**
     * 新增开工方案
     */
    @PreAuthorize("@ss.hasPermi('pssr:programme:add')")
    @Log(title = "开工方案", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TPssrProgramme tPssrProgramme) {
        if (StringUtils.isNotEmpty(tPssrProgramme.getConfirm1())&&tPssrProgramme.getConfirm1().equals(tPssrProgramme.getConfirm2())) {
            return AjaxResult.error("确认人不能为同一人，请重新选择！");
        }
        return toAjax(tPssrProgrammeService.insertTPssrProgramme(tPssrProgramme));
    }

    /**
     * 修改开工方案
     */
    @PreAuthorize("@ss.hasPermi('pssr:programme:edit')")
    @Log(title = "开工方案", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TPssrProgramme tPssrProgramme)
    {
        if (tPssrProgramme.getConfirm1().equals(tPssrProgramme.getConfirm2())){
            return AjaxResult.error("确认人不能为同一人，请重新选择！");
        }
        return toAjax(tPssrProgrammeService.updateTPssrProgramme(tPssrProgramme));
    }

    /**
     * 修改开工方案
     */
    @PreAuthorize("@ss.hasPermi('pssr:programme:edit')")
    @Log(title = "开工方案", businessType = BusinessType.UPDATE)
    @PutMapping("/editBatch")
    public AjaxResult editb(@RequestBody TPssrProgramme tPssrProgramme)
    {
        if (tPssrProgramme.getConfirm1().equals(tPssrProgramme.getConfirm2())){
            return AjaxResult.error("确认人不能为同一人，请重新选择！");
        }
        return toAjax(tPssrProgrammeMapper.updateTPssrProgrammeByIds(tPssrProgramme));
    }

    /**
     * 删除开工方案
     */
    @PreAuthorize("@ss.hasPermi('pssr:programme:remove')")
    @Log(title = "开工方案", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tPssrProgrammeService.deleteTPssrProgrammeByIds(ids));
    }

    /**
     * 确认设计变更
     */
    @PreAuthorize("@ss.hasPermi('pssr:programme:edit')")
    @Log(title = "设计变更", businessType = BusinessType.UPDATE)
    @PutMapping("/confirmProgramme")
    public AjaxResult confirmProgramme(@RequestBody TPssrProgramme tPssrProgramme) {
        long queryStatus = 0;
        long approveStatus = 0;
        Date date = null;
        TPssrProgramme lock = new TPssrProgramme();
        if (tPssrProgramme.getTaskType() == 4) {
            //确认人1确认
            queryStatus = 1;
            approveStatus = 3;
            date = new Date();
            lock.setConfirm1(getUserId().toString());
        } else if (tPssrProgramme.getTaskType() == 5) {
            //确认人2确认
            queryStatus = 3;
            approveStatus = 2;
            date = new Date();
            lock.setConfirm2(getUserId().toString());
        }
        // 修改状态
        if (tPssrProgramme.getIds() != null && tPssrProgramme.getIds().length > 0) {
            for (Long id : tPssrProgramme.getIds()) {
                TPssrProgramme item = tPssrProgrammeService.selectTPssrProgrammeById(id);
                item.setApproveStatus(approveStatus);
                tPssrProgrammeService.updateTPssrProgramme(item);
            }
        } else {
            lock.setSubId(tPssrProgramme.getSubId());
            lock.setApproveStatus(queryStatus);
            for (TPssrProgramme item : tPssrProgrammeService.selectTPssrProgrammeList(lock)) {
                item.setApproveStatus(approveStatus);
                tPssrProgrammeService.updateTPssrProgramme(item);
            }
        }
        //查询当前待审批的确认人
        TPssrProgramme entity = new TPssrProgramme();
        entity.setSubId(tPssrProgramme.getSubId());
        entity.setApproveStatus(queryStatus);
        for (TPssrProgramme item : tPssrProgrammeService.selectTPssrProgrammeList(entity)) {
            if (tPssrProgramme.getTaskType() == 4) {
                if (item.getConfirm1().equals(getUserId().toString())) {
                    return AjaxResult.success();
                }
            } else if (tPssrProgramme.getTaskType() == 5) {
                if (item.getConfirm2().equals(getUserId().toString())) {
                    return AjaxResult.success();
                }
            }
        }

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

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

    }

    /**
     * 驳回设计变更
     */
    @PutMapping("/turnDownProgramme")
    public AjaxResult turnDownProgramme(@RequestBody List<TPssrProgramme> tPssrProgramme) {
        if (CollectionUtils.isNotEmpty(tPssrProgramme)) {
            String userId = getUserId().toString();
            Long subId = tPssrProgramme.get(0).getSubId();
            // 修改已选择数据的状态
            for (TPssrProgramme item : tPssrProgramme) {
                TPssrProgramme blind = new TPssrProgramme();
                blind.setId(item.getId());
                blind.setApproveStatus(1L);
                blind.setUpdatedate(new Date());
                blind.setUpdaterCode(getUserId().toString());
                tPssrProgrammeService.updateTPssrProgramme(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();

            // 驳回 查询所有待审批的人员
            TPssrProgramme blind = new TPssrProgramme();
            blind.setSubId(subId);
            blind.setApproveStatus(1L);
            Set<String> confirm1 = new HashSet<>();
            Set<String> confirm2 = new HashSet<>();
            for (TPssrProgramme item : tPssrProgrammeService.selectTPssrProgrammeList(blind)) {

                // 确认人1
                confirm1.add(item.getConfirm1());

                // 确认人2
                confirm2.add(item.getConfirm2());
            }


            //处理流程节点
            Map<String, Object> param = new HashMap<>();
            param.put("condition", 1);
            param.put("confirmUsers1", new ArrayList<>(confirm1));
            param.put("confirmUsers2", new ArrayList<>(confirm2));
            //认领任务
            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();
    }


    @Log(title = "仪联锁测试附件上传", businessType = BusinessType.UPDATE)
    @PostMapping("/uploadFile")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file, Long subId) throws IOException {
        if (!file.isEmpty()) {
            String url = FileUploadUtils.upload(RuoYiConfig.getFilePath("/pssr/programme"), file);
            TPssrProgramme test = new TPssrProgramme();
            test.setSubId(subId);
            test.setFileUrl(url);
            test.setFileName(file.getOriginalFilename());
            test.setWriteDone("Y");
            test.setCheckDone("N");
            test.setTrainDone("N");
            test.setApproveStatus(0L);
            test.setCreatedate(new Date());
            test.setCreaterCode(getUserId().toString());
            tPssrProgrammeService.insertTPssrProgramme(test);
            return AjaxResult.success();
        }
        return AjaxResult.error("上传失败，请联系管理员");
    }
}
