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

import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.github.stuxuhai.jpinyin.PinyinFormat;
import com.github.stuxuhai.jpinyin.PinyinHelper;
import com.ruoyi.common.sendEmail.IMailService;
import com.ruoyi.common.thread.Trainning.PlanApproveMailThread;
import com.ruoyi.project.approve.damain.DevTask;
import com.ruoyi.project.system.domain.SysMessage;
import com.ruoyi.project.system.mapper.SysUserMapper;
import com.ruoyi.project.system.service.ISysMessageService;
import com.ruoyi.project.training.spec.domain.TStPlan;
import com.ruoyi.project.training.spec.domain.TStYearplan;
import com.ruoyi.project.training.spec.service.ITStPlanService;
import com.ruoyi.project.training.spec.service.ITStYearplanService;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.training.spec.domain.TStApprove;
import com.ruoyi.project.training.spec.service.ITStApproveService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;

import javax.annotation.Resource;

/**
 * 专项培训计划申请Controller
 *
 * @author ly
 * @date 2022-04-18
 */
@RestController
@RequestMapping("/spec/stapprove")
public class TStApproveController extends BaseController
{
    @Autowired
    private ITStApproveService tStApproveService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private ITStPlanService tStPlanService;
    @Autowired
    private ITStYearplanService tStYearplanService;
    @Resource
    private SysUserMapper sysUserMapper;
    @Autowired
    private IMailService mailService;
    @Autowired
    private ISysMessageService sysMessageService;

    /**
     * 查询专项培训计划申请列表
     */
    @GetMapping("/list")
    public TableDataInfo list(TStApprove tStApprove)
    {
        startPage();
        List<TStApprove> list = tStApproveService.selectTStApproveList(tStApprove);
        return getDataTable(list);
    }

    @GetMapping(value = "info/{id}")
    public AjaxResult info(@PathVariable("id") Long id)
    {
        TStApprove tStApprove = tStApproveService.selectTStApproveById(id);
        String ids = tStApprove.getPlanId();
        TStYearplan tStYearplan = tStYearplanService.selectTStYearplanById(Long.parseLong(ids));
        // 培训明细
        TStPlan tStPlan = new TStPlan();
        tStPlan.setYearPlanId(tStYearplan.getId());
        List<TStPlan> planList = tStPlanService.selectTStPlanList(tStPlan);
        //判断是否可以修改
        for (TStPlan t: planList
        ) {
            try {
                if (new Date().before(t.getStartDate())){
                    t.setEditFlag(1);
                }else {
                    t.setEditFlag(0);
                }
            }catch (Exception e){
                t.setEditFlag(1);
            }
        }
        tStApprove.setPlanList(planList);
        tStApprove.setYearplan(tStYearplan);
        return AjaxResult.success(tStApprove);
    }

    /**
     * 新增专项培训计划申请
     */
    @Log(title = "专项培训计划申请", businessType = BusinessType.INSERT)
    @RequestMapping("/addStPlanApprove")
    public AjaxResult add(@RequestBody TStApprove tStApprove)
    {
        //任务开始时间
        long startTime = System.currentTimeMillis();
        logger.info("任务申请" + JSON.toJSONString(tStApprove));
        Long userid = getUserId();
        //审批编号
        Date dt = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
        String data = sdf.format(dt) + userid;
        tStApprove.setApNo(data);
        tStApprove.setUserId(userid);
        tStApproveService.insertTStApprove(tStApprove);
        TStYearplan tStYearplan = tStYearplanService.selectTStYearplanById(Long.parseLong(tStApprove.getPlanId()));
        tStYearplan.setApproveStatus(3l);
        tStYearplanService.updateTStYearplan(tStYearplan);
        Map<String, Object> variables = new HashMap<>();
        //开始工作流、监听
//        variables.put("endSucessListener", new MonthEndSucessListener());
//        variables.put("endFaileListener", new MonthEndFaileListener());
        //审批人员设置
        variables.put("zzjlusers", tStApprove.getZzjl());

        long bussniseeKey = tStApprove.getId();
        logger.info("bussniseeKey:" + bussniseeKey);
        Authentication.setAuthenticatedUserId(userid.toString());

        //采用key来启动流程定义并设置流程变量，返回流程实例
        ProcessInstance pi = runtimeService.startProcessInstanceByKey("specTrainingPlanProcess", String.valueOf(bussniseeKey), variables);
        logger.info("流程部署id：" + pi.getDeploymentId());
        logger.info("流程定义id：" + pi.getProcessDefinitionId());
        logger.info("流程实例id：" + pi.getProcessInstanceId());
        logger.info("流程定义对象：" + pi.getProcessVariables());
        tStApprove.setProcessId(pi.getProcessInstanceId());
        tStApproveService.updateTStApprove(tStApprove);
        //发送邮件
        try {
            SysMessage message = new SysMessage();
            String email = sysUserMapper.selectUserById(tStApprove.getZzjl()).getEmail();
            String apNo = tStApprove.getApNo();
            String username = sysUserMapper.selectUserById(tStApprove.getZzjl()).getNickName();
            String usernameEN = PinyinHelper.convertToPinyinString(username, " ", PinyinFormat.WITHOUT_TONE);
            logger.info("email:" + email);
            logger.info("username:" + username);
            message.setUserId(tStApprove.getZzjl());
            message.setMsgTitle("您有一条系统消息");
            message.setMsgContent("您有一条培训待审核");
            PlanApproveMailThread sendEmailThead = new PlanApproveMailThread(email,apNo, username,usernameEN, mailService, tStApprove,sysMessageService,message,"0");
            Thread t = new Thread(sendEmailThead);
            t.start();
        }catch (Exception e) {
            logger.error("邮件发送失败" + JSON.toJSONString(e));
        }
        return AjaxResult.success();
    }

