package com.ruoyi.project.pssr.controller;

import com.ruoyi.common.utils.StringUtils;
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.listener.pssr.ConfirmTaskCreateListener;
import com.ruoyi.project.pssr.domain.*;
import com.ruoyi.project.pssr.mapper.TPssrMaterialRawMapper;
import com.ruoyi.project.pssr.service.*;
import org.activiti.engine.*;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.collections4.CollectionUtils;
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.util.*;

/**
 * 原料Controller
 *
 * @author ssy
 * @date 2024-09-18
 */
@RestController
@RequestMapping("/pssr/materialRaw")
public class TPssrMaterialRawController extends BaseController {
    @Autowired
    private ITPssrFileService tPssrFileService;

    @Autowired
    private ITPssrTurndownService tPssrTurndownService;
    @Autowired
    private ITPssrMaterialRawService tPssrMaterialRawService;

    @Autowired
    private ITPssrApproveService tPssrApproveService;

    @Autowired
    private ITPssrSubcontentService tPssrSubcontentService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private HistoryService historyService;
    @Resource
    private TPssrMaterialRawMapper tPssrMaterialRawMapper;
    private String forShort = "yfl-raw";

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

    /**
     * 导出原料列表
     */
    @PreAuthorize("@ss.hasPermi('pssr:materialRaw:export')")
    @Log(title = "原料", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TPssrMaterialRaw tPssrMaterialRaw) {
        List<TPssrMaterialRaw> list = tPssrMaterialRawService.selectTPssrMaterialRawList(tPssrMaterialRaw);
        ExcelUtil<TPssrMaterialRaw> util = new ExcelUtil<TPssrMaterialRaw>(TPssrMaterialRaw.class);
        return util.exportExcel(list, "materialRaw");
    }

    /**
     * 获取原料详细信息
     */
    @PreAuthorize("@ss.hasPermi('pssr:materialRaw:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        TPssrMaterialRaw item = tPssrMaterialRawService.selectTPssrMaterialRawById(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(), "yfl-raw"));
        return AjaxResult.success(item);
    }

    /**
     * 新增原料
     */
    @PreAuthorize("@ss.hasPermi('pssr:materialRaw:add')")
    @Log(title = "原料", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TPssrMaterialRaw tPssrMaterialRaw) {
        if (StringUtils.isNotEmpty(tPssrMaterialRaw.getConfirm1())&&tPssrMaterialRaw.getConfirm1().equals(tPssrMaterialRaw.getConfirm2())) {
            return AjaxResult.error("确认人不能为同一人，请重新选择！");
        }
        return toAjax(tPssrMaterialRawService.insertTPssrMaterialRaw(tPssrMaterialRaw));
    }

    /**
     * 修改原料
     */
    @PreAuthorize("@ss.hasPermi('pssr:materialRaw:edit')")
    @Log(title = "原料", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TPssrMaterialRaw tPssrMaterialRaw) {
        TPssrMaterialRaw entity = tPssrMaterialRawService.selectTPssrMaterialRawById(tPssrMaterialRaw.getId());
        if (entity.getApproveStatus() != 1 && entity.getApproveStatus() != 0) {
            return  AjaxResult.error("当前状态不可修改！");
        }
        if (tPssrMaterialRaw.getConfirm1().equals(tPssrMaterialRaw.getConfirm2())){
            return AjaxResult.error("确认人不能为同一人，请重新选择！");
        }
        tPssrFileService.updateFileRelevance(tPssrMaterialRaw.getFileIds(), "yfl-raw", tPssrMaterialRaw.getId(), tPssrMaterialRaw.getSubId());
        return toAjax(tPssrMaterialRawService.updateTPssrMaterialRaw(tPssrMaterialRaw));
    }

    /**
     * 修改原料
     */
    @PreAuthorize("@ss.hasPermi('pssr:materialRaw:edit')")
    @Log(title = "原料", businessType = BusinessType.UPDATE)
    @PutMapping("editBatch")
    public AjaxResult editBatch(@RequestBody TPssrMaterialRaw tPssrMaterialRaw) {
        if (tPssrMaterialRaw.getConfirm1().equals(tPssrMaterialRaw.getConfirm2())){
            return AjaxResult.error("确认人不能为同一人，请重新选择！");
        }
        return toAjax(tPssrMaterialRawMapper.updateTPssrMaterialRawByIds(tPssrMaterialRaw));
    }

