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.interceptor.annotation.RepeatSubmit;
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.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysUserService;
import com.ruoyi.project.training.bccnew.domain.TTsNew;
import com.ruoyi.project.training.bccnew.domain.TTsYsplan;
import com.ruoyi.project.training.bccnew.domain.TTsYsplanContent;
import com.ruoyi.project.training.bccnew.service.*;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 转岗培训Controller
 *
 * @author ssy
 * @date 2024-06-13
 */
@RestController
@RequestMapping("/bccnew/ysplandsdt")
public class TTsYsplanController extends BaseController {
    @Autowired
    private ITTsYsplanService tTsYsplanService;
    @Autowired
    private ITTsYsplanContentService tTsYsplanContentService;
    @Autowired
    private ITTsNewService tTsNewService;
    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ITTsFirstplanService tTsFirstplanService;

    @Autowired
    private ITTsApproveService tTsApproveService;
    @Autowired
    private JiGuangPushService jiGuangPushService;

    /**
     * 查询转岗培训列表
     */
    @GetMapping("/list")
    public TableDataInfo list(TTsYsplan tTsYsplan) {
        List<TTsYsplan> list = new ArrayList<>();
        List<TTsYsplan> tTsYsplans = tTsYsplanService.selectTTsYsplanList(tTsYsplan);
        StringBuilder content = null;
        StringBuilder planDate = null;
        TTsYsplan entity = null;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < tTsYsplans.size(); i++) {
            TTsYsplan item = tTsYsplans.get(i);
            if (i == 0) {
                entity = item;
                content = new StringBuilder();
                planDate = new StringBuilder();
                if (item.getPlanDate() != null)
                    planDate.append(format.format(item.getPlanDate()));
                content.append(item.getCourseDay()).append("：").append(item.getContent()).append("；");
            } else {
                if (Objects.equals(entity.getPid(), item.getPid())) {
                    content.append(item.getCourseDay()).append("：").append(item.getContent()).append("；");
                } else {
                    if (tTsYsplans.get(i - 1).getPlanDate() != null)
                        planDate.append(" ~ ").append(format.format(tTsYsplans.get(i - 1).getPlanDate()));
                    entity.setContent(content.toString());
                    entity.setPlanStartData(planDate.toString());
                    list.add(entity);
                    entity = item;
                    content = new StringBuilder();
                    planDate = new StringBuilder();
                    if (item.getPlanDate() != null)
                        planDate.append(format.format(item.getPlanDate()));
                    content.append(item.getCourseDay()).append("：").append(item.getContent()).append("；");
                }
            }
            if (i + 1 == tTsYsplans.size()) {
                if (item.getPlanDate() != null)
                    planDate.append(" ~ ").append(format.format(item.getPlanDate()));
                entity.setContent(content.toString());
                entity.setPlanStartData(planDate.toString());
                list.add(entity);
            }
        }
        for (int i = 0; i < list.size(); i++) {
            if (i == 0) {
                list.get(i).setStudy(1);
            }
            if ((list.get(i).getPlanStatus() == 5 || list.get(i).getPlanStatus() == 1) && i <= list.size() - 1) {
                list.get(i).setStudy(1);
                if(i < list.size() - 1) {
                    list.get(i + 1).setStudy(1);
                }
            }
            if (list.get(i).getStudy() == null) {
                list.get(i).setStudy(0);
            }
        }

