package com.ruoyi.project.training.controller;

import java.time.LocalDate;
import java.util.*;

import com.ruoyi.framework.interceptor.annotation.RepeatSubmit;
import com.ruoyi.project.plant.domain.TStaffmgr;
import com.ruoyi.project.plant.service.ITStaffmgrService;
import com.ruoyi.project.system.domain.SysDictData;
import com.ruoyi.project.system.service.ISysDictTypeService;
import com.ruoyi.project.training.domain.*;
import com.ruoyi.project.training.service.*;
import org.apache.commons.lang.StringUtils;
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.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;

/**
 * 装置培训计划Controller
 *
 * @author ssy
 * @date 2024-06-24
 */
@RestController
@RequestMapping("/training/bccregular")
public class TTrainingbccRegularController extends BaseController
{
    @Autowired
    private ITTrainingbccRegularService tTrainingbccRegularService;
    @Autowired
    private ISysDictTypeService iSysDictTypeService;
    @Autowired
    private ITTrainingbccService trainingbccService;

    @Autowired
    private ITTrainingbccDeviceService trainingbccDeviceService;
    @Autowired
    private ITTrainingMatrixService tTrainingMatrixService;
    @Autowired
    private ITStaffmgrService tStaffmgrService;
    /**
     * 查询装置培训计划列表
     */
    @PreAuthorize("@ss.hasPermi('training:bccregular:list')")
    @GetMapping("/list")
    public TableDataInfo list(TTrainingbccRegular tTrainingRegular)
    {
        startPage();
        List<TTrainingbccRegular> list = tTrainingbccRegularService.selectTTrainingbccRegularList(tTrainingRegular);
        List<SysDictData> actualpost = iSysDictTypeService.selectDictDataByType("ACTUALPOST");
        for (TTrainingbccRegular t : list) {
            String[] actualpostId = new String[0];;
            if (t.getActualpostId() != null) {
                actualpostId = t.getActualpostId().split(",");
            }
            List<String> postStatu = new ArrayList<>();
            for (SysDictData p : actualpost) {
                int i = 0;
                for (String a : actualpostId) {
                    if (p.getDictValue().equals(a)) {
                        i = 1;
                    }
                }
                if (t.getDesignatedPosition() != null) {
                    String[] designatedPosition = t.getDesignatedPosition().split(",");
                    for (String d : designatedPosition) {
                        if (p.getDictValue().equals(d)) {
                            i = 2;
                        }
                    }
                }
                if (i == 1) {
                    postStatu.add("M");
                }else if (i == 2) {
                    postStatu.add("|");
                }else {
                    postStatu.add("-");
                }
            }
            if (t.getInvolvedMoc().equals("true")) {
                if (t.getDesignatedOther() != null) {
                    String[] designatedOther = t.getDesignatedOther().split(",");
                    for (String d : designatedOther) {
                        if (d.equals("28")) {
                            postStatu.set(postStatu.size() - 5, "(M)");
                        }
                        if (d.equals("30")) {
                            postStatu.set(postStatu.size() - 4, "(M)");
                        }
                        if (d.equals("32")) {
                            postStatu.set(postStatu.size() - 3, "(M)");
                        }
                    }
                }
            }
            t.setActualpost(postStatu);
        }
        return getDataTable(list);
    }

    /**
     * 导出装置培训计划列表
     */
    @PreAuthorize("@ss.hasPermi('training:bccregular:export')")
    @Log(title = "装置培训计划", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TTrainingbccRegular tTrainingbccRegular)
    {
        List<TTrainingbccRegular> list = tTrainingbccRegularService.selectTTrainingbccRegularList(tTrainingbccRegular);
        ExcelUtil<TTrainingbccRegular> util = new ExcelUtil<TTrainingbccRegular>(TTrainingbccRegular.class);
        return util.exportExcel(list, "bccregular");
    }

    /**
     * 获取装置培训计划详细信息
     */
    @PreAuthorize("@ss.hasPermi('training:bccregular:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tTrainingbccRegularService.selectTTrainingbccRegularById(id));
    }

