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.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysUserService;
import com.ruoyi.project.training.bccnew.domain.TTsFtplan;
import com.ruoyi.project.training.bccnew.domain.TTsFtplanContent;
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/ftplandsdt")
public class TTsFtplanController extends BaseController {
    @Autowired
    private ITTsFtplanService tTsFtplanService;
    @Autowired
    private ITTsFtplanContentService tTsFtplanContentService;
    @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(TTsFtplan tTsFtplan) {
        List<TTsFtplan> list = new ArrayList<>();
        List<TTsFtplan> tTsFtplans = tTsFtplanService.selectTTsFtplanList(tTsFtplan);
        StringBuilder content = null;
        StringBuilder planDate = null;
        TTsFtplan entity = null;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < tTsFtplans.size(); i++) {
            TTsFtplan item = tTsFtplans.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 (tTsFtplans.get(i - 1).getPlanDate() != null)
                        planDate.append(" ~ ").append(format.format(tTsFtplans.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 == tTsFtplans.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(TTsFtplan tTsFtplan) {
        List<TTsFtplan> list = tTsFtplanService.selectTTsFtplanList(tTsFtplan);
        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(TTsFtplan tTsFtplan) {
        List<TTsFtplan> list = tTsFtplanService.selectTTsFtplanList(tTsFtplan);
        ExcelUtil<TTsFtplan> util = new ExcelUtil<TTsFtplan>(TTsFtplan.class);
        return util.exportExcel(list, "ftplandsdt");
    }

    /**
     * 获取芳烃培训详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tTsFtplanService.selectTTsFtplanById(id));
    }

    /**
     * 新增芳烃培训
     */
    @Log(title = "芳烃培训", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TTsFtplan tTsFtplan) {
        int i = tTsFtplanService.insertTTsFtplan(tTsFtplan);
        if (CollectionUtils.isNotEmpty(tTsFtplan.getContents())) {
            for (TTsFtplanContent content : tTsFtplan.getContents()) {
                content.setPid(tTsFtplan.getId());
                tTsFtplanContentService.insertTTsFtplanContent(content);
            }
        }
        return toAjax(i);
    }

    @Log(title = "芳烃培训", businessType = BusinessType.UPDATE)
    @PutMapping("/updateFtLearnTime")
    public AjaxResult updateFtLearnTime(@RequestBody TTsFtplan tTsFtplan) {
        Long userId = getUserId();
        TTsNew tTsNew = tTsNewService.selectTTsNewById(tTsFtplan.getNewId());
        SysUser sysUser = sysUserService.selectUserByStaffId(tTsNew.getStaffId());
        if (userId.equals(sysUser.getUserId())) {
            TTsFtplan need = tTsFtplanService.selectTTsFtplanById(tTsFtplan.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());

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

    /**
     * 修改芳烃培训
     */
    @Log(title = "芳烃培训", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TTsFtplan tTsFtplan) {
        if (CollectionUtils.isNotEmpty(tTsFtplan.getContents())) {
            for (TTsFtplanContent content : tTsFtplan.getContents()) {
                if (content.getId() == null) {
                    content.setPid(tTsFtplan.getId());
                    tTsFtplanContentService.insertTTsFtplanContent(content);
                } else {
                    tTsFtplanContentService.updateTTsFtplanContent(content);
                }
            }
        }
        TTsFtplan ftplan = tTsFtplanService.selectTTsFtplanById(tTsFtplan.getId());
        SysUser staff = sysUserService.selectUserByStaffId(tTsNewService.selectTTsNewById(ftplan.getNewId()).getStaffId());
        if ("好".equals(tTsFtplan.getScore1())) {
            tTsFtplan.setPlanStatus(5L);
            jiGuangPushService.send("导师带徒-导师带徒（芳烃）培训", "您的成绩为——好，可以进行下一项培训啦！", staff.getUserId().toString());
        }
        if ((("满意".equals(tTsFtplan.getScore1()) || "差".equals(tTsFtplan.getScore1())) && tTsFtplan.getScore2() == null) ||
                (("满意".equals(tTsFtplan.getScore2()) || "差".equals(tTsFtplan.getScore2())) && tTsFtplan.getScore3() == null)) {
            tTsFtplan.setScorePass(0);
            jiGuangPushService.send("导师带徒-导师带徒（芳烃）培训", "本次考试不合格，请等待经理审批后再次进行线下考试", staff.getUserId().toString());
            tTsApproveService.doApprove(ftplan.getId(), "4", getUserId(), getNickName(), "dsdtNoPass");
        }
        if (("满意".equals(tTsFtplan.getScore1()) || "满意".equals(ftplan.getScore1())) && "好".equals(tTsFtplan.getScore2())) {
            tTsFtplan.setPlanStatus(5L);
        }
        if (("满意".equals(tTsFtplan.getScore1()) || "满意".equals(ftplan.getScore1())) && ("满意".equals(tTsFtplan.getScore2()) || "满意".equals(ftplan.getScore2())) && "好".equals(tTsFtplan.getScore3())) {
            tTsFtplan.setPlanStatus(5L);
        }
        if (("满意".equals(tTsFtplan.getScore1()) || "满意".equals(ftplan.getScore1())) && ("差".equals(tTsFtplan.getScore2()) || "差".equals(ftplan.getScore2())) && "好".equals(tTsFtplan.getScore3())) {
            tTsFtplan.setPlanStatus(5L);
        }
        if (("满意".equals(tTsFtplan.getScore1()) || "满意".equals(ftplan.getScore1())) && ("满意".equals(tTsFtplan.getScore2()) || "满意".equals(ftplan.getScore2())) && "差".equals(tTsFtplan.getScore3())) {
            tTsFtplan.setPlanStatus(4L);
        }
        if (("满意".equals(tTsFtplan.getScore1()) || "满意".equals(ftplan.getScore1())) && ("差".equals(tTsFtplan.getScore2()) || "差".equals(ftplan.getScore2())) && "满意".equals(tTsFtplan.getScore3())) {
            tTsFtplan.setPlanStatus(4L);
        }
        if (("满意".equals(tTsFtplan.getScore1()) || "满意".equals(ftplan.getScore1())) && ("满意".equals(tTsFtplan.getScore2()) || "满意".equals(ftplan.getScore2())) && "满意".equals(tTsFtplan.getScore3())) {
            tTsFtplan.setPlanStatus(4L);
        }
        if (("满意".equals(tTsFtplan.getScore1()) || "满意".equals(ftplan.getScore1())) && ("差".equals(tTsFtplan.getScore2()) || "差".equals(ftplan.getScore2())) && "差".equals(tTsFtplan.getScore3())) {
            tTsFtplan.setPlanStatus(4L);
        }
        if (("差".equals(tTsFtplan.getScore1()) || "差".equals(ftplan.getScore1())) && "好".equals(tTsFtplan.getScore2())) {
            tTsFtplan.setPlanStatus(5L);
        }
        if (("差".equals(tTsFtplan.getScore1()) || "差".equals(ftplan.getScore1())) && "满意".equals(tTsFtplan.getScore2())) {
            tTsFtplan.setPlanStatus(4L);
        }
        if (("差".equals(tTsFtplan.getScore1()) || "差".equals(ftplan.getScore1())) && "差".equals(tTsFtplan.getScore2())) {
            tTsFtplan.setPlanStatus(4L);
        }
        tTsFtplanService.updateTTsFtplan(tTsFtplan);
        if (tTsFtplan.getPlanStatus() != null) {
            if (tTsFtplan.getPlanStatus() == 5) {
                TTsNew tTsNew = new TTsNew();
                tTsNew.setPlanStatus(5L);
                tTsNew.setPlanType(4L);
                tTsNew.setNewId(tTsFtplan.getNewId());
                tTsNewService.updateTTsNew(tTsNew, getUserId(), getNickName());
            } else if (tTsFtplan.getPlanStatus() == 4) {
                TTsNew tTsNew = new TTsNew();
                tTsNew.setPlanStatus(4L);
                tTsNew.setPlanType(4L);
                tTsNew.setNewId(tTsFtplan.getNewId());
                tTsNewService.updateTTsNew(tTsNew, getUserId(), getNickName());
            }
        }
        return toAjax(1);
    }

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