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

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

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.PlanStudyMailThread;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.security.service.TokenService;
import com.ruoyi.project.system.domain.SysMessage;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysMessageService;
import com.ruoyi.project.system.service.ISysUserService;
import com.ruoyi.project.training.spec.domain.TStFeedback;
import com.ruoyi.project.training.spec.domain.TStSuccessor;
import com.ruoyi.project.training.spec.domain.TStYearplan;
import com.ruoyi.project.training.spec.domain.vo.TStPlanExportVO;
import com.ruoyi.project.training.spec.domain.vo.TStPlanImportVO;
import com.ruoyi.project.training.spec.mapper.TStSuccessorMapper;
import com.ruoyi.project.training.spec.service.ITStSuccessorService;
import com.ruoyi.project.training.spec.service.ITStYearplanService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
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.TStPlan;
import com.ruoyi.project.training.spec.service.ITStPlanService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 培训计划Controller
 *
 * @author ruoyi
 * @date 2022-04-13
 */
@RestController
@RequestMapping("/spec/plan")
public class TStPlanController extends BaseController
{
    @Autowired
    private ITStPlanService tStPlanService;

    @Autowired
    private ITStSuccessorService tStSuccessorService;

    @Resource
    private TStSuccessorMapper stSuccessorMapper;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ITStYearplanService tStYearplanService;

    @Autowired
    private IMailService mailService;

    @Autowired
    private ISysMessageService sysMessageService;

    @Autowired
    private TokenService tokenService;

    /**
     * 导入培养计划数据
     *
     * @param file 用户上传的文件
     * @param updateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param yearPlanId 年度计划id
     * @return
     * @throws Exception
     */
    @Log(title = "培训计划", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('spec:plan:add')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport, Long yearPlanId) throws Exception
    {
        ExcelUtil<TStPlanImportVO> util = new ExcelUtil<TStPlanImportVO>(TStPlanImportVO.class);
        List<TStPlanImportVO> planList = util.importExcelFromIndex0(file.getInputStream());
        Long userId = getUserId();
        SysUser loginUser = sysUserService.selectUserById(userId);
        String message = tStPlanService.importData(planList, updateSupport, loginUser, yearPlanId);
        return AjaxResult.success(message);
    }

    /**
     * 下载培养计划导入模板
     *
     * @return
     */
    @GetMapping("/importTemplate")
    public AjaxResult importTemplate()
    {
        ExcelUtil<TStPlanImportVO> util = new ExcelUtil<TStPlanImportVO>(TStPlanImportVO.class);
        return util.importTemplateExcel("培养计划数据");
    }

    /**
     * 查询月度反馈培养计划列表
     */
    @PreAuthorize("@ss.hasPermi('spec:plan:list')")
    @GetMapping("/listMonthly")
    public TableDataInfo listMonthly(TStFeedback feedback)
    {
        startPage();
        List<TStPlan> list = tStPlanService.selectMonthlyTStPlanList(feedback);
        return getDataTable(list);
    }

    /**
     * 查询季度汇报培养计划列表
     */
    @PreAuthorize("@ss.hasPermi('spec:plan:list')")
    @GetMapping("/listSeasonal")
    public TableDataInfo listSeasonal(TStFeedback feedback)
    {
        startPage();
        List<TStPlan> list = tStPlanService.selectSeasonalTStPlanList(feedback);
        return getDataTable(list);
    }

    /**
     * 我的培训页面查询
     * 根据STAFF_ID查询培训计划列表
     *
     * @autor 王子文
     * @date 2022年4月20日
     * @param tStPlan 培训计划对象
     * @return 培训计划列表
     */
    @PreAuthorize("@ss.hasPermi('spec:plan:list')")
    @GetMapping("/listByStaffId")
    public TableDataInfo listByStaffId(TStPlan tStPlan) {
        Long userId = getUserId();
        SysUser sysUser = sysUserService.selectUserById(userId);
        String staffId = sysUser.getStaffId();
        tStPlan.setStaffId(staffId);
        startPage();
        List<TStPlan> list = tStPlanService.selectTStPlanList(tStPlan);
        // 过滤掉申请状态为“未申请”或未通过的数据
        List<TStPlan> approvedList = list
                .stream()
                .filter( (TStPlan plan) -> plan.getApproveStatus() == 1 )
                .collect(Collectors.toList());
        return getDataTable(approvedList);
    }

