package com.ruoyi.project.training.bccnew.controller;

import com.ruoyi.common.jpush.JiGuangPushService;
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.approve.damain.DevTask;
import com.ruoyi.project.plant.domain.TStaffmgr;
import com.ruoyi.project.plant.mapper.TStaffmgrMapper;
import com.ruoyi.project.shiftmgr.domain.TShiftRoster;
import com.ruoyi.project.shiftmgr.mapper.TShiftRosterMapper;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysUserService;
import com.ruoyi.project.system.service.impl.SysUserServiceImpl;
import com.ruoyi.project.training.bccnew.domain.*;
import com.ruoyi.project.training.bccnew.service.*;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.*;

/**
 * 导师带徒审批Controller
 *
 * @author ssy
 * @date 2024-06-25
 */
@RestController
@RequestMapping("/bccnew/approve")
public class TTsApproveController extends BaseController {
    @Autowired
    private ITTsApproveService tTsApproveService;
    @Autowired
    private ITTsNewService tTsNewService;

    @Autowired
    private ITTsLjplanService tTsLjplanService;

    @Autowired
    private ITTsYsplanService tTsYsplanService;

    @Autowired
    private ITTsFlplanService tTsFlplanService;

    @Autowired
    private ITTsFtplanService tTsFtplanService;


    @Autowired
    private ITTsLjplanContentService tTsLjplanContentService;

    @Autowired
    private ITTsYsplanContentService tTsYsplanContentService;

    @Autowired
    private ITTsFlplanContentService tTsFlplanContentService;

    @Autowired
    private ITTsFtplanContentService tTsFtplanContentService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private TShiftRosterMapper tShiftRosterMapper;

    @Autowired
    private TStaffmgrMapper tStaffmgrMapper;
    @Autowired
    private SysUserServiceImpl sysUserService;
    @Autowired
    private JiGuangPushService jiGuangPushService;


    /**
     * 查询导师带徒审批列表
     */
    @PreAuthorize("@ss.hasPermi('bccnew:approve:list')")
    @GetMapping("/list")
    public TableDataInfo list(TTsApprove tTsApprove) {
        startPage();
        List<TTsApprove> list = tTsApproveService.selectTTsApproveList(tTsApprove);
        return getDataTable(list);
    }

    /**
     * 导出导师带徒审批列表
     */
    @PreAuthorize("@ss.hasPermi('bccnew:approve:export')")
    @Log(title = "导师带徒审批", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TTsApprove tTsApprove) {
        List<TTsApprove> list = tTsApproveService.selectTTsApproveList(tTsApprove);
        ExcelUtil<TTsApprove> util = new ExcelUtil<TTsApprove>(TTsApprove.class);
        return util.exportExcel(list, "approve");
    }

