package com.ruoyi.project.training.controller;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;

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.TTraining;
import com.ruoyi.project.training.domain.TTrainingDevice;
import com.ruoyi.project.training.service.ITTrainingDeviceService;
import com.ruoyi.project.training.service.ITTrainingService;
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.project.training.domain.TTrainingRegular;
import com.ruoyi.project.training.service.ITTrainingRegularService;
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 ruoyi
 * @date 2021-06-22
 */
@RestController
@RequestMapping("/training/regular")
public class TTrainingRegularController extends BaseController
{
    @Autowired
    private ITTrainingRegularService tTrainingRegularService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;

    @Autowired
    private ITStaffmgrService tStaffmgrService;

    @Autowired
    private ITTrainingDeviceService tTrainingDeviceService;

    @Autowired
    private ITTrainingService tTrainingService;

    /**
     * 查询装置培训计划列表
     */
    @PreAuthorize("@ss.hasPermi('training:regular:list')")
    @GetMapping("/list")
    public TableDataInfo list(TTrainingRegular tTrainingRegular)
    {
        startPage();
        List<TTrainingRegular> list = tTrainingRegularService.selectTTrainingRegularList(tTrainingRegular);
        List<SysDictData> actualpost = iSysDictTypeService.selectDictDataByType("ACTUALPOST");
        for (TTrainingRegular 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:regular:export')")
    @Log(title = "装置培训计划", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TTrainingRegular tTrainingRegular)
    {
        List<TTrainingRegular> list = tTrainingRegularService.selectTTrainingRegularList(tTrainingRegular);
        ExcelUtil<TTrainingRegular> util = new ExcelUtil<TTrainingRegular>(TTrainingRegular.class);
        return util.exportExcel(list, "regular");
    }

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

    /**
     * 新增装置培训计划
     */
    @PreAuthorize("@ss.hasPermi('training:regular:add')")
    @Log(title = "装置培训计划", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TTrainingRegular tTrainingRegular)
    {
        int doInsert = tTrainingRegularService.insertTTrainingRegular(tTrainingRegular);
        logger.info("regular:" + tTrainingRegular);
        //如果确定计划日期新增关联内容
        if (tTrainingRegular.getNotPlan().equals("true")) {
            //新增培训计划定期类
            TTraining tTraining = new TTraining();
            tTraining.setTrainingType("10");
            tTraining.setYear(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());
            tTrainingService.insertTTraining(tTraining);
            Long trainingId = tTraining.getId();
            //新增人员-装置级关系
            // 参培岗位人员
            if (tTrainingRegular.getActualpostId() != null) {
                logger.info("参培岗位人员");
                TStaffmgr staffmgr = new TStaffmgr();
                staffmgr.setActualposts(tTrainingRegular.getActualpostId());
                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) {
                    TTrainingDevice tTrainingDevice = new TTrainingDevice();
                    tTrainingDevice.setStaffId(s.getStaffid());
                    tTrainingDevice.setRegularId(trainingId);
                    tTrainingDevice.setStartDate(tTrainingRegular.getPlanTrainingdate());
                    tTrainingDevice.setSupplementary("0");
                    tTrainingDeviceService.insertTTrainingDevice(tTrainingDevice);
                }
            }
            //指定岗位人员
            if (tTrainingRegular.getDesignatedStaff() != null) {
                logger.info("指定岗位人员");
                String[] designatedStaffs = tTrainingRegular.getDesignatedStaff().split(",");
                for (String staffId : designatedStaffs) {
                    TTrainingDevice tTrainingDevice = new TTrainingDevice();
                    tTrainingDevice.setStaffId(staffId);
                    tTrainingDevice.setRegularId(trainingId);
                    tTrainingDevice.setStartDate(tTrainingRegular.getPlanTrainingdate());
                    tTrainingDevice.setSupplementary("0");
                    tTrainingDeviceService.insertTTrainingDevice(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) {
                    TTrainingDevice tTrainingDevice = new TTrainingDevice();
                    tTrainingDevice.setStaffId(s.getStaffid());
                    tTrainingDevice.setRegularId(trainingId);
                    tTrainingDevice.setStartDate(tTrainingRegular.getPlanTrainingdate());
                    tTrainingDevice.setSupplementary("0");
                    tTrainingDeviceService.insertTTrainingDevice(tTrainingDevice);
                }
            }
        }
        return toAjax(doInsert);
    }

    /**
     * 修改装置培训计划
     */
    @PreAuthorize("@ss.hasPermi('training:regular:edit')")
    @Log(title = "装置培训计划", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TTrainingRegular tTrainingRegular)
    {
        //如果确定计划日期新增关联内容
        if (tTrainingRegular.getNotPlan().equals("true")) {
            //查找跟这条培训计划相关联的装置级培训记录  修改其培训的年份，课程名称和课程代码
            TTraining t=  tTrainingService.selectTTrainingByRegularId(tTrainingRegular.getId());
            if(null == t) {
                //新增培训计划定期类
                TTraining tTraining = new TTraining();
                tTraining.setTrainingType("10");
                tTraining.setYear(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());
                tTrainingService.insertTTraining(tTraining);
                t = tTraining;
            }
            t.setCourse(tTrainingRegular.getItem());
            t.setCourseid(tTrainingRegular.getCourseCode());
            t.setYear(tTrainingRegular.getYear());
            t.setDelFlag(tTrainingRegular.getDelFlag());
            int result=   tTrainingService.updateTTraining(t);
            TTrainingRegular oldRegular = tTrainingRegularService.selectTTrainingRegularById(tTrainingRegular.getId());
            int i = 0;
            if (oldRegular.getActualpostId() != null) {
                if (!oldRegular.getActualpostId().equals(tTrainingRegular.getActualpostId())) {
                    i = 1;
                }
            }else {
                if (tTrainingRegular.getActualpostId() != null) {
                    i = 1;
                }
            }
            if (oldRegular.getDesignatedStaff() != null) {
                if (!oldRegular.getDesignatedStaff().equals(tTrainingRegular.getDesignatedStaff())) {
                    i = 1;
                }
            }else {
                if (tTrainingRegular.getDesignatedStaff() != null) {
                    i = 1;
                }
            }
            if (!oldRegular.getInvolvedMoc().equals(tTrainingRegular.getInvolvedMoc())) {
                i = 1;
            }
            if (i == 1) {
                logger.info("修改了需参培人员名单");

                TTraining training = tTrainingService.selectTTrainingByRegularId(tTrainingRegular.getId());
                training.setPosition(tTrainingRegular.getActualpostId());
                tTrainingService.updateTTraining(training);

                TStaffmgr staffmgrMoc = new TStaffmgr();
                staffmgrMoc.setActualposts(tTrainingRegular.getDesignatedOther());
                List<TStaffmgr> staffmgrsMoc = tStaffmgrService.selectTStaffmgrList(staffmgrMoc);
                try {
                    //判断离职
                    if (!StringUtils.isEmpty(tTrainingRegular.getYear())) {
                        Iterator<TStaffmgr> iterator = staffmgrsMoc.iterator();
                        while (iterator.hasNext()) {
                            TStaffmgr staffmgr2 = iterator.next();
                            if (staffmgr2.getLeftDate() != null && t.getDelFlag() == 9){
                                if (staffmgr2.getLeftDate().getTime() - tTrainingRegular.getPlanTrainingdate().getTime() < 0l ) {
                                    logger.debug(staffmgr2.getName() + "离职时间小于培训时间");
                                    iterator.remove();
                                }
                            }
                        }
                    }
                }catch (Exception e) {
                    logger.error(e.toString());
                }
                //如果存在条目
                if (oldRegular.getActualpostId() != null || oldRegular.getDesignatedStaff() != null || oldRegular.getInvolvedMoc().equals("true")) {
                    TTrainingDevice tTrainingDevice = new TTrainingDevice();
                    tTrainingDevice.setRegularId(training.getId());
                    tTrainingDeviceService.deleteTTrainingDevice(tTrainingDevice);
                }
                //参培岗位人员
                if (tTrainingRegular.getActualpostId() != null) {
                    logger.info("参培岗位人员");
                    TStaffmgr staffmgr = new TStaffmgr();
                    staffmgr.setActualposts(tTrainingRegular.getActualpostId());
                    List<TStaffmgr> staffmgrs = tStaffmgrService.selectAllTStaffmgrList(staffmgr);
                    try {
                        //判断离职
                        if (!StringUtils.isEmpty(tTrainingRegular.getYear())) {
                            Iterator<TStaffmgr> iterator = staffmgrs.iterator();
                            while (iterator.hasNext()) {
                                TStaffmgr staffmgr1 = iterator.next();
                                if (staffmgr1.getLeftDate() != null && t.getDelFlag() == 9){
                                    if (staffmgr1.getLeftDate().getTime() - tTrainingRegular.getPlanTrainingdate().getTime() < 0l ) {
                                        logger.debug(staffmgr1.getName() + "离职时间小于培训时间");
                                        iterator.remove();
                                    }
                                }
                            }
                        }
                    }catch (Exception e) {
                        logger.error(e.toString());
                    }
                    for (TStaffmgr s : staffmgrs) {
                        TTrainingDevice tTrainingDevice = new TTrainingDevice();
                        tTrainingDevice.setStaffId(s.getStaffid());
                        tTrainingDevice.setRegularId(training.getId());
                        tTrainingDevice.setSupplementary("0");
                        tTrainingDeviceService.insertTTrainingDevice(tTrainingDevice);
                    }
                }
                //指定岗位人员
                if (tTrainingRegular.getDesignatedStaff() != null) {
                    logger.info("指定岗位人员");
                    String[] designatedStaffs = tTrainingRegular.getDesignatedStaff().split(",");
                    for (String staffId : designatedStaffs) {
                        TTrainingDevice tTrainingDevice = new TTrainingDevice();
                        tTrainingDevice.setStaffId(staffId);
                        tTrainingDevice.setRegularId(training.getId());
                        tTrainingDevice.setSupplementary("0");
                        tTrainingDeviceService.insertTTrainingDevice(tTrainingDevice);
                    }
                }
                //涉及MOC人员
                if (tTrainingRegular.getInvolvedMoc().equals("true")){
                    logger.info("涉及MOC人员");
                    for (TStaffmgr s : staffmgrsMoc) {
                        TTrainingDevice tTrainingDevice = new TTrainingDevice();
                        tTrainingDevice.setStaffId(s.getStaffid());
                        tTrainingDevice.setRegularId(training.getId());
                        tTrainingDevice.setSupplementary("0");
                        tTrainingDeviceService.insertTTrainingDevice(tTrainingDevice);
                    }
                }
            }else {
                logger.info("没有修改参培人员名单");
            }
        }
        return toAjax(tTrainingRegularService.updateTTrainingRegular(tTrainingRegular));
    }

    /**
     * 删除装置培训计划
     */
    @PreAuthorize("@ss.hasPermi('training:regular:remove')")
    @Log(title = "装置培训计划", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        for (Long id : ids) {
            TTraining training = tTrainingService.selectTTrainingByRegularId(id); //查询培训跟踪计划
            if (training == null) {
                continue;
            }
            tTrainingService.deleteTTrainingById(training.getId());
            TTrainingRegular regular = tTrainingRegularService.selectTTrainingRegularById(id);
            if (regular.getActualpostId() != null || regular.getDesignatedStaff() != null || regular.getInvolvedMoc().equals("true")) {
                TTrainingDevice tTrainingDevice = new TTrainingDevice();
                tTrainingDevice.setRegularId(training.getId());
                tTrainingDeviceService.deleteTTrainingDevice(tTrainingDevice);
            }
        }
        return toAjax(tTrainingRegularService.deleteTTrainingRegularByIds(ids));
    }
}
