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.TTsFlplan;
import com.ruoyi.project.training.bccnew.domain.TTsFlplanContent;
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/flplandsdt")
public class TTsFlplanController extends BaseController {
    @Autowired
    private ITTsFlplanService tTsFlplanService;
    @Autowired
    private ITTsFlplanContentService tTsFlplanContentService;
    @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(TTsFlplan tTsFlplan) {
        List<TTsFlplan> list = new ArrayList<>();
        List<TTsFlplan> tTsFlplans = tTsFlplanService.selectTTsFlplanList(tTsFlplan);
        StringBuilder content = null;
        StringBuilder planDate = null;
        TTsFlplan entity = null;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < tTsFlplans.size(); i++) {
            TTsFlplan item = tTsFlplans.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 (tTsFlplans.get(i - 1).getPlanDate() != null)
                        planDate.append(" ~ ").append(format.format(tTsFlplans.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 == tTsFlplans.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(TTsFlplan tTsFlplan) {
        List<TTsFlplan> list = tTsFlplanService.selectTTsFlplanList(tTsFlplan);
        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(TTsFlplan tTsFlplan) {
        List<TTsFlplan> list = tTsFlplanService.selectTTsFlplanList(tTsFlplan);
        ExcelUtil<TTsFlplan> util = new ExcelUtil<TTsFlplan>(TTsFlplan.class);
        return util.exportExcel(list, "flplandsdt");
    }

    /**
     * 获取分离培训详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tTsFlplanService.selectTTsFlplanById(id));
    }

    /**
     * 新增分离培训
     */
    @Log(title = "分离培训", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TTsFlplan tTsFlplan) {
        int i = tTsFlplanService.insertTTsFlplan(tTsFlplan);
        if (CollectionUtils.isNotEmpty(tTsFlplan.getContents())) {
            for (TTsFlplanContent content : tTsFlplan.getContents()) {
                content.setPid(tTsFlplan.getId());
                tTsFlplanContentService.insertTTsFlplanContent(content);
            }
        }
        return toAjax(i);
    }


    @Log(title = "分离培训", businessType = BusinessType.UPDATE)
    @PutMapping("/updateFlLearnTime")
    public AjaxResult updateFlLearnTime(@RequestBody TTsFlplan tTsFlplan) {
        Long userId = getUserId();
        TTsNew tTsNew = tTsNewService.selectTTsNewById(tTsFlplan.getNewId());
        SysUser sysUser = sysUserService.selectUserByStaffId(tTsNew.getStaffId());
        if (userId.equals(sysUser.getUserId())) {
            TTsFlplan need = tTsFlplanService.selectTTsFlplanById(tTsFlplan.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());

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

    /**
     * 修改分离培训
     */
    @Log(title = "分离培训", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TTsFlplan tTsFlplan) {
        if (CollectionUtils.isNotEmpty(tTsFlplan.getContents())) {
            for (TTsFlplanContent content : tTsFlplan.getContents()) {
                if (content.getId() == null) {
                    content.setPid(tTsFlplan.getId());
                    tTsFlplanContentService.insertTTsFlplanContent(content);
                } else {
                    tTsFlplanContentService.updateTTsFlplanContent(content);
                }
            }
        }
        TTsFlplan flplan = tTsFlplanService.selectTTsFlplanById(tTsFlplan.getId());

        SysUser staff = sysUserService.selectUserByStaffId(tTsNewService.selectTTsNewById(flplan.getNewId()).getStaffId());
        if ("好".equals(tTsFlplan.getScore1())) {
            tTsFlplan.setPlanStatus(5L);
            jiGuangPushService.send("导师带徒-导师带徒（分离）培训", "您的成绩为——好，可以进行下一项培训啦！", staff.getUserId().toString());
        }
        if ((("满意".equals(tTsFlplan.getScore1()) || "差".equals(tTsFlplan.getScore1())) && tTsFlplan.getScore2() == null) ||
                (("满意".equals(tTsFlplan.getScore2()) || "差".equals(tTsFlplan.getScore2())) && tTsFlplan.getScore3() == null)) {
            tTsFlplan.setScorePass(0);
            tTsApproveService.doApprove(flplan.getId(), "3", getUserId(), getNickName(), "dsdtNoPass");
            jiGuangPushService.send("导师带徒-导师带徒（分离）培训", "本次考试不合格，请等待经理审批后再次进行线下考试", staff.getUserId().toString());
        }
        if (("满意".equals(tTsFlplan.getScore1()) || "满意".equals(flplan.getScore1())) && "好".equals(tTsFlplan.getScore2())) {
            tTsFlplan.setPlanStatus(5L);
        }
        if (("满意".equals(tTsFlplan.getScore1()) || "满意".equals(flplan.getScore1())) && ("满意".equals(tTsFlplan.getScore2()) || "满意".equals(flplan.getScore2())) && "好".equals(tTsFlplan.getScore3())) {
            tTsFlplan.setPlanStatus(5L);
        }
        if (("满意".equals(tTsFlplan.getScore1()) || "满意".equals(flplan.getScore1())) && ("差".equals(tTsFlplan.getScore2()) || "差".equals(flplan.getScore2())) && "好".equals(tTsFlplan.getScore3())) {
            tTsFlplan.setPlanStatus(5L);
        }
        if (("满意".equals(tTsFlplan.getScore1()) || "满意".equals(flplan.getScore1())) && ("满意".equals(tTsFlplan.getScore2()) || "满意".equals(flplan.getScore2())) && "差".equals(tTsFlplan.getScore3())) {
            tTsFlplan.setPlanStatus(4L);
        }
        if (("满意".equals(tTsFlplan.getScore1()) || "满意".equals(flplan.getScore1())) && ("差".equals(tTsFlplan.getScore2()) || "差".equals(flplan.getScore2())) && "满意".equals(tTsFlplan.getScore3())) {
            tTsFlplan.setPlanStatus(4L);
        }
        if (("满意".equals(tTsFlplan.getScore1()) || "满意".equals(flplan.getScore1())) && ("满意".equals(tTsFlplan.getScore2()) || "满意".equals(flplan.getScore2())) && "满意".equals(tTsFlplan.getScore3())) {
            tTsFlplan.setPlanStatus(4L);
        }
        if (("满意".equals(tTsFlplan.getScore1()) || "满意".equals(flplan.getScore1())) && ("差".equals(tTsFlplan.getScore2()) || "差".equals(flplan.getScore2())) && "差".equals(tTsFlplan.getScore3())) {
            tTsFlplan.setPlanStatus(4L);
        }
        if (("差".equals(tTsFlplan.getScore1()) || "差".equals(flplan.getScore1())) && "好".equals(tTsFlplan.getScore2())) {
            tTsFlplan.setPlanStatus(5L);
        }
        if (("差".equals(tTsFlplan.getScore1()) || "差".equals(flplan.getScore1())) && "满意".equals(tTsFlplan.getScore2())) {
            tTsFlplan.setPlanStatus(4L);
        }
        if (("差".equals(tTsFlplan.getScore1()) || "差".equals(flplan.getScore1())) && "差".equals(tTsFlplan.getScore2())) {
            tTsFlplan.setPlanStatus(4L);
        }
        tTsFlplanService.updateTTsFlplan(tTsFlplan);
        if (tTsFlplan.getPlanStatus() != null) {
            if (tTsFlplan.getPlanStatus() == 5) {
                TTsNew tTsNew = new TTsNew();
                tTsNew.setPlanStatus(5L);
                tTsNew.setPlanType(3L);
                tTsNew.setNewId(tTsFlplan.getNewId());
                tTsNewService.updateTTsNew(tTsNew, getUserId(), getNickName());
            } else if (tTsFlplan.getPlanStatus() == 4) {
                TTsNew tTsNew = new TTsNew();
                tTsNew.setPlanStatus(4L);
                tTsNew.setPlanType(3L);
                tTsNew.setNewId(tTsFlplan.getNewId());
                tTsNewService.updateTTsNew(tTsNew, getUserId(), getNickName());
            }
        }
        return AjaxResult.success();
    }

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