    /**
     * 删除原料
     */
    @PreAuthorize("@ss.hasPermi('pssr:materialRaw:remove')")
    @Log(title = "原料", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tPssrMaterialRawService.deleteTPssrMaterialRawByIds(ids));
    }


    /**
     * 确认人身防护
     */
    @PreAuthorize("@ss.hasPermi('pssr:materialRaw:edit')")
    @Log(title = "人身防护", businessType = BusinessType.UPDATE)
    @PutMapping("/confirmMaterialRaw")
    public AjaxResult confirmMaterialRaw(@RequestBody TPssrMaterialRaw tPssrMaterialRaw) {
        TPssrMaterialRaw materialRaw = new TPssrMaterialRaw();
        if (tPssrMaterialRaw.getIds() != null && tPssrMaterialRaw.getIds().length > 0) {
            for (Long id : tPssrMaterialRaw.getIds()) {
                materialRaw = tPssrMaterialRawService.selectTPssrMaterialRawById(id);
                materialRaw.setConfirmationDate(new Date());
                materialRaw.setApproveStatus(2L);
                materialRaw.setUpdatedate(new Date());
                materialRaw.setUpdaterCode(String.valueOf(getUserId()));
                tPssrMaterialRawService.updateTPssrMaterialRaw(materialRaw);
            }
        } else {
            materialRaw.setSubId(tPssrMaterialRaw.getSubId());
            materialRaw.setApproveStatus(1L);
            materialRaw.setConfirm1(getUserId().toString());
            for (TPssrMaterialRaw item : tPssrMaterialRawService.selectTPssrMaterialRawList(materialRaw)) {
                item.setConfirmationDate(new Date());
                item.setApproveStatus(2L);
                item.setUpdatedate(new Date());
                item.setUpdaterCode(String.valueOf(getUserId()));
                tPssrMaterialRawService.updateTPssrMaterialRaw(item);
            }
        }
        //查询当前待审批的确认人
        TPssrMaterialRaw entity = new TPssrMaterialRaw();
        entity.setSubId(tPssrMaterialRaw.getSubId());
        entity.setApproveStatus(1L);
        TPssrMaterialRaw MaterialRaw = tPssrMaterialRawService.selectAllConfirmedPersonBySubId(entity);
        if (MaterialRaw != null) {
            //如果当前用户还有待审批任务
            if (tPssrMaterialRaw.getTaskType() == 4 && StringUtils.isNotEmpty(MaterialRaw.getConfirm1())) {
                if (MaterialRaw.getConfirm1().contains(getUserId().toString())) {
                    return AjaxResult.success();
                }
            }

            if (tPssrMaterialRaw.getTaskType() == 5 && StringUtils.isNotEmpty(MaterialRaw.getConfirm2())) {
                if (MaterialRaw.getConfirm2().contains(getUserId().toString())) {
                    return AjaxResult.success();
                }
            }
        }
        //无待审批任务结束当前用户流程

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


    /**
     * 驳回人身防护
     */
    @PutMapping("/turnDownMaterialRaw")
    public AjaxResult turnDownMaterialRaw(@RequestBody List<TPssrMaterialRaw> tPssrMaterialRaw) {
        if (CollectionUtils.isNotEmpty(tPssrMaterialRaw)) {
            String userId = getUserId().toString();
            Long subId = tPssrMaterialRaw.get(0).getSubId();
            // 修改已选择数据的状态
            for (TPssrMaterialRaw item : tPssrMaterialRaw) {
                TPssrMaterialRaw blind = new TPssrMaterialRaw();
                blind.setId(item.getId());
                blind.setApproveStatus(1L);
                blind.setUpdatedate(new Date());
                blind.setUpdaterCode(getUserId().toString());
                tPssrMaterialRawService.updateTPssrMaterialRaw(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);

            try {
                runtimeService.deleteProcessInstance(approve.getProcessId(), "pssr1confirm");
                historyService.deleteHistoricProcessInstance(approve.getProcessId());
            } catch (Exception e) {
                logger.info("无运行时流程");
            }

            // 驳回 查询所有待审批的人员
            // 查询确认人
            TPssrMaterialRaw entity = new TPssrMaterialRaw();
            entity.setSubId(subId);
            entity.setApproveStatus(1L);
            TPssrMaterialRaw PssrMaterialRaw = tPssrMaterialRawService.selectAllConfirmedPersonBySubId(entity);
            String confirmer1s = null;
            if (PssrMaterialRaw != null) {
                confirmer1s = PssrMaterialRaw.getConfirm1();
            }
            logger.info("=======================confirmer1s:{}", confirmer1s);

            Set<String> confirmerUsers1 = new HashSet<>();
            if (StringUtils.isNotEmpty(confirmer1s)) {
                confirmerUsers1.addAll(Arrays.asList(confirmer1s.split(",")));
            }

            // 开始申请流程
            long businessKey = approve.getApproveId();
            //开始工作流、监听
            Authentication.setAuthenticatedUserId(userId);//设置当前申请人
            Map<String, Object> variables = new HashMap<>();
            variables.put("applyUser", userId);
            variables.put("confirmUsers", new ArrayList<>(confirmerUsers1));
            variables.put("confirmTaskCreateListener", new ConfirmTaskCreateListener());//发送邮件
            variables.put("chargePerson", approve.getSubCharge());
            //采用key来启动流程定义并设置流程变量，返回流程实例
            ProcessInstance pi = runtimeService.startProcessInstanceByKey("pssr1confirm", String.valueOf(businessKey), variables);

            // 修改审批表和sub表
            approve.setProcessId(pi.getProcessInstanceId());
            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();
    }
}