    /**
     * 获取导师带徒审批详细信息
     */
//    @PreAuthorize("@ss.hasPermi('bccnew:approve:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        TTsApprove tTsApprove = tTsApproveService.selectTTsApproveById(id);
        if (tTsApprove.getTrainingId() != null)
            tTsApprove.settTsNew(tTsNewService.selectTTsNewById(tTsApprove.getTrainingId()));
        switch (tTsApprove.getPlanType()) {
            case "1":
                if (tTsApprove.getContentId() != null) {
                    tTsApprove.settTsLjplan(tTsLjplanService.selectTTsLjplanById(tTsApprove.getContentId()));
                    tTsApprove.settTsNew(tTsNewService.selectTTsNewById(tTsApprove.gettTsLjplan().getNewId()));
                }
                break;
            case "2":
                if (tTsApprove.getContentId() != null) {
                    tTsApprove.settTsYsplan(tTsYsplanService.selectTTsYsplanById(tTsApprove.getContentId()));
                    tTsApprove.settTsNew(tTsNewService.selectTTsNewById(tTsApprove.gettTsYsplan().getNewId()));
                }
                break;
            case "3":
                if (tTsApprove.getContentId() != null) {
                    tTsApprove.settTsFlplan(tTsFlplanService.selectTTsFlplanById(tTsApprove.getContentId()));
                    tTsApprove.settTsNew(tTsNewService.selectTTsNewById(tTsApprove.gettTsFlplan().getNewId()));
                }
                break;
            case "4":
                if (tTsApprove.getContentId() != null) {
                    tTsApprove.settTsFtplan(tTsFtplanService.selectTTsFtplanById(tTsApprove.getContentId()));
                    tTsApprove.settTsNew(tTsNewService.selectTTsNewById(tTsApprove.gettTsFtplan().getNewId()));
                }
                break;
        }
        return AjaxResult.success(tTsApprove);
    }

    /**
     * 新增导师带徒审批
     */
    @PreAuthorize("@ss.hasPermi('bccnew:approve:add')")
    @Log(title = "导师带徒审批", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TTsApprove tTsApprove) {
        return toAjax(tTsApproveService.insertTTsApprove(tTsApprove));
    }

    /**
     * 修改导师带徒审批
     */
    @PreAuthorize("@ss.hasPermi('bccnew:approve:edit')")
    @Log(title = "导师带徒审批", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TTsApprove tTsApprove) {
        return toAjax(tTsApproveService.updateTTsApprove(tTsApprove));
    }

    @Log(title = "导师带徒审批", businessType = BusinessType.UPDATE)
    @PutMapping("/handle")
    public AjaxResult handle(@RequestBody DevTask devTask) {
        return tTsApproveService.handle(devTask, getNickName(), getUserId().toString());
    }


    @Log(title = "导师带徒审批成绩", businessType = BusinessType.UPDATE)
    @PutMapping("/handleScore")
    public AjaxResult handleScore(@RequestBody DevTask devTask) {
        TTsApprove tTsApprove = devTask.gettTsApprove();
        //使用任务服务完成任务(提交任务)
        String taskId = devTask.getTaskId();
        // 使用任务id,获取任务对象，获取流程实例id
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        //利用任务对象，获取流程实例id
        String taskName = task.getName();//实例名
        String processInstancesId = task.getProcessInstanceId();
        String userId = getUserId().toString();
        // 判断流程
        Long newId = null;
        if ("1".equals(devTask.getCondition())) {
            devTask.setComment("补考");
                switch (tTsApprove.getPlanType()) {
                    case "1": {
                        TTsLjplan item = tTsLjplanService.selectTTsLjplanById(tTsApprove.getContentId());
                        newId= item.getNewId();
                        item.setScorePass(1);
                        tTsLjplanService.updateTTsLjplan(item);
                        break;
                    }
                    case "2": {
                        TTsYsplan item = tTsYsplanService.selectTTsYsplanById(tTsApprove.getContentId());
                        newId= item.getNewId();
                        item.setScorePass(1);
                        tTsYsplanService.updateTTsYsplan(item);
                        break;
                    }
                    case "3": {
                        TTsFlplan item = tTsFlplanService.selectTTsFlplanById(tTsApprove.getContentId());
                        newId= item.getNewId();
                        item.setScorePass(1);
                        tTsFlplanService.updateTTsFlplan(item);
                        break;
                    }
                    case "4": {
                        TTsFtplan item = tTsFtplanService.selectTTsFtplanById(tTsApprove.getContentId());
                        newId= item.getNewId();
                        item.setScorePass(1);
                        tTsFtplanService.updateTTsFtplan(item);
                        break;
                    }
                }
            SysUser staff = sysUserService.selectUserByStaffId(tTsNewService.selectTTsNewById(newId).getStaffId());
            jiGuangPushService.send("导师带徒-导师带徒级培训", "您有待补考的培训课程", staff.getUserId().toString());

        } else if ("0".equals(devTask.getCondition())) {
            devTask.setComment("重新学习");
                switch (tTsApprove.getPlanType()) {
                    case "1": {
                        //查询旧数据
                        TTsLjplan item = tTsLjplanService.selectTTsLjplanById(tTsApprove.getContentId());
                        newId= item.getNewId();
                        item.setPlanStatus(1L);
                        tTsLjplanService.updateTTsLjplan(item);
                        TTsLjplanContent contentItem = new TTsLjplanContent();
                        contentItem.setPid(item.getId());
                        //                新增需要重新学习的数据
                        item.setId(null);
                        item.setCreatedate(new Date());
                        item.setCreaterCode(userId);
                        item.setUpdatedate(null);
                        item.setUpdaterCode(null);
                        item.setPlanStatus(0L);
                        item.setScorePass(null);
                        item.setTimer(0L);
                        item.setSortTmpl(item.getSortTmpl() + 1);//排序往后顺延1

                        tTsLjplanService.insertTTsLjplan(item);
                        //新增内容
                        List<TTsLjplanContent> contents = tTsLjplanContentService.selectTTsLjplanContentList(contentItem);
                        List<TShiftRoster> rosters = new ArrayList<>();
                        int i = 0;
                        if (contents.get(contents.size() - 1).getPlanDate() != null) {
                            TTsNew tTsNew = tTsNewService.selectTTsNewById(item.getNewId());
                            TStaffmgr tStaffmgr = tStaffmgrMapper.selectTStaffmgrByStaffId(tTsNew.getStaffId());
                            TShiftRoster tShiftRoster = new TShiftRoster();
                            tShiftRoster.setShiftDate(contents.get(contents.size() - 1).getPlanDate());
                            tShiftRoster.setDclass(tStaffmgr.getTeam());
                            tShiftRoster.setNclass(tStaffmgr.getTeam());
                            tShiftRoster.setVacation(null);
                            rosters = tShiftRosterMapper.selectTShiftRosterListByTrain(tShiftRoster);
                        }
                        for (TTsLjplanContent content : contents) {
                            content.setId(null);
                            content.setPid(item.getId());
                            if (rosters.size() > i) {
                                //                        修改计划培训日期
                                i++;
                                content.setPlanDate(rosters.get(i).getShiftDate());
                            }
                            tTsLjplanContentService.insertTTsLjplanContent(content);
                        }
                        //                查询剩余未完成的训培内容
                        TTsLjplan query = new TTsLjplan();
                        query.setNewId(item.getNewId());
                        query.setPlanStatus(0L);
                        for (TTsLjplan entity : tTsLjplanService.selectTTsLjplanListByNewId(query)) {
                            if (Objects.equals(entity.getId(), item.getId()))
                                continue;
                            contentItem.setPid(entity.getId());
                            contents = tTsLjplanContentService.selectTTsLjplanContentList(contentItem);
                            for (TTsLjplanContent content : contents) {
                                if (rosters.size() > i) {
                                    //                            修改计划培训日期
                                    i++;
                                    content.setPlanDate(rosters.get(i).getShiftDate());
                                }
                                tTsLjplanContentService.updateTTsLjplanContent(content);
                            }
                        }
                        break;
                    }
                    case "2": {
                        //查询旧数据
                        TTsYsplan item = tTsYsplanService.selectTTsYsplanById(tTsApprove.getContentId());
                        newId= item.getNewId();
                        item.setPlanStatus(1L);
                        tTsYsplanService.updateTTsYsplan(item);
                        TTsYsplanContent contentItem = new TTsYsplanContent();
                        contentItem.setPid(item.getId());
                        //                新增需要重新学习的数据
                        item.setId(null);
                        item.setCreatedate(new Date());
                        item.setCreaterCode(userId);
                        item.setUpdatedate(null);
                        item.setUpdaterCode(null);
                        item.setPlanStatus(0L);
                        item.setScorePass(null);
                        item.setTimer(0L);
                        item.setSortTmpl(item.getSortTmpl() + 1);//排序往后顺延1

                        tTsYsplanService.insertTTsYsplan(item);
                        //新增内容
                        List<TTsYsplanContent> contents = tTsYsplanContentService.selectTTsYsplanContentList(contentItem);
                        List<TShiftRoster> rosters = new ArrayList<>();
                        int i = 0;
                        if (contents.get(contents.size() - 1).getPlanDate() != null) {
                            TTsNew tTsNew = tTsNewService.selectTTsNewById(item.getNewId());
                            TStaffmgr tStaffmgr = tStaffmgrMapper.selectTStaffmgrByStaffId(tTsNew.getStaffId());
                            TShiftRoster tShiftRoster = new TShiftRoster();
                            tShiftRoster.setShiftDate(contents.get(contents.size() - 1).getPlanDate());
                            tShiftRoster.setDclass(tStaffmgr.getTeam());
                            tShiftRoster.setNclass(tStaffmgr.getTeam());
                            tShiftRoster.setVacation(null);
                            rosters = tShiftRosterMapper.selectTShiftRosterListByTrain(tShiftRoster);
                        }
                        for (TTsYsplanContent content : contents) {
                            content.setId(null);
                            content.setPid(item.getId());
                            if (rosters.size() > i) {
                                //                        修改计划培训日期
                                i++;
                                content.setPlanDate(rosters.get(i).getShiftDate());
                            }
                            tTsYsplanContentService.insertTTsYsplanContent(content);
                        }
                        //                查询剩余未完成的训培内容
                        TTsYsplan query = new TTsYsplan();
                        query.setNewId(item.getNewId());
                        query.setPlanStatus(0L);
                        for (TTsYsplan entity : tTsYsplanService.selectTTsYsplanListByNewId(query)) {
                            if (Objects.equals(entity.getId(), item.getId()))
                                continue;
                            contentItem.setPid(entity.getId());
                            contents = tTsYsplanContentService.selectTTsYsplanContentList(contentItem);
                            for (TTsYsplanContent content : contents) {
                                if (rosters.size() > i) {
                                    //                        修改计划培训日期
                                    i++;
                                    content.setPlanDate(rosters.get(i).getShiftDate());
                                }
                                tTsYsplanContentService.updateTTsYsplanContent(content);
                            }
                        }
                        break;
                    }
                    case "3": {
                        //查询旧数据
                        TTsFlplan item = tTsFlplanService.selectTTsFlplanById(tTsApprove.getContentId());
                        newId= item.getNewId();
                        item.setPlanStatus(1L);
                        tTsFlplanService.updateTTsFlplan(item);
                        TTsFlplanContent contentItem = new TTsFlplanContent();
                        contentItem.setPid(item.getId());
                        //                新增需要重新学习的数据
                        item.setId(null);
                        item.setCreatedate(new Date());
                        item.setCreaterCode(userId);
                        item.setUpdatedate(null);
                        item.setUpdaterCode(null);
                        item.setPlanStatus(0L);
                        item.setScorePass(null);
                        item.setTimer(0L);
                        item.setSortTmpl(item.getSortTmpl() + 1);//排序往后顺延1

                        tTsFlplanService.insertTTsFlplan(item);
                        //新增内容
                        List<TTsFlplanContent> contents = tTsFlplanContentService.selectTTsFlplanContentList(contentItem);
                        List<TShiftRoster> rosters = new ArrayList<>();
                        int i = 0;
                        if (contents.get(contents.size() - 1).getPlanDate() != null) {
                            TTsNew tTsNew = tTsNewService.selectTTsNewById(item.getNewId());
                            TStaffmgr tStaffmgr = tStaffmgrMapper.selectTStaffmgrByStaffId(tTsNew.getStaffId());
                            TShiftRoster tShiftRoster = new TShiftRoster();
                            tShiftRoster.setShiftDate(contents.get(contents.size() - 1).getPlanDate());
                            tShiftRoster.setDclass(tStaffmgr.getTeam());
                            tShiftRoster.setNclass(tStaffmgr.getTeam());
                            tShiftRoster.setVacation(null);
                            rosters = tShiftRosterMapper.selectTShiftRosterListByTrain(tShiftRoster);
                        }
                        for (TTsFlplanContent content : contents) {
                            content.setId(null);
                            content.setPid(item.getId());
                            if (rosters.size() > i) {
                                //                        修改计划培训日期
                                i++;
                                content.setPlanDate(rosters.get(i).getShiftDate());
                            }
                            tTsFlplanContentService.insertTTsFlplanContent(content);
                        }
                        //                查询剩余未完成的训培内容
                        TTsFlplan query = new TTsFlplan();
                        query.setNewId(item.getNewId());
                        query.setPlanStatus(0L);
                        for (TTsFlplan entity : tTsFlplanService.selectTTsFlplanListByNewId(query)) {
                            if (Objects.equals(entity.getId(), item.getId()))
                                continue;
                            contentItem.setPid(entity.getId());
                            contents = tTsFlplanContentService.selectTTsFlplanContentList(contentItem);
                            for (TTsFlplanContent content : contents) {
                                if (rosters.size() > i) {
                                    //                        修改计划培训日期
                                    i++;
                                    content.setPlanDate(rosters.get(i).getShiftDate());
                                }
                                tTsFlplanContentService.updateTTsFlplanContent(content);
                            }
                        }
                        break;
                    }
                    case "4": {
                        //查询旧数据
                        TTsFtplan item = tTsFtplanService.selectTTsFtplanById(tTsApprove.getContentId());
                        newId= item.getNewId();
                        item.setPlanStatus(1L);
                        tTsFtplanService.updateTTsFtplan(item);
                        TTsFtplanContent contentItem = new TTsFtplanContent();
                        contentItem.setPid(item.getId());
                        //                新增需要重新学习的数据
                        item.setId(null);
                        item.setCreatedate(new Date());
                        item.setCreaterCode(userId);
                        item.setUpdatedate(null);
                        item.setUpdaterCode(null);
                        item.setPlanStatus(0L);
                        item.setScorePass(null);
                        item.setTimer(0L);
                        item.setSortTmpl(item.getSortTmpl() + 1);//排序往后顺延1

                        tTsFtplanService.insertTTsFtplan(item);
                        //新增内容
                        List<TTsFtplanContent> contents = tTsFtplanContentService.selectTTsFtplanContentList(contentItem);
                        List<TShiftRoster> rosters = new ArrayList<>();
                        int i = 0;
                        if (contents.get(contents.size() - 1).getPlanDate() != null) {
                            TTsNew tTsNew = tTsNewService.selectTTsNewById(item.getNewId());
                            TStaffmgr tStaffmgr = tStaffmgrMapper.selectTStaffmgrByStaffId(tTsNew.getStaffId());
                            TShiftRoster tShiftRoster = new TShiftRoster();
                            tShiftRoster.setShiftDate(contents.get(contents.size() - 1).getPlanDate());
                            tShiftRoster.setDclass(tStaffmgr.getTeam());
                            tShiftRoster.setNclass(tStaffmgr.getTeam());
                            tShiftRoster.setVacation(null);
                            rosters = tShiftRosterMapper.selectTShiftRosterListByTrain(tShiftRoster);
                        }
                        for (TTsFtplanContent content : contents) {
                            content.setId(null);
                            content.setPid(item.getId());
                            if (rosters.size() > i) {
                                //                        修改计划培训日期
                                i++;
                                content.setPlanDate(rosters.get(i).getShiftDate());
                            }
                            tTsFtplanContentService.insertTTsFtplanContent(content);
                        }
                        //                查询剩余未完成的训培内容
                        TTsFtplan query = new TTsFtplan();
                        query.setNewId(item.getNewId());
                        query.setPlanStatus(0L);
                        for (TTsFtplan entity : tTsFtplanService.selectTTsFtplanListByNewId(query)) {
                            if (Objects.equals(entity.getId(), item.getId()))
                                continue;
                            contentItem.setPid(entity.getId());
                            contents = tTsFtplanContentService.selectTTsFtplanContentList(contentItem);
                            for (TTsFtplanContent content : contents) {
                                if (rosters.size() > i) {
                                    //                        修改计划培训日期
                                    i++;
                                    content.setPlanDate(rosters.get(i).getShiftDate());
                                }
                                tTsFtplanContentService.updateTTsFtplanContent(content);
                            }
                        }
                        break;
                    }
                }
            SysUser staff = sysUserService.selectUserByStaffId(tTsNewService.selectTTsNewById(newId).getStaffId());
            jiGuangPushService.send("导师带徒-导师带徒级培训", "您有待重新学习的培训课程", staff.getUserId().toString());
        }
        // 处理流程节点
        Map<String, Object> param = new HashMap<>();
        if (taskName.equals("装置经理")) {
            tTsApprove.setApproverName(getNickName());
            tTsApprove.setApprover(userId);
            tTsApprove.setApproveTime(new Date());
            param.put("condition", devTask.getCondition());
        }
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = processEngine.getTaskService();
        //认领任务
        processEngine.getTaskService()
                .claim(taskId, userId);
        taskService.addComment(taskId, processInstancesId, devTask.getComment());
        taskService.complete(taskId, param);
        tTsApproveService.updateTTsApprove(tTsApprove);
        return AjaxResult.success();
    }

    /**
     * 删除导师带徒审批
     */
    @PreAuthorize("@ss.hasPermi('bccnew:approve:remove')")
    @Log(title = "导师带徒审批", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tTsApproveService.deleteTTsApproveByIds(ids));
    }
}