    /**
     * 培训计划页面查询
     * 根据MENTOR_STAFF_ID查询培训计划列表
     *
     * @autor 王子文
     * @date 2022年4月20日
     * @param tStPlan 培训计划对象
     * @return 培训计划列表
     */
    @PreAuthorize("@ss.hasPermi('spec:plan:list')")
    @GetMapping("/listByMentorId")
    public TableDataInfo listByMentorId(TStPlan tStPlan) {
        Long userId = getUserId();
        SysUser sysUser = sysUserService.selectUserById(userId);
        String staffId = sysUser.getStaffId();
        tStPlan.setMentorStaffId(staffId);
        startPage();
        List<TStPlan> list = tStPlanService.selectTStPlanList(tStPlan);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('spec:plan:list')")
    @GetMapping("/listByYearId")
    public TableDataInfo listByYearId(TStPlan tStPlan) {
        startPage();
        List<TStPlan> list = tStPlanService.selectTStPlanList(tStPlan);
        //判断是否可以修改
        for (TStPlan t: list
        ) {
            try {
                if (new Date().before(t.getStartDate())){
                    t.setEditFlag(1);
                }else {
                    t.setEditFlag(0);
                }
            }catch (Exception e){
                t.setEditFlag(1);
            }
        }
        return getDataTable(list);
    }

    /**
     * 根据导师ID查询学员列表
     *
     * @autor 王子文
     * @date 2022年4月18日
     * @param tStSuccessor 继任者清单对象
     * @return 学员列表
     */
    @PreAuthorize("@ss.hasPermi('spec:plan:list')")
    @GetMapping("/listSuccessorsByMentorId")
    public AjaxResult getSuccessorListByMentorId(TStSuccessor tStSuccessor) {
        Long userId = getUserId();
        SysUser sysUser = sysUserService.selectUserById(userId);
        String staffId = sysUser.getStaffId();
        tStSuccessor.setMentorStaffId(staffId);
        List<TStSuccessor> tStSuccessors = tStSuccessorService.listSuccessorsByMentorId(tStSuccessor);
        return AjaxResult.success(tStSuccessors);
    }

    /**
     * 查询培训计划列表
     */
    @PreAuthorize("@ss.hasPermi('spec:plan:list')")
    @GetMapping("/list")
    public TableDataInfo list(TStPlan tStPlan)
    {
        startPage();
        List<TStPlan> list = tStPlanService.selectTStPlanList(tStPlan);
        //判断是否可以修改
        for (TStPlan t: list
             ) {
            try {
                if (new Date().before(t.getStartDate())){
                    t.setEditFlag(1);
                }else {
                    t.setEditFlag(0);
                }
            }catch (Exception e){
                t.setEditFlag(1);
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出培训计划列表
     */
    @PreAuthorize("@ss.hasPermi('spec:plan:export')")
    @Log(title = "培训计划", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TStPlan tStPlan)
    {
        // 培养计划
        List<TStPlan> plans = tStPlanService.selectTStPlanList(tStPlan);
        // 培养计划导出内容
        List<TStPlanExportVO> planVOs = new ArrayList<>();
        for (TStPlan plan : plans) {
            TStPlanExportVO planVO = new TStPlanExportVO();
            planVO.setStaffName(plan.getStaffName());
            planVO.setPlantName(plan.getPlantName());
            planVO.setStartDate(plan.getStartDate());
            planVO.setEndDate(plan.getEndDate());
            planVO.setDateOfCompletion(plan.getDateOfCompletion());
            planVO.setClassContent(plan.getClassContent());
            planVO.setStudyState(plan.getStudyState());
            planVO.setApproveStatus(plan.getApproveStatus());
            planVOs.add(planVO);
        }
        ExcelUtil<TStPlanExportVO> util = new ExcelUtil<TStPlanExportVO>(TStPlanExportVO.class);
        return util.exportExcel(planVOs, "培养计划明细");
    }

    /**
     * 获取培训计划详细信息
     */
    @PreAuthorize("@ss.hasPermi('spec:plan:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tStPlanService.selectTStPlanById(id));
    }

    /**
     * 新增培训计划
     */
    @PreAuthorize("@ss.hasPermi('spec:plan:add')")
    @Log(title = "培训计划", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TStPlan tStPlan)
    {
//        tStPlan.setStartYear((tStPlan.getStartDate().getYear() + 1900) + "");
//        tStPlan.setStartMonth((tStPlan.getStartDate().getMonth() + 1) + "");
        tStPlan.setCreaterCode(getUserId().toString());
        return toAjax(tStPlanService.insertTStPlan(tStPlan));
    }

    /**
     * 修改培训计划
     */
    @PreAuthorize("@ss.hasPermi('spec:plan:edit')")
    @Log(title = "培训计划", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TStPlan tStPlan)
    {
        tStPlan.setUpdaterCode(getUserId().toString());
        tStPlan.setUpdatedate(new Date());
        tStPlan.setApproveStatus(0L);

        TStYearplan tStYearplan = tStYearplanService.selectTStYearplanById(tStPlan.getYearPlanId());
        tStYearplan.setApproveStatus(0L);
        tStYearplanService.updateTStYearplan(tStYearplan);
        return toAjax(tStPlanService.updateTStPlan(tStPlan));
    }

    /**
     * 修改培训计划
     */
    @PreAuthorize("@ss.hasPermi('spec:plan:edit')")
    @Log(title = "培训计划", businessType = BusinessType.UPDATE)
    @PutMapping("/edit2")
    public AjaxResult edit2(@RequestBody TStPlan tStPlan)
    {
        //发送邮件
        try {
            TStPlan mailStPlan = tStPlanService.selectTStPlanById(tStPlan.getId());
            SysMessage message = new SysMessage();
            if (tStPlan.getStudyState().equals("2")){//待导师确认
                List<TStSuccessor> successorList = stSuccessorMapper.selectMentorListByStaffId(mailStPlan.getStaffId());
                if (successorList.size() > 0) {
                    TStSuccessor mentor = successorList.get(0);
                    SysUser mt = sysUserService.selectUserByStaffId(mentor.getMentorStaffId());
                    String email = mt.getEmail();
                    String username = mt.getNickName();
                    String usernameEN = PinyinHelper.convertToPinyinString(username, " ", PinyinFormat.WITHOUT_TONE);
                    logger.info("email:" + email);
                    logger.info("username:" + username);
                    message.setUserId(mt.getUserId());
                    message.setMsgTitle("您有一条系统消息");
                    message.setMsgContent("您有一条培训待导师确认");
                    PlanStudyMailThread sendEmailThead = new PlanStudyMailThread(mailService,email, username,usernameEN, mailStPlan,sysMessageService,message, 2);
                    Thread t = new Thread(sendEmailThead);
                    t.start();
                }
            }else if (tStPlan.getStudyState().equals("3")) { // 拒绝
                    SysUser xs = sysUserService.selectUserByStaffId(mailStPlan.getStaffId());
                    String email = xs.getEmail();
                    String username = xs.getNickName();
                    String usernameEN = PinyinHelper.convertToPinyinString(username, " ", PinyinFormat.WITHOUT_TONE);
                    logger.info("email:" + email);
                    logger.info("username:" + username);
                    message.setUserId(xs.getUserId());
                    message.setMsgTitle("您有一条系统消息");
                    message.setMsgContent("您有一条培训被导师拒绝");
                    PlanStudyMailThread sendEmailThead = new PlanStudyMailThread(mailService,email, username,usernameEN, mailStPlan,sysMessageService,message, 3);
                    Thread t = new Thread(sendEmailThead);
                    t.start();
            }else if (tStPlan.getStudyState().equals("1")) { //完成
                    SysUser xs = sysUserService.selectUserByStaffId(mailStPlan.getStaffId());
                    String email = xs.getEmail();
                    String username = xs.getNickName();
                    String usernameEN = PinyinHelper.convertToPinyinString(username, " ", PinyinFormat.WITHOUT_TONE);
                    logger.info("email:" + email);
                    logger.info("username:" + username);
                    message.setUserId(xs.getUserId());
                    message.setMsgTitle("您有一条系统消息");
                    message.setMsgContent("您有一条培训已完成");
                    PlanStudyMailThread sendEmailThead = new PlanStudyMailThread(mailService,email, username,usernameEN, mailStPlan,sysMessageService,message, 1);
                    Thread t = new Thread(sendEmailThead);
                    t.start();
                }
        }catch (Exception e) {
            logger.error("邮件发送失败" + JSON.toJSONString(e));
        }
        return toAjax(tStPlanService.updateTStPlan(tStPlan));
    }

    /**
     * 删除培训计划
     */
    @PreAuthorize("@ss.hasPermi('spec:plan:remove')")
    @Log(title = "培训计划", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tStPlanService.deleteTStPlanByIds(ids));
    }
}