    /**
     * 新增装置培训计划
     */
    @PreAuthorize("@ss.hasPermi('training:bccregular:add')")
    @Log(title = "装置培训计划", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TTrainingbccRegular tTrainingRegular)
    {
        int doInsert = tTrainingbccRegularService.insertTTrainingbccRegular(tTrainingRegular);
        logger.info("regular:" + tTrainingRegular);
        tTrainingRegular.setDeptId(103l); //bcc专用
        //如果确定计划日期新增关联内容
        if (tTrainingRegular.getNotPlan().equals("true")) {
            //新增培训计划定期类
            TTrainingbcc tTraining = new TTrainingbcc();
            tTraining.setTrainingType("10");
            tTraining.setYears(tTrainingRegular.getYear());
            tTraining.setCourse(tTrainingRegular.getItem());
            tTraining.setCourseid(tTrainingRegular.getCourseCode());
            tTraining.setDuration(tTrainingRegular.getHour());
            tTraining.setTrainer(tTrainingRegular.getLecturer());
            tTraining.setPosition(tTrainingRegular.getActualpostId());
            tTraining.setIsfinish(Long.parseLong("0"));
            tTraining.setDeptId(tTrainingRegular.getDeptId());
            tTraining.setRegularId(tTrainingRegular.getId());
            trainingbccService.insertTTrainingbcc(tTraining);
            Long trainingId = tTraining.getId();
            //新增人员-装置级关系
            // 参培岗位人员
            if (tTrainingRegular.getActualpostId() != null) {
                logger.info("参培岗位人员");
                TStaffmgr staffmgr = new TStaffmgr();
                staffmgr.setActualposts(tTrainingRegular.getActualpostId());
                staffmgr.setDeptId(tTrainingRegular.getDeptId());
                List<TStaffmgr> staffmgrs = tStaffmgrService.selectAllTStaffmgrList(staffmgr);
                try {
                    //判断离职
                    if (!StringUtils.isEmpty(tTrainingRegular.getYear())) {
                        Iterator<TStaffmgr> iterator = staffmgrs.iterator();
                        while (iterator.hasNext()) {
                            TStaffmgr t = iterator.next();
                            if (t.getLeftDate() != null && t.getDelFlag() == 9){
                                if (t.getLeftDate().getTime() - tTrainingRegular.getPlanTrainingdate().getTime() < 0l ) {
                                    logger.debug(t.getName() + "离职时间小于培训时间");
                                    iterator.remove();
                                }
                            }
                        }
                    }
                }catch (Exception e) {
                    logger.error(e.toString());
                }
                for (TStaffmgr s : staffmgrs) {
                    TTrainingbccDevice tTrainingDevice = new TTrainingbccDevice();
                    tTrainingDevice.setStaffId(s.getStaffid());
                    tTrainingDevice.setRegularId(trainingId);
                    tTrainingDevice.setStartDate(tTrainingRegular.getPlanTrainingdate());
                    tTrainingDevice.setSupplementary("0");
                    trainingbccDeviceService.insertTTrainingbccDevice(tTrainingDevice);
                }
            }
            //指定岗位人员
            if (tTrainingRegular.getDesignatedStaff() != null) {
                logger.info("指定岗位人员");
                String[] designatedStaffs = tTrainingRegular.getDesignatedStaff().split(",");
                for (String staffId : designatedStaffs) {
                    TTrainingbccDevice tTrainingDevice = new TTrainingbccDevice();
                    tTrainingDevice.setStaffId(staffId);
                    tTrainingDevice.setRegularId(trainingId);
                    tTrainingDevice.setStartDate(tTrainingRegular.getPlanTrainingdate());
                    tTrainingDevice.setSupplementary("0");
                    trainingbccDeviceService.insertTTrainingbccDevice(tTrainingDevice);
                }
            }
            //涉及其他部门
            if (tTrainingRegular.getInvolvedMoc().equals("true")){
                logger.info("涉及MOC人员");
                TStaffmgr staffmgrMoc = new TStaffmgr();
                staffmgrMoc.setActualposts(tTrainingRegular.getDesignatedOther());
                List<TStaffmgr> staffmgrsMoc = tStaffmgrService.selectAllTStaffmgrList(staffmgrMoc);
                try {
                    //判断离职
                    if (!StringUtils.isEmpty(tTrainingRegular.getYear())) {
                        Iterator<TStaffmgr> iterator = staffmgrsMoc.iterator();
                        while (iterator.hasNext()) {
                            TStaffmgr t = iterator.next();
                            if (t.getLeftDate() != null && t.getDelFlag() == 9){
                                if (t.getLeftDate().getTime() - tTrainingRegular.getPlanTrainingdate().getTime() > 0l ) {
                                    logger.debug(t.getName() + "离职时间小于培训时间");
                                    iterator.remove();
                                }
                            }
                        }
                    }
                }catch (Exception e) {
                    logger.error(e.toString());
                }
                for (TStaffmgr s : staffmgrsMoc) {
                    TTrainingbccDevice tTrainingDevice = new TTrainingbccDevice();
                    tTrainingDevice.setStaffId(s.getStaffid());
                    tTrainingDevice.setRegularId(trainingId);
                    tTrainingDevice.setStartDate(tTrainingRegular.getPlanTrainingdate());
                    tTrainingDevice.setSupplementary("0");
                    trainingbccDeviceService.insertTTrainingbccDevice(tTrainingDevice);
                }
            }
        }
        return toAjax(doInsert);
    }