        //startPage();
        return getDataTable(list);
    }


    /**
     * 查询分离培训列表
     */
    @GetMapping("/listAll")
    public AjaxResult listAll(TTsYsplan tTsYsplan) {
        List<TTsYsplan> list = tTsYsplanService.selectTTsYsplanList(tTsYsplan);
        for (int i = 0; i < list.size(); i++) {
            if (i == 0) {
                list.get(i).setStudy(1);
            }
            if ((list.get(i).getPlanStatus() == 5 || list.get(i).getPlanStatus() == 1) && i <= list.size() - 1) {
                list.get(i).setStudy(1);
                if(i < list.size() - 1) {
                    list.get(i + 1).setStudy(1);
                }
            }
            if (list.get(i).getStudy() == null) {
                list.get(i).setStudy(0);
            }
        }
        return AjaxResult.success(list);
    }

    /**
     * 导出转岗培训列表
     */
    @Log(title = "转岗培训", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TTsYsplan tTsYsplan) {
        List<TTsYsplan> list = tTsYsplanService.selectTTsYsplanList(tTsYsplan);
        ExcelUtil<TTsYsplan> util = new ExcelUtil<TTsYsplan>(TTsYsplan.class);
        return util.exportExcel(list, "ysplandsdt");
    }

    /**
     * 获取转岗培训详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tTsYsplanService.selectTTsYsplanById(id));
    }

    /**
     * 新增转岗培训
     */
    @Log(title = "转岗培训", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TTsYsplan tTsYsplan) {
        int i = tTsYsplanService.insertTTsYsplan(tTsYsplan);
        if (CollectionUtils.isNotEmpty(tTsYsplan.getContents())) {
            for (TTsYsplanContent content : tTsYsplan.getContents()) {
                content.setPid(tTsYsplan.getId());
                tTsYsplanContentService.insertTTsYsplanContent(content);
            }
        }
        return toAjax(i);
    }


    @Log(title = "压缩培训", businessType = BusinessType.UPDATE)
    @PutMapping("/updateYsLearnTime")
    public AjaxResult updateYsLearnTime(@RequestBody TTsYsplan tTsYsplan) {
        Long userId = getUserId();
        TTsNew tTsNew = tTsNewService.selectTTsNewById(tTsYsplan.getNewId());
        SysUser sysUser = sysUserService.selectUserByStaffId(tTsNew.getStaffId());
        if (userId.equals(sysUser.getUserId())) {
            TTsYsplan need = tTsYsplanService.selectTTsYsplanById(tTsYsplan.getId());
            long timer = need.getTimer() == null ? 0 : need.getTimer();
            if (timer < need.getTimerNeed()) {
                need.setTimer(timer + 1);
                if (need.getTimerNeed() == null)
                    need.setTimerNeed(0.0);
                if (need.getTimerNeed() != null && need.getTimerNeed() <= timer + 1 && need.getPlanStatus() == 0) {
                    need.setPlanStatus(2L);

                    sysUser = new SysUser();
                    sysUser.setNickName(need.getTrainer());
                    SysUser trainer = sysUserService.selectUserByStaffId(tTsNew.getMentorStaffId());
                    sysUser = new SysUser();
                    SysUser staff = sysUserService.selectUserByStaffId(tTsNew.getStaffId());
                    jiGuangPushService.send("导师带徒-导师带徒（压缩）培训", staff.getNickName() + "的学习已完成，请进行线下考试，并上传成绩。", trainer.getUserId().toString());
                }
            }

            tTsYsplanService.updateTTsYsplan(need);
            return AjaxResult.success(need.getTimer());
        }
        return AjaxResult.error("当前登录用户非学习用户!");
    }

    /**
     * 修改转岗培训
     */
    @Log(title = "转岗培训", businessType = BusinessType.UPDATE)
    @PutMapping
    @RepeatSubmit
    public AjaxResult edit(@RequestBody TTsYsplan tTsYsplan) {
        if (CollectionUtils.isNotEmpty(tTsYsplan.getContents())) {
            for (TTsYsplanContent content : tTsYsplan.getContents()) {
                if (content.getId() == null) {
                    content.setPid(tTsYsplan.getId());
                    tTsYsplanContentService.insertTTsYsplanContent(content);
                } else {
                    tTsYsplanContentService.updateTTsYsplanContent(content);
                }
            }
        }
        TTsYsplan ysplan = tTsYsplanService.selectTTsYsplanById(tTsYsplan.getId());
        SysUser staff = sysUserService.selectUserByStaffId(tTsNewService.selectTTsNewById(ysplan.getNewId()).getStaffId());

        if ("好".equals(tTsYsplan.getScore1())) {
            tTsYsplan.setPlanStatus(5L);
            jiGuangPushService.send("导师带徒-导师带徒（压缩）培训", "您的成绩为——好，可以进行下一项培训啦！", staff.getUserId().toString());

        }
        if ((("满意".equals(tTsYsplan.getScore1()) || "差".equals(tTsYsplan.getScore1())) && tTsYsplan.getScore2() == null) ||
                (("满意".equals(tTsYsplan.getScore2()) || "差".equals(tTsYsplan.getScore2())) && tTsYsplan.getScore3() == null)) {
            tTsYsplan.setScorePass(0);
            jiGuangPushService.send("导师带徒-导师带徒（压缩）培训", "本次考试不合格，请等待经理审批后再次进行线下考试", staff.getUserId().toString());
            tTsApproveService.doApprove(ysplan.getId(), "2", getUserId(), getNickName(), "dsdtNoPass");
        }
        if (("满意".equals(tTsYsplan.getScore1()) || "满意".equals(ysplan.getScore1())) && "好".equals(tTsYsplan.getScore2())) {
            tTsYsplan.setPlanStatus(5L);
        }
        if (("满意".equals(tTsYsplan.getScore1()) || "满意".equals(ysplan.getScore1())) && ("满意".equals(tTsYsplan.getScore2()) || "满意".equals(ysplan.getScore2())) && "好".equals(tTsYsplan.getScore3())) {
            tTsYsplan.setPlanStatus(5L);
        }
        if (("满意".equals(tTsYsplan.getScore1()) || "满意".equals(ysplan.getScore1())) && ("差".equals(tTsYsplan.getScore2()) || "差".equals(ysplan.getScore2())) && "好".equals(tTsYsplan.getScore3())) {
            tTsYsplan.setPlanStatus(5L);
        }
        if (("满意".equals(tTsYsplan.getScore1()) || "满意".equals(ysplan.getScore1())) && ("满意".equals(tTsYsplan.getScore2()) || "满意".equals(ysplan.getScore2())) && "差".equals(tTsYsplan.getScore3())) {
            tTsYsplan.setPlanStatus(4L);
        }
        if (("满意".equals(tTsYsplan.getScore1()) || "满意".equals(ysplan.getScore1())) && ("差".equals(tTsYsplan.getScore2()) || "差".equals(ysplan.getScore2())) && "满意".equals(tTsYsplan.getScore3())) {
            tTsYsplan.setPlanStatus(4L);
        }
        if (("满意".equals(tTsYsplan.getScore1()) || "满意".equals(ysplan.getScore1())) && ("满意".equals(tTsYsplan.getScore2()) || "满意".equals(ysplan.getScore2())) && "满意".equals(tTsYsplan.getScore3())) {
            tTsYsplan.setPlanStatus(4L);
        }
        if (("满意".equals(tTsYsplan.getScore1()) || "满意".equals(ysplan.getScore1())) && ("差".equals(tTsYsplan.getScore2()) || "差".equals(ysplan.getScore2())) && "差".equals(tTsYsplan.getScore3())) {
            tTsYsplan.setPlanStatus(4L);
        }
        if (("差".equals(tTsYsplan.getScore1()) || "差".equals(ysplan.getScore1())) && "好".equals(tTsYsplan.getScore2())) {
            tTsYsplan.setPlanStatus(5L);
        }
        if (("差".equals(tTsYsplan.getScore1()) || "差".equals(ysplan.getScore1())) && "满意".equals(tTsYsplan.getScore2())) {
            tTsYsplan.setPlanStatus(4L);
        }
        if (("差".equals(tTsYsplan.getScore1()) || "差".equals(ysplan.getScore1())) && "差".equals(tTsYsplan.getScore2())) {
            tTsYsplan.setPlanStatus(4L);
        }
        tTsYsplanService.updateTTsYsplan(tTsYsplan);
        if (tTsYsplan.getPlanStatus() != null) {
            if (tTsYsplan.getPlanStatus() == 5) {
                TTsNew tTsNew = new TTsNew();
                tTsNew.setPlanStatus(5L);
                tTsNew.setNewId(tTsYsplan.getNewId());
                tTsNew.setPlanType(2L);
                tTsNewService.updateTTsNew(tTsNew, getUserId(), getNickName());

            } else if (tTsYsplan.getPlanStatus() == 4) {
                TTsNew tTsNew = new TTsNew();
                tTsNew.setPlanStatus(4L);
                tTsNew.setNewId(tTsYsplan.getNewId());
                tTsNew.setPlanType(2L);
                tTsNewService.updateTTsNew(tTsNew, getUserId(), getNickName());
            }
        }
        return toAjax(1);
    }

    /**
     * 删除转岗培训
     */
    @Log(title = "转岗培训", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tTsYsplanService.deleteTTsYsplanByIds(ids));
    }
}
