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.TTsLjplan;
import com.ruoyi.project.training.bccnew.domain.TTsLjplanContent;
import com.ruoyi.project.training.bccnew.domain.TTsNew;
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/ljplandsdt")
public class TTsLjplanController extends BaseController {
    @Autowired
    private ITTsLjplanService tTsLjplanService;
    @Autowired
    private ITTsLjplanContentService tTsLjplanContentService;
    @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(TTsLjplan tTsLjplan) {
        List<TTsLjplan> list = new ArrayList<>();
        List<TTsLjplan> tTsLjplans = tTsLjplanService.selectTTsLjplanList(tTsLjplan);
        StringBuilder content = null;//内容
        StringBuilder planDate = null;//计划培训时间
        TTsLjplan entity = null;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < tTsLjplans.size(); i++) {
            TTsLjplan item = tTsLjplans.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 (tTsLjplans.get(i - 1).getPlanDate() != null)
                        planDate.append(" ~ ").append(format.format(tTsLjplans.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 == tTsLjplans.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(TTsLjplan tTsLjplan) {
        List<TTsLjplan> list = tTsLjplanService.selectTTsLjplanList(tTsLjplan);
        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(TTsLjplan tTsLjplan) {
        List<TTsLjplan> list = tTsLjplanService.selectTTsLjplanList(tTsLjplan);
        ExcelUtil<TTsLjplan> util = new ExcelUtil<TTsLjplan>(TTsLjplan.class);
        return util.exportExcel(list, "ljplandsdt");
    }

    /**
     * 获取裂解培训详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tTsLjplanService.selectTTsLjplanById(id));
    }

    /**
     * 新增裂解培训
     */
    @Log(title = "裂解培训", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TTsLjplan tTsLjplan) {
        int i = tTsLjplanService.insertTTsLjplan(tTsLjplan);
        if (CollectionUtils.isNotEmpty(tTsLjplan.getContents())) {
            for (TTsLjplanContent content : tTsLjplan.getContents()) {
                content.setPid(tTsLjplan.getId());
                tTsLjplanContentService.insertTTsLjplanContent(content);
            }
        }
        return toAjax(i);
    }

    /**
     * 修改裂解培训
     */
    @Log(title = "裂解培训", businessType = BusinessType.UPDATE)
    @PutMapping("/updateLjLearnTime")
    @RepeatSubmit
    public AjaxResult updateLjLearnTime(@RequestBody TTsLjplan tTsLjplan) {
        Long userId = getUserId();
        TTsNew tTsNew = tTsNewService.selectTTsNewById(tTsLjplan.getNewId());
        SysUser sysUser = sysUserService.selectUserByStaffId(tTsNew.getStaffId());
        if (userId.equals(sysUser.getUserId())) {
            TTsLjplan need = tTsLjplanService.selectTTsLjplanById(tTsLjplan.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());
                }
            }

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


    /**
     * 修改裂解培训
     */
    @Log(title = "裂解培训", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TTsLjplan tTsLjplan) {
        if (CollectionUtils.isNotEmpty(tTsLjplan.getContents())) {
            for (TTsLjplanContent content : tTsLjplan.getContents()) {
                if (content.getId() == null) {
                    content.setPid(tTsLjplan.getId());
                    tTsLjplanContentService.insertTTsLjplanContent(content);
                } else {
                    tTsLjplanContentService.updateTTsLjplanContent(content);
                }
            }
        }
        TTsLjplan ljplan = tTsLjplanService.selectTTsLjplanById(tTsLjplan.getId());

        SysUser staff = sysUserService.selectUserByStaffId(tTsNewService.selectTTsNewById(ljplan.getNewId()).getStaffId());

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

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

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

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