    /**
     * 新增装置培训计划
     */
    @PreAuthorize("@ss.hasPermi('training:bccregular:add')")
    @Log(title = "装置培训计划", businessType = BusinessType.INSERT)
    @GetMapping("batchAddTraining")
    @RepeatSubmit
    public AjaxResult addBatch() {
        TTrainingbccRegular tr =new TTrainingbccRegular();
        TTrainingMatrix tTrainingMatrix = new TTrainingMatrix();
        tTrainingMatrix.setDeptId(103l);
        tTrainingMatrix.setTrainingLevel("14");
        List<TTrainingMatrix> list = tTrainingMatrixService.selectTTrainingMatrixList(tTrainingMatrix);
        logger.info("===========" + list.size() + "");
        int currentYear = LocalDate.now().getYear();
        int resNum = 0;
        for (TTrainingMatrix matrix: list
             ) {
            int addFlag = 0;
            if ("每年一次".equals(matrix.getFrequency()) || "每年至少一次".equals(matrix.getFrequency())) {
                tr.setYear(String.valueOf(currentYear));
                tr.setItem(matrix.getItem());
                List<TTrainingbccRegular> regulars = tTrainingbccRegularService.selectTTrainingbccRegularList(tr);
                if (regulars.size() == 0) {
                    addFlag = 1;
                }
            }
            if ("每年两次".equals(matrix.getFrequency()) || "每年2次".equals(matrix.getFrequency())) {
                tr.setYear(String.valueOf(currentYear));
                tr.setItem(matrix.getItem());
                List<TTrainingbccRegular> regulars = tTrainingbccRegularService.selectTTrainingbccRegularList(tr);
                if (regulars.size() < 2) {
                    addFlag = 1;
                }
            }
            if ("每月一次".equals(matrix.getFrequency()) ) {
                tr.setYear(String.valueOf(currentYear));
                tr.setItem(matrix.getItem());
                List<TTrainingbccRegular> regulars0 = tTrainingbccRegularService.selectTTrainingbccRegularList(tr);
                tr.setPlanTrainingdate(new Date());
                List<TTrainingbccRegular> regulars = tTrainingbccRegularService.selectTTrainingbccRegularList(tr);
                if (regulars.size() == 0) {
                    addFlag = 1;
                }
                if (regulars0.size() >= LocalDate.now().getMonthValue()) { //数量够了不需要增加了
                    addFlag = 0;
                }
            }
            if (addFlag == 1) {
                TTrainingbccRegular tTrainingRegular = new TTrainingbccRegular();
                tTrainingRegular.setDeptId(matrix.getDeptId());
                tTrainingRegular.setActualpostId(matrix.getActualpostId());
                tTrainingRegular.setCourseCode(matrix.getCourseCode());
                tTrainingRegular.setItem(matrix.getItem());
                tTrainingRegular.setHour(matrix.getHour());
                tTrainingRegular.setInvolvedMoc("false");
                tTrainingRegular.setNotPlan("false");
                tTrainingRegular.setYear(String.valueOf(currentYear));

                int doInsert = tTrainingbccRegularService.insertTTrainingbccRegular(tTrainingRegular);

                logger.info("regular:" + tTrainingRegular);
                tTrainingRegular.setDeptId(103l); //bcc专用
                    //新增培训计划定期类
                    TTrainingbcc tTraining = new TTrainingbcc();
                    tTraining.setTrainingType("10");
                    tTraining.setYears(tTrainingRegular.getYear());
                    tTraining.setCourse(tTrainingRegular.getItem());
                    tTraining.setCourseid(tTrainingRegular.getCourseCode());
                    tTraining.setDuration(tTrainingRegular.getHour());
                    tTraining.setTrainer(tTrainingRegular.getLecturer());
                    tTraining.setPosition(tTrainingRegular.getActualpostId());
                    tTraining.setIsfinish(Long.parseLong("0"));
                    tTraining.setDeptId(tTrainingRegular.getDeptId());
                    tTraining.setRegularId(tTrainingRegular.getId());
                    trainingbccService.insertTTrainingbcc(tTraining);
                    Long trainingId = tTraining.getId();
                    //新增人员-装置级关系
                    // 参培岗位人员
                    if (tTrainingRegular.getActualpostId() != null) {
                        logger.info("参培岗位人员");
                        TStaffmgr staffmgr = new TStaffmgr();
                        staffmgr.setActualposts(tTrainingRegular.getActualpostId());
                        staffmgr.setDeptId(tTrainingRegular.getDeptId());
                        List<TStaffmgr> staffmgrs = tStaffmgrService.selectAllTStaffmgrList(staffmgr);
                        try {
                            //判断离职
                            if (!StringUtils.isEmpty(tTrainingRegular.getYear())) {
                                Iterator<TStaffmgr> iterator = staffmgrs.iterator();
                                while (iterator.hasNext()) {
                                    TStaffmgr t = iterator.next();
                                    if (t.getLeftDate() != null && t.getDelFlag() == 9){
                                        if (t.getLeftDate().getTime() - tTrainingRegular.getPlanTrainingdate().getTime() < 0l ) {
                                            logger.debug(t.getName() + "离职时间小于培训时间");
                                            iterator.remove();
                                        }
                                    }
                                }
                            }
                        }catch (Exception e) {
                            logger.error(e.toString());
                        }
                        for (TStaffmgr s : staffmgrs) {
                            TTrainingbccDevice tTrainingDevice = new TTrainingbccDevice();
                            tTrainingDevice.setStaffId(s.getStaffid());
                            tTrainingDevice.setRegularId(trainingId);
                            tTrainingDevice.setStartDate(tTrainingRegular.getPlanTrainingdate());
                            tTrainingDevice.setSupplementary("0");
                            trainingbccDeviceService.insertTTrainingbccDevice(tTrainingDevice);
                        }
                    }
                    //指定岗位人员
                    if (tTrainingRegular.getDesignatedStaff() != null) {
                        logger.info("指定岗位人员");
                        String[] designatedStaffs = tTrainingRegular.getDesignatedStaff().split(",");
                        for (String staffId : designatedStaffs) {
                            TTrainingbccDevice tTrainingDevice = new TTrainingbccDevice();
                            tTrainingDevice.setStaffId(staffId);
                            tTrainingDevice.setRegularId(trainingId);
                            tTrainingDevice.setStartDate(tTrainingRegular.getPlanTrainingdate());
                            tTrainingDevice.setSupplementary("0");
                            trainingbccDeviceService.insertTTrainingbccDevice(tTrainingDevice);
                        }
                    }
                    //涉及其他部门
                    if (tTrainingRegular.getInvolvedMoc().equals("true")){
                        logger.info("涉及MOC人员");
                        TStaffmgr staffmgrMoc = new TStaffmgr();
                        staffmgrMoc.setActualposts(tTrainingRegular.getDesignatedOther());
                        List<TStaffmgr> staffmgrsMoc = tStaffmgrService.selectAllTStaffmgrList(staffmgrMoc);
                        try {
                            //判断离职
                            if (!StringUtils.isEmpty(tTrainingRegular.getYear())) {
                                Iterator<TStaffmgr> iterator = staffmgrsMoc.iterator();
                                while (iterator.hasNext()) {
                                    TStaffmgr t = iterator.next();
                                    if (t.getLeftDate() != null && t.getDelFlag() == 9){
                                        if (t.getLeftDate().getTime() - tTrainingRegular.getPlanTrainingdate().getTime() > 0l ) {
                                            logger.debug(t.getName() + "离职时间小于培训时间");
                                            iterator.remove();
                                        }
                                    }
                                }
                            }
                        }catch (Exception e) {
                            logger.error(e.toString());
                        }
                        for (TStaffmgr s : staffmgrsMoc) {
                            TTrainingbccDevice tTrainingDevice = new TTrainingbccDevice();
                            tTrainingDevice.setStaffId(s.getStaffid());
                            tTrainingDevice.setRegularId(trainingId);
                            tTrainingDevice.setStartDate(tTrainingRegular.getPlanTrainingdate());
                            tTrainingDevice.setSupplementary("0");
                            trainingbccDeviceService.insertTTrainingbccDevice(tTrainingDevice);
                        }
                    }
                resNum ++;
            }
        }
        return AjaxResult.success("成功添加" + resNum + "条培训");
    }

    /**
     * 修改装置培训计划
     */
    @PreAuthorize("@ss.hasPermi('training:bccregular:edit')")
    @Log(title = "装置培训计划", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TTrainingbccRegular tTrainingbccRegular)
    {
        return toAjax(tTrainingbccRegularService.updateTTrainingbccRegular(tTrainingbccRegular));
    }

    /**
     * 删除装置培训计划
     */
    @PreAuthorize("@ss.hasPermi('training:bccregular:remove')")
    @Log(title = "装置培训计划", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tTrainingbccRegularService.deleteTTrainingbccRegularByIds(ids));
    }
}
