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.process.domain.TMoc;
import com.ruoyi.project.process.service.ITMocService;
import com.ruoyi.project.pssr.domain.*;
import com.ruoyi.project.pssr.mapper.TPssrMocMapper;
import com.ruoyi.project.pssr.service.*;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysDictDataService;
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.*;

/**
 * MOC完成确认清单Controller
 *
 * @author ssy
 * @date 2024-10-31
 */
@RestController
@RequestMapping("/pssr/moc")
public class TPssrMocController extends BaseController {
    @Resource
    private TPssrMocMapper tPssrMocMapper;
    @Autowired
    private ITPssrFileService tPssrFileService;

    @Autowired
    private ITPssrTurndownService tPssrTurndownService;

    @Autowired
    private ITPssrMocService tPssrMocService;

    @Autowired
    private ITPssrApproveService tPssrApproveService;

    @Autowired
    private ITPssrSubcontentService tPssrSubcontentService;

    @Autowired
    private ITPssrAboveallService tPssraboveallService;

    @Autowired
    private ITMocService tMocService;

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

    @Autowired
    private ISysDictDataService sysDictDataService;

    /**
     * 查询MOC完成确认清单列表
     */
    @PreAuthorize("@ss.hasPermi('pssr:moc:list')")
    @GetMapping("/list")
    public TableDataInfo list(TPssrMoc tPssrMoc) {
        try {
            TPssrApprove approve = tPssrApproveService.selectTPssrApproveBySubId(tPssrMoc.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")){
                        tPssrMoc.setConfirm1(getUserId().toString());
                    }else if (task.getName().equals("确认人2")){
                       tPssrMoc.setConfirm2(getUserId().toString());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("待办确认人查询报错：{}",e.getMessage());
        }
        startPage();
        List<TPssrMoc> list = tPssrMocService.selectTPssrMocList(tPssrMoc);
        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(), forShort));
        });
        return getDataTable(list);
    }

    /**
     * 导出MOC完成确认清单列表
     */
    @PreAuthorize("@ss.hasPermi('pssr:moc:export')")
    @Log(title = "MOC完成确认清单", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TPssrMoc tPssrMoc) {
        List<TPssrMoc> list = tPssrMocService.selectTPssrMocList(tPssrMoc);
        if (list.size() != 0) {
            return AjaxResult.success(exportTmpl(list));
        } else {
            return AjaxResult.error("暂无可导出数据");
        }
    }

    public String exportTmpl(List<TPssrMoc> list) {
        OutputStream out = null;
        String filename = null;
        try {
            String tempUrl = "static/word/pssr/sjbg.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 (TPssrMoc t : list) {
                Row row = sheet.createRow(rowIndex);
                row.setHeight((short) 800);
                row.createCell(0).setCellValue(num);
                row.createCell(1).setCellValue(t.getRegion());
                row.createCell(2).setCellValue(t.getMocNo());
                row.createCell(3).setCellValue(t.getTitle());
                row.createCell(4).setCellValue(t.getDocUpdate());
                row.createCell(5).setCellValue(t.getTraining());
                row.createCell(6).setCellValue(t.getPssr());
                row.createCell(7);
                row.createCell(8);
                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(), 7, 1, 1);
                    ExcelUtils.insertPicture(wb, sheet, confirm2, row.getRowNum(), 8, 1, 1);
                } catch (Exception e) {

                }
                row.createCell(9).setCellValue(DateUtils.dateTime(t.getConfirmationDate()));
                row.createCell(10).setCellValue(t.getRemarks());


                //渲染样式
                for (int i = 0; i < 11; i++) {
                    row.getCell(i).setCellStyle(originalStyle);
                }
                num++;
                rowIndex++;
            }
            filename = "PSSR_03_设计变更"  + ".xlsx";
            out = new FileOutputStream(ExcelUtil.getAbsoluteFile(filename));
            wb.write(out);
            wb.close();

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

    /**
     * 获取MOC完成确认清单详细信息
     */
    @PreAuthorize("@ss.hasPermi('pssr:moc:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        TPssrMoc item = tPssrMocService.selectTPssrMocById(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(), forShort));
        return AjaxResult.success(item);
    }

    /**
     * 新增MOC完成确认清单
     */
    @PreAuthorize("@ss.hasPermi('pssr:moc:add')")
    @Log(title = "MOC完成确认清单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TPssrMoc tPssrMoc) {
        if (StringUtils.isNotEmpty(tPssrMoc.getConfirm1())&&tPssrMoc.getConfirm1().equals(tPssrMoc.getConfirm2())) {
            return AjaxResult.error("确认人不能为同一人，请重新选择！");
        }
        return toAjax(tPssrMocService.insertTPssrMoc(tPssrMoc));
    }

    //导入时判断更新或新增
    private int insertOrUpdate(TPssrMoc item) {
        TPssrMoc entity = new TPssrMoc();
        entity.setSubId(item.getSubId());
        entity.setMocNo(item.getMocNo());
        List<TPssrMoc> list = tPssrMocService.selectTPssrMocList(entity);
        if (CollectionUtils.isNotEmpty(list)) {
            item.setId(list.get(0).getId());
            return tPssrMocService.updateTPssrMoc(item);
        } else {
            return tPssrMocService.insertTPssrMoc(item);
        }
    }

    @PreAuthorize("@ss.hasPermi('pssr:moc:add')")
    @Log(title = "MOC完成确认清单", businessType = BusinessType.INSERT)
    @PostMapping("/syncMoc")
    public AjaxResult syncMoc(@RequestBody TPssrMoc tPssrMoc) {
        if (StringUtils.isEmpty(tPssrMoc.getRemarks())) {
            tPssrMoc.setRemarks("TRA2025");
        }
        TPssrSubcontent subcontent = tPssrSubcontentService.selectTPssrSubcontentById(tPssrMoc.getSubId());
        TPssrAboveall tPssrAboveall = tPssraboveallService.selectTPssrAboveallById(subcontent.getAboveallId());

        TMoc tMoc = new TMoc();
        // 永久moc
//        tMoc.setTimeliness("1");
        if (tPssrAboveall.getRegion().equals("裂解")){
            tMoc.setAreas(new String[]{"10","20","21","22"});
        }
        if (tPssrAboveall.getRegion().equals("压缩")){
            tMoc.setAreas(new String[]{"12","20","21","22"});
        }
        if (tPssrAboveall.getRegion().equals("分离")){
            tMoc.setAreas(new String[]{"14","20","21","22"});
        }
        if (tPssrAboveall.getRegion().equals("AEU")){
            tMoc.setAreas(new String[]{"16","20","21","22"});
        }
        if (tPssrAboveall.getRegion().equals("PGU")){
            tMoc.setAreas(new String[]{"18","20","21","22"});
        }
        tMoc.setRemarks(tPssrMoc.getRemarks());
        for (TMoc moc : tMocService.selectTMocList(tMoc)) {
            TPssrMoc pssrMoc = new TPssrMoc();
            pssrMoc.setSubId(tPssrMoc.getSubId());
            pssrMoc.setRegion(sysDictDataService.selectDictLabel("MOC_AREA", moc.getArea()));
            pssrMoc.setMocNo(moc.getCompanyMocNo());
            pssrMoc.setTitle(moc.getTitle());
            pssrMoc.setDocUpdate(!Objects.isNull(moc.getDocUpdate()) ? "Y" : "N");
            pssrMoc.setTraining(!Objects.isNull(moc.getTraining()) ? "Y" : "N");
            pssrMoc.setPssr(!Objects.isNull(moc.getPssr()) ? "Y" : "N");
            pssrMoc.setCreaterCode(getUserId().toString());
            pssrMoc.setCreatedate(new Date());
            pssrMoc.setApproveStatus(0L);
            upOrIn(pssrMoc);
        }
        return AjaxResult.success();
    }

    private void upOrIn(TPssrMoc tPssrMoc) {
        TPssrMoc moc = new TPssrMoc();
        moc.setMocNo(tPssrMoc.getMocNo());
        moc.setSubId(tPssrMoc.getSubId());
        List<TPssrMoc> tPssrMocs = tPssrMocService.selectTPssrMocList(moc);
        if (CollectionUtils.isNotEmpty(tPssrMocs)) {
            for (TPssrMoc pssrMoc : tPssrMocs) {
                tPssrMoc.setId(pssrMoc.getId());
                tPssrMocService.updateTPssrMoc(tPssrMoc);
            }
        } else {
            tPssrMocService.insertTPssrMoc(tPssrMoc);
        }
    }

    /**
     * 修改MOC完成确认清单
     */
    @PreAuthorize("@ss.hasPermi('pssr:moc:edit')")
    @Log(title = "MOC完成确认清单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TPssrMoc tPssrMoc) {
        TPssrMoc entity = tPssrMocService.selectTPssrMocById(tPssrMoc.getId());
        if (entity.getApproveStatus() != 1 && entity.getApproveStatus() != 0) {
            return  AjaxResult.error("当前状态不可修改！");
        }
        if (tPssrMoc.getConfirm1().equals(tPssrMoc.getConfirm2())){
            return AjaxResult.error("确认人不能为同一人，请重新选择！");
        }
        tPssrFileService.updateFileRelevance(tPssrMoc.getFileIds(), forShort, tPssrMoc.getId(), tPssrMoc.getSubId());
        return toAjax(tPssrMocService.updateTPssrMoc(tPssrMoc));
    }

    /**
     * 修改MOC完成确认清单
     */
    @PreAuthorize("@ss.hasPermi('pssr:moc:edit')")
    @Log(title = "MOC完成确认清单", businessType = BusinessType.UPDATE)
    @PutMapping("/editBatch")
    public AjaxResult editb(@RequestBody TPssrMoc tPssrMoc) {
        if (tPssrMoc.getConfirm1().equals(tPssrMoc.getConfirm2())){
            return AjaxResult.error("确认人不能为同一人，请重新选择！");
        }
        return toAjax(tPssrMocMapper.updateTPssrMocByIds(tPssrMoc));
    }

    /**
     * 删除MOC完成确认清单
     */
    @PreAuthorize("@ss.hasPermi('pssr:moc:remove')")
    @Log(title = "MOC完成确认清单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tPssrMocService.deleteTPssrMocByIds(ids));
    }


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

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

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

    }

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

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