    /**
     * 审核处理
     */
    @Log(title = "专项培训计划申请审核处理", businessType = BusinessType.UPDATE)
    @PutMapping("/handle")
    public AjaxResult handle(@RequestBody DevTask devTask) {
        //流程审批意见
        String symbol= "";
        if (devTask.getComment() != "") {
            symbol = "，";
        }
        //使用任务服务完成任务(提交任务)
        String taskId = devTask.getTaskId();
        // 使用任务id,获取任务对象，获取流程实例id
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        //利用任务对象，获取流程实例id
        String processInstancesId = task.getProcessInstanceId();
        TStApprove tStApprove = tStApproveService.selectTStApproveById(Long.parseLong(devTask.getBusinessKey()));
        tStApprove.setContent(devTask.getComment());
        if (devTask.getCondition().equals("1")) {
            devTask.setComment("通过");
            TStYearplan tStYearplan = tStYearplanService.selectTStYearplanById(Long.parseLong(tStApprove.getPlanId()));
            tStYearplan.setApproveStatus(1l);
            tStYearplanService.updateTStYearplan(tStYearplan);
            // 培训明细
            TStPlan tStPlan = new TStPlan();
            tStPlan.setYearPlanId(tStYearplan.getId());
            List<TStPlan> planList = tStPlanService.selectTStPlanList(tStPlan);
            for (TStPlan t: planList
                 ) {
                t.setApproveStatus(1l);
                tStPlanService.updateTStPlan(t);
            }
            //发送邮件
            try {
                SysMessage message = new SysMessage();
                String email = sysUserMapper.selectUserById(tStApprove.getUserId()).getEmail();
                String apNo = tStApprove.getApNo();
                String username = sysUserMapper.selectUserById(tStApprove.getUserId()).getNickName();
                String usernameEN = PinyinHelper.convertToPinyinString(username, " ", PinyinFormat.WITHOUT_TONE);
                logger.info("email:" + email);
                logger.info("username:" + username);
                message.setUserId(tStApprove.getUserId());
                message.setMsgTitle("您有一条系统消息");
                message.setMsgContent("您有一条培训申请已通过");
                PlanApproveMailThread sendEmailThead = new PlanApproveMailThread(email,apNo, username,usernameEN, mailService, tStApprove,sysMessageService,message,"1");
                Thread t = new Thread(sendEmailThead);
                t.start();
            }catch (Exception e) {
                logger.error("邮件发送失败" + JSON.toJSONString(e));
            }
         }
        else if (devTask.getCondition().equals("0")) {
            devTask.setComment("未通过");
            TStYearplan tStYearplan = tStYearplanService.selectTStYearplanById(Long.parseLong(tStApprove.getPlanId()));
            tStYearplan.setApproveStatus(2l);
            tStYearplanService.updateTStYearplan(tStYearplan);
            // 培训明细
            TStPlan tStPlan = new TStPlan();
            tStPlan.setYearPlanId(tStYearplan.getId());
            List<TStPlan> planList = tStPlanService.selectTStPlanList(tStPlan);
            for (TStPlan t: planList
            ) {
                t.setApproveStatus(2l);
                tStPlanService.updateTStPlan(t);
            }
            //发送邮件
            try {
                SysMessage message = new SysMessage();
                String email = sysUserMapper.selectUserById(tStApprove.getUserId()).getEmail();
                String apNo = tStApprove.getApNo();
                String username = sysUserMapper.selectUserById(tStApprove.getUserId()).getNickName();
                String usernameEN = PinyinHelper.convertToPinyinString(username, " ", PinyinFormat.WITHOUT_TONE);
                logger.info("email:" + email);
                logger.info("username:" + username);
                message.setUserId(tStApprove.getUserId());
                message.setMsgTitle("您有一条系统消息");
                message.setMsgContent("您有一条培训申请未通过");
                PlanApproveMailThread sendEmailThead = new PlanApproveMailThread(email,apNo, username,usernameEN, mailService, tStApprove,sysMessageService,message,"2");
                Thread t = new Thread(sendEmailThead);
                t.start();
            }catch (Exception e) {
                logger.error("邮件发送失败" + JSON.toJSONString(e));
            }
        }
        tStApproveService.updateTStApprove(tStApprove);
        System.out.println(processInstancesId);
        Map<String, Object> param = new HashMap<>();
        param.put("condition", devTask.getCondition());
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = processEngine.getTaskService();
        //认领任务
        processEngine.getTaskService()//
                .claim(taskId, getUserId().toString());
//        Authentication.setAuthenticatedUserId("cmc"); // 添加批注时候的审核人
        taskService.addComment(taskId, processInstancesId, devTask.getComment());
        //业务监听处理
//        tApproveService.handleApprove(task ,devTask);
        taskService.complete(taskId, param);
        return AjaxResult.success();
    }

    /**
     * 修改专项培训计划申请
     */
    @Log(title = "专项培训计划申请", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TStApprove tStApprove)
    {
        return toAjax(tStApproveService.updateTStApprove(tStApprove));
    }

    /**
     * 删除专项培训计划申请
     */
    @Log(title = "专项培训计划申请", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tStApproveService.deleteTStApproveByIds(ids));
    }
}
