package com.ruoyi.project.plant.controller;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.file.ExcelUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
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.config.RuoYiConfig;
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.common.domain.DataEntity;
import com.ruoyi.project.plant.domain.TStaffmgr;
import com.ruoyi.project.plant.mapper.TStaffmgrMapper;
import com.ruoyi.project.plant.service.ITStaffmgrService;
import com.ruoyi.project.system.domain.SysDept;
import com.ruoyi.project.system.domain.SysDictData;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysDeptService;
import com.ruoyi.project.system.service.ISysDictTypeService;
import com.ruoyi.project.system.service.ISysUserService;
import com.ruoyi.project.training.domain.*;
import com.ruoyi.project.training.service.*;
import com.ruoyi.project.training.spec.service.ITStPlanService;
import com.ruoyi.project.training.spec.service.ITStSuccessorService;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 人员管理Controller
 *
 * @author ruoyi
 * @date 2020-11-25
 */
@RestController
@RequestMapping("/plant/staffmgr")
public class TStaffmgrController extends BaseController {
    @Autowired
    private ITStaffmgrService tStaffmgrService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;

    @Resource
    private TStaffmgrMapper tStaffmgrMapper;

    @Autowired
    private ITTrainingrecordsService tTrainingrecordsService;

    @Autowired
    private ITTrainingParticipantsService tTrainingParticipantsService;

    @Autowired
    private ITWorklicenseService tWorklicenseService;

    @Autowired
    private ITTrainingRegularService tTrainingRegularService;

    @Autowired
    private ITTrainingDeviceService tTrainingDeviceService;

    @Autowired
    private ITTrainingService tTrainingService;

    @Autowired
    private ITTrainingNonService tTrainingNonService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ITStSuccessorService stSuccessorService;

    @Autowired
    private ITStPlanService tStPlanService;

    /**
     * 获取SAI整改负责人列表
     */
    @PreAuthorize("@ss.hasPermi('plant:staffmgr:list')")
    @GetMapping("/listSaiExecutors")
    public AjaxResult listSaiExecutors() {
        return AjaxResult.success(tStaffmgrService.selectSaiExecutors());
    }

    /**
     * 获取SAI验证人列表
     */
    @PreAuthorize("@ss.hasPermi('plant:staffmgr:list')")
    @GetMapping("/listSaiInspectors")
    public AjaxResult listSaiInspectors() {
        return AjaxResult.success(tStaffmgrService.selectSaiInspectors());
    }

    /**
     * 获取人员管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('plant:staffmgr:query')")
    @GetMapping(value = "/loginStaffInfo")
    public AjaxResult getLoginStaffInfo() {
        Long userId = getUserId();
        SysUser sysUser = sysUserService.selectUserById(userId);
        String staffId = sysUser.getStaffId();
        TStaffmgr staffmgr = tStaffmgrService.selectTStaffmgrByStaffId(staffId);
        if (staffmgr != null) {
            staffmgr.setUserId(userId.toString());
            if (staffmgr.getActualpost().contains("14") || staffmgr.getActualpost().contains("12")) {
                staffmgr.setChecker(true);
            }
        }
        return AjaxResult.success(staffmgr);
    }

    /**
     * 获取当前用户id
     *
     * @return 当前用户id
     */
    @PreAuthorize("@ss.hasPermi('plant:staffmgr:query')")
    @GetMapping("/getStaffId")
    public AjaxResult getStaffId() {
        Long userId = getUserId();
        SysUser sysUser = sysUserService.selectUserById(userId);
        String staffId = sysUser.getStaffId();
        return AjaxResult.success("操作成功", staffId);
    }

    /**
     * 判断当前用户是否为导师
     *
     * @return 是否为导师
     */
    @PreAuthorize("@ss.hasPermi('plant:staffmgr:query')")
    @GetMapping("/isMentor")
    public AjaxResult isMentor() {
        // 是否为导师
        boolean isMentor = false;
        ServletUtils.getParameter("sexs");
        // 导师清单
        List<TStaffmgr> tStaffmgrs = tStaffmgrService.selectMentorList(null);
        Long userId = getUserId();
        SysUser sysUser = sysUserService.selectUserById(userId);
        // 当前用户id
        String staffId = sysUser.getStaffId();
        for (TStaffmgr staffmgr : tStaffmgrs) {
            // 导师id=当前用户id
            if (staffmgr.getStaffid().equals(staffId)) {
                isMentor = true;
            }
        }
        return AjaxResult.success("操作成功", isMentor);
    }

    /**
     * 查询导师下拉列表
     */
    @PreAuthorize("@ss.hasPermi('plant:staffmgr:list')")
    @GetMapping("/listMentors")
    public AjaxResult listMentors(TStaffmgr tStaffmgr) {
        ServletUtils.getParameter("sexs");
        return AjaxResult.success(tStaffmgrService.selectMentorList(tStaffmgr));
    }

    /**
     * 查询人员管理列表--包含离职人员
     */
    @GetMapping("/listAll")
    public TableDataInfo listAll(TStaffmgr tStaffmgr) {
        ServletUtils.getParameter("sexs");
        startPage();
        logger.info("staffmgr:" + tStaffmgr);
        List<TStaffmgr> list = tStaffmgrMapper.selectTStaffmgrListAll(tStaffmgr);
        return getDataTable(list);
    }

    /**
     * 查询人员管理列表
     */
    @PreAuthorize("@ss.hasPermi('plant:staffmgr:list')")
    @GetMapping("/list")
    public TableDataInfo list(TStaffmgr tStaffmgr) {
        ServletUtils.getParameter("sexs");
        startPage();
        logger.info("staffmgr:" + tStaffmgr);
        List<TStaffmgr> list = tStaffmgrService.selectTStaffmgrList(tStaffmgr);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('plant:staffmgr:list')")
    @GetMapping("/averageAge")
    public AjaxResult averageAge(TStaffmgr tStaffmgr) {
        int sumAge = 0;
        Calendar calendar = Calendar.getInstance();
        List<TStaffmgr> tStaffmgrs = tStaffmgrService.selectTStaffmgrList(tStaffmgr);
        for (TStaffmgr staffmgr : tStaffmgrs) {
            if (staffmgr.getBirthday() != null) {
                calendar.setTime(staffmgr.getBirthday());
                int birthYear = calendar.get(Calendar.YEAR);
                calendar.setTime(new Date());
                int currentYear = calendar.get(Calendar.YEAR);
                sumAge += (currentYear - birthYear);
            }
        }
        int result = sumAge / tStaffmgrs.size();
        return AjaxResult.success(result);
    }


    /**
     * 通过部门查询人员列表
     */
    @GetMapping("/listByDeptAndTeam")
    public TableDataInfo listByDeptAndTeam(TStaffmgr tStaffmgr) {
        startPage();
        List<TStaffmgr> list = tStaffmgrService.selectTStaffmgrListByDeptAndTeam(tStaffmgr);
        return getDataTable(list);
    }

    /**
     * 查询人员管理列表（包含离职）
     */
    @PreAuthorize("@ss.hasPermi('plant:staffmgr:list')")
    @GetMapping("/getAllList")
    public TableDataInfo getAllList(TStaffmgr tStaffmgr) {
        ServletUtils.getParameter("sexs");
        startPage();
        logger.info("staffmgr:" + tStaffmgr);
        List<TStaffmgr> list = tStaffmgrService.selectAllTStaffmgrList(tStaffmgr);
        try {
            //判断离职
            if (!StringUtils.isEmpty(tStaffmgr.getLeftYear())) {
                Iterator<TStaffmgr> iterator = list.iterator();
                while (iterator.hasNext()) {
                    TStaffmgr t = iterator.next();
                    if (t.getLeftDate() != null && t.getDelFlag() == 9) {
                        Calendar cal = Calendar.getInstance();
                        cal.setTime(t.getLeftDate());
                        Integer year = cal.get(Calendar.YEAR);//获取年
                        if (year < Integer.parseInt(tStaffmgr.getLeftYear())) {
                            logger.debug(t.getName() + "离职年份小于数据");
                            iterator.remove();
                        }
                    }
                }
            }

            // 使用一个 HashMap 来存储去重后的结果
            Map<String, TStaffmgr> map = new HashMap<>();

            // 遍历列表并将每个 TStaffmgr 实例放入 Map 中
            for (TStaffmgr staffmgr : list) {
                map.put(staffmgr.getStaffid(), staffmgr);
            }
            // 从 Map 中提取去重后的结果
            list = new ArrayList<>(map.values());
        } catch (Exception e) {
            logger.error(e.toString());
        }


        return getDataTable(list);
    }

    /**
     * 查询人员公司级培训时间列表
     */
    @PreAuthorize("@ss.hasPermi('plant:staffmgr:list')")
    @GetMapping("/selectTime")
    public TableDataInfo selectTime(TStaffmgr tStaffmgr) {
        startPage();
        List<TStaffmgr> list = tStaffmgrService.selectRecordList(tStaffmgr);
        try {
            //判断离职
            if (!StringUtils.isEmpty(tStaffmgr.getLeftYear())) {
                Iterator<TStaffmgr> iterator = list.iterator();
                while (iterator.hasNext()) {
                    TStaffmgr t = iterator.next();
                    if (t.getLeftDate() != null && t.getDelFlag() == 9) {
                        Calendar cal = Calendar.getInstance();
                        cal.setTime(t.getLeftDate());
                        Integer year = cal.get(Calendar.YEAR);//获取年
                        if (year < Integer.parseInt(tStaffmgr.getLeftYear())) {
                            logger.debug(t.getName() + "离职年份小于数据");
                            iterator.remove();
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.toString());
        }
        logger.info("selectTime:" + list.size());
        List<TTrainingParticipants> tTrainingParticipants = tTrainingParticipantsService.selectTTrainingParticipantsList(new TTrainingParticipants());

        //线程池
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        final CountDownLatch latch = new CountDownLatch(list.size()); //相同线程数量的计数
        for (int i = 0; i < list.size(); i++) {
            int finalI = i;
            executorService.execute(() -> {
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                    double time = 0;
                    for (TTrainingParticipants t : tTrainingParticipants) {
                        if (t.getStaffId().equals(list.get(finalI).getStaffid())) {
                            if (t.getStartDate() != null) {
                                if (sdf.format(t.getStartDate()).equals(sdf.format(new Date()))) {
                                    if (t.getTrainingDuration() != null) {
                                        try {
                                            time = time + Double.parseDouble(t.getTrainingDuration());
                                        } catch (Exception e) {
                                            logger.error("转double出错", JSON.toJSONString(e));
                                        }

                                    }
                                }
                            }
                        }
                    }
                    list.get(finalI).setTrainingTime(String.valueOf(time));
                } catch (Exception e) {
                    logger.error("e:", e);
                }finally {
                    latch.countDown(); //线程计数
                }
            });
        }
        try {
            latch.await(); //线程计数完毕后继续执行
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executorService.shutdown();
        return getDataTable(list);
    }

    /**
     * 查询人员管理列表
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('plant:staffmgr:list')")
    @GetMapping("/ogzList")
    public List<TStaffmgr> ogzList(TStaffmgr tStaffmgr) {
        List<TStaffmgr> list = tStaffmgrService.selectTStaffmgrList(tStaffmgr);
        return list;
    }

    /**
     * 上级领导字段查询人员管理列表
     */
    @PreAuthorize("@ss.hasPermi('plant:staffmgr:list')")
    @GetMapping("/pIdList")
    public AjaxResult pIdList(TStaffmgr tStaffmgr) {
        List<TStaffmgr> list = tStaffmgrService.selectTStaffmgrList(tStaffmgr);
        return AjaxResult.success(list);
    }

    /**
     * 查询离职人员管理列表
     */
    @PreAuthorize("@ss.hasPermi('plant:staffmgr:list')")
    @GetMapping("/leftList")
    public TableDataInfo leftList(TStaffmgr tStaffmgr) {
        startPage();
        List<TStaffmgr> list = tStaffmgrService.selectLeftTStaffmgrList(tStaffmgr);
        return getDataTable(list);
    }

    //学历统计
    @GetMapping("/eduData")
    public List<DataEntity> eduData(TStaffmgr param) {
        List<DataEntity> list = tStaffmgrMapper.selectEduData(param);
        List<SysDictData> education = iSysDictTypeService.selectDictDataByType("EDUCATION");
        for (DataEntity d : list
        ) {
            for (SysDictData s : education
            ) {
                if (StringUtils.isBlank(d.getDataName())) {
                    d.setDataName("未知");
                    break;
                }
                if (s.getDictValue().equals(d.getDataName())) {
                    d.setDataName(s.getDictLabel());
                    break;
                }
            }
        }
        return list;
    }

    //年龄统计
    @GetMapping("/ageData")
    public List<DataEntity> ageData(TStaffmgr param) {
        List<DataEntity> list = tStaffmgrMapper.selectAgeData(param);
        List<SysDictData> education = iSysDictTypeService.selectDictDataByType("EDUCATION");
        for (DataEntity d : list
        ) {
            for (SysDictData s : education
            ) {
                if (StringUtils.isBlank(d.getDataName())) {
                    d.setDataName("未知");
                    break;
                }
                if (s.getDictValue().equals(d.getDataName())) {
                    d.setDataName(s.getDictLabel());
                    break;
                }
            }
        }
        return list;
    }

    //英语统计
    @GetMapping("/engData")
    public List<DataEntity> engData(TStaffmgr param) {
        List<DataEntity> list = tStaffmgrMapper.selectEngData(param);
        List<SysDictData> englishability = iSysDictTypeService.selectDictDataByType("ENGLISHABILITY");
        for (DataEntity d : list
        ) {
            for (SysDictData s : englishability
            ) {
                if (StringUtils.isBlank(d.getDataName())) {
                    d.setDataName("未知");
                    break;
                }
                if (s.getDictValue().equals(d.getDataName())) {
                    d.setDataName(s.getDictLabel());
                    break;
                }
            }
        }
        return list;
    }

    //班值统计
    @GetMapping("/teamData")
    public List<DataEntity> teamData(TStaffmgr param) {
        List<DataEntity> list = tStaffmgrMapper.selectTeamData(param);
        List<SysDictData> englishability = iSysDictTypeService.selectDictDataByType("TEAM_DIVIDE");
        for (DataEntity d : list
        ) {
            for (SysDictData s : englishability
            ) {
                if (StringUtils.isBlank(d.getDataName())) {
                    d.setDataName("未知");
                    break;
                }
                if (s.getDictValue().equals(d.getDataName())) {
                    d.setDataName(s.getDictLabel());
                    break;
                }
            }
        }
        return list;
    }

    /**
     * 导出人员管理列表
     */
    @PreAuthorize("@ss.hasPermi('plant:staffmgr:export')")
    @Log(title = "人员管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TStaffmgr tStaffmgr) {
        List<TStaffmgr> list = tStaffmgrService.selectTStaffmgrList(tStaffmgr);
        ExcelUtil<TStaffmgr> util = new ExcelUtil<TStaffmgr>(TStaffmgr.class);
        return util.exportExcel(list, "staffmgr");
    }

    /**
     * 获取人员管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('plant:staffmgr:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        TStaffmgr staffmgr = tStaffmgrService.selectTStaffmgrById(id);
        return AjaxResult.success(staffmgr);
    }

    @PreAuthorize("@ss.hasPermi('plant:staffmgr:query')")
    @GetMapping(value = "/staffid/{id}")
    public AjaxResult getInfoByStaffId(@PathVariable("id") String id) {
        TStaffmgr staffmgr = tStaffmgrService.selectTStaffmgrByStaffId(id);
        return AjaxResult.success(staffmgr);
    }

    /**
     * 为参培人员名单获取人员管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('plant:staffmgr:query')")
    @GetMapping("/byStaffId/{staffIds}")
    public AjaxResult byStaffId(@PathVariable String[] staffIds) {
        List<TStaffmgr> staffmgrs = new ArrayList<TStaffmgr>();
        for (int i = 0; i < staffIds.length; i++) {
            TStaffmgr staffmgr = tStaffmgrService.selectTStaffmgrByStaffId(staffIds[i]);
            staffmgrs.add(staffmgr);
        }
        return AjaxResult.success(staffmgrs);
    }

    /**
     * 新增人员管理
     */
    @PreAuthorize("@ss.hasPermi('plant:staffmgr:add')")
    @Log(title = "人员管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TStaffmgr tStaffmgr) {
        //判断是否重复员工
        TStaffmgr tStaffmgr1 = tStaffmgrMapper.selectTStaffmgrByStaffId(tStaffmgr.getStaffid());
        if (tStaffmgr1 != null) {
            return AjaxResult.error("员工号已存在");
        }

        int insertResult = tStaffmgrService.insertTStaffmgr(tStaffmgr);
        tStaffmgr.setCreaterCode(getUserId().toString());
        if (tStaffmgr.getUnit().equals("10") || tStaffmgr.getUnit().equals("18") || tStaffmgr.getUnit().equals("20") || tStaffmgr.getUnit().equals("30")) {
            TTrainingrecords tTrainingrecords = new TTrainingrecords();
            tTrainingrecords.setStaffId(tStaffmgr.getId());
            tTrainingrecords.setPlantCode(tStaffmgr.getPlantCode());
            tTrainingrecords.setName(tStaffmgr.getName());
            tTrainingrecords.setEmployeeid(tStaffmgr.getStaffid());
            tTrainingrecords.setClasses(tStaffmgr.getTeam());
            tTrainingrecords.setDeptId(tStaffmgr.getDeptId());
            tTrainingrecordsService.insertTTrainingrecords(tTrainingrecords);
        }
        if (!tStaffmgr.getTeam().equals("18")) {
            TWorklicense tWorklicense = new TWorklicense();
            tWorklicense.setPlantCode(tStaffmgr.getPlantCode());
            tWorklicense.setClasses(tStaffmgr.getTeam());
            tWorklicense.setName(tStaffmgr.getName());
            tWorklicense.setEmployeeid(tStaffmgr.getStaffid());
            tWorklicense.setPost(tStaffmgr.getActualpost());
            tWorklicense.setDeptId(tStaffmgr.getDeptId());
            tWorklicenseService.insertTWorklicense(tWorklicense);
        }
        if (tStaffmgr.getUnit().equals("10")) {
            SimpleDateFormat sdfYear = new SimpleDateFormat("yyyy");
            TTrainingRegular regular = new TTrainingRegular();
            regular.setYear(sdfYear.format(new Date()));
            List<TTrainingRegular> tTrainingRegulars = tTrainingRegularService.selectTTrainingRegularList(regular);
            for (TTrainingRegular r : tTrainingRegulars) {
                if (r.getNotPlan().equals("true")) {
                    String[] posts = r.getActualpostId().split(",");
                    for (String post : posts) {
                        if (post.equals(tStaffmgr.getActualpost())) {
                            TTraining training = tTrainingService.selectTTrainingByRegularId(r.getId());
                            if (training.getStartDate() == null) {
                                TTrainingDevice tTrainingDevice = new TTrainingDevice();
                                tTrainingDevice.setStaffId(tStaffmgr.getStaffid());
                                tTrainingDevice.setRegularId(training.getId());
                                tTrainingDevice.setStartDate(r.getPlanTrainingdate());
                                tTrainingDevice.setSupplementary("0");
                                tTrainingDeviceService.insertTTrainingDevice(tTrainingDevice);
                            } else {
                                TTrainingDevice tTrainingDevice = new TTrainingDevice();
                                tTrainingDevice.setStaffId(tStaffmgr.getStaffid());
                                tTrainingDevice.setRegularId(training.getId());
                                tTrainingDevice.setSupplementary("2");
                                tTrainingDeviceService.insertTTrainingDevice(tTrainingDevice);
                            }
                            TTrainingNon tTrainingNon = new TTrainingNon();
                            tTrainingNon.setStaffId(tStaffmgr.getStaffid());
                            tTrainingNon.setTrainingId(training.getId());
                            tTrainingNon.setIsNew("1");
                            tTrainingNonService.insertTTrainingNon(tTrainingNon);
                        }
                    }
                }
            }
        }
        return toAjax(insertResult);
    }

    /**
     * 修改人员管理
     */
    @PreAuthorize("@ss.hasPermi('plant:staffmgr:edit')")
    @Log(title = "人员管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TStaffmgr tStaffmgr) {
        //判断是否重复员工
        TStaffmgr tStaffmgr1 = tStaffmgrMapper.selectTStaffmgrByStaffId(tStaffmgr.getStaffid());
        if (tStaffmgr1 != null) {
            if (!tStaffmgr1.getId().equals(tStaffmgr.getId())) {
                return AjaxResult.error("员工号已存在");
            }
        }
        tStaffmgr.setPhoto(null);
        tStaffmgr.setUpdaterCode(getUserId().toString());
        tStaffmgr.setUpdatedate(new Date());
        TStaffmgr oldStaffmgr = tStaffmgrService.selectTStaffmgrById(tStaffmgr.getId());
        if (tStaffmgr.getUnit().equals("10") || tStaffmgr.getUnit().equals("18")) {
            //部门为CBP/C或CBP的人员
            TTrainingrecords tTrainingrecords = tTrainingrecordsService.selectTTrainingrecordsBystaffId(tStaffmgr.getId());
            if (tTrainingrecords != null) {
                tTrainingrecords.setPlantCode(tStaffmgr.getPlantCode());
                tTrainingrecords.setName(tStaffmgr.getName());
                tTrainingrecords.setEmployeeid(tStaffmgr.getStaffid());
                tTrainingrecords.setClasses(tStaffmgr.getTeam());
                tTrainingrecords.setDeptId(tStaffmgr.getDeptId());
                tTrainingrecordsService.updateTTrainingrecords(tTrainingrecords);
            }
        }
        if (!tStaffmgr.getTeam().equals("18")) {
            //非W班组人员
            TWorklicense tWorklicense = tWorklicenseService.selectTWorklicenseByEmployeeid(tStaffmgr.getStaffid());
            if (tWorklicense == null) {
                TWorklicense newWorklicense = new TWorklicense();
                newWorklicense.setPlantCode(tStaffmgr.getPlantCode());
                newWorklicense.setClasses(tStaffmgr.getTeam());
                newWorklicense.setName(tStaffmgr.getName());
                newWorklicense.setEmployeeid(tStaffmgr.getStaffid());
                newWorklicense.setPost(tStaffmgr.getActualpost());
                newWorklicense.setDeptId(tStaffmgr.getDeptId());
                tWorklicenseService.insertTWorklicense(newWorklicense);
            } else {
                tWorklicense.setPlantCode(tStaffmgr.getPlantCode());
                tWorklicense.setClasses(tStaffmgr.getTeam());
                tWorklicense.setName(tStaffmgr.getName());
                tWorklicense.setEmployeeid(tStaffmgr.getStaffid());
                tWorklicense.setPost(tStaffmgr.getActualpost());
                tWorklicense.setDeptId(tStaffmgr.getDeptId());
                tWorklicenseService.updateTWorklicense(tWorklicense);
            }
        }
        return toAjax(tStaffmgrService.updateTStaffmgr(tStaffmgr));
    }

    /**
     * 删除人员管理
     */
    @PreAuthorize("@ss.hasPermi('plant:staffmgr:remove')")
    @Log(title = "人员管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        for (int i = 0; i < ids.length; i++) {
            TTrainingrecords tTrainingrecords = tTrainingrecordsService.selectTTrainingrecordsBystaffId(ids[i]);
            if (tTrainingrecords != null) {
                tTrainingrecords.setDelFlag(2l);
                tTrainingrecordsService.updateTTrainingrecords(tTrainingrecords);
            }
            TStaffmgr staffmgr = tStaffmgrService.selectTStaffmgrById(ids[i]);
            TTrainingDevice device = new TTrainingDevice();
            device.setStaffId(staffmgr.getStaffid());
            List<TTrainingDevice> devices = tTrainingDeviceService.selectTTrainingDeviceList(device);
            if (devices.size() != 0) {
                Long[] devicesIds = new Long[devices.size()];
                for (int m = 0; m < devices.size(); m++) {
                    devicesIds[m] = devices.get(m).getId();
                }
                tTrainingDeviceService.deleteTTrainingDeviceByIds(devicesIds);
            }
            TTrainingNon non = new TTrainingNon();
            non.setStaffId(staffmgr.getStaffid());
            List<TTrainingNon> nons = tTrainingNonService.selectTTrainingNonList(non);
            if (nons.size() != 0) {
                Long[] nonIds = new Long[nons.size()];
                for (int n = 0; n < nons.size(); n++) {
                    nonIds[n] = nons.get(n).getId();
                }
                tTrainingNonService.deleteTTrainingNonByIds(nonIds);
            }
        }
        return toAjax(tStaffmgrService.deleteTStaffmgrByIds(ids));
    }

    /**
     * 删除离职人员
     */
    @PreAuthorize("@ss.hasPermi('plant:staffmgr:remove')")
    @Log(title = "人员管理", businessType = BusinessType.DELETE)
    @GetMapping("/left/{id}")
    public AjaxResult removeLeft(@PathVariable Long id) {
        TTrainingrecords tTrainingrecords = tTrainingrecordsService.selectTTrainingrecordsBystaffId(id);
        if (tTrainingrecords != null) {
            tTrainingrecords.setDelFlag(9l);
            tTrainingrecordsService.updateTTrainingrecords(tTrainingrecords);
        }
        // 王子文 2022年6月27日 添加
        // 离职时修改继任者清单状态、培养计划状态
        Long staffId = Long.parseLong(tStaffmgrService.selectTStaffmgrById(id).getStaffid());
        stSuccessorService.updateStateByStaffId(staffId);
        tStPlanService.updateStudyStateByStaffId(staffId);
        return toAjax(tStaffmgrService.deleteLeftTStaffmgrByIds(id));
    }

    /**
     * 删除退休人员
     */
    @PreAuthorize("@ss.hasPermi('plant:staffmgr:remove')")
    @Log(title = "人员管理", businessType = BusinessType.DELETE)
    @GetMapping("/retire/{id}")
    public AjaxResult removeRetire(@PathVariable Long id) {
        TTrainingrecords tTrainingrecords = tTrainingrecordsService.selectTTrainingrecordsBystaffId(id);
        if (tTrainingrecords != null) {
            tTrainingrecords.setDelFlag(9l);
            tTrainingrecordsService.updateTTrainingrecords(tTrainingrecords);
        }
        // 王子文 2022年6月27日 添加
        // 离职时修改继任者清单状态、培养计划状态
        Long staffId = Long.parseLong(tStaffmgrService.selectTStaffmgrById(id).getStaffid());
        stSuccessorService.updateStateByStaffId(staffId);
        tStPlanService.updateStudyStateByStaffId(staffId);
        return toAjax(tStaffmgrService.deleteRetireTStaffmgrByIds(id));
    }

    /**
     * 复职离职人员
     */
    @PreAuthorize("@ss.hasPermi('plant:staffmgr:remove')")
    @Log(title = "人员管理", businessType = BusinessType.DELETE)
    @GetMapping("/reLeft/{id}")
    public AjaxResult reLeft(@PathVariable Long id) {
        TTrainingrecords tTrainingrecords = tTrainingrecordsService.selectTTrainingrecordsBystaffId(id);
        if (tTrainingrecords != null) {
            tTrainingrecords.setDelFlag(0l);
            tTrainingrecordsService.updateTTrainingrecords(tTrainingrecords);
        }
        return toAjax(tStaffmgrService.reLeftTStaffmgrByIds(id));
    }

    /**
     * 批量导入人员管理
     */
    @PreAuthorize("@ss.hasPermi('plant:staffmgr:add')")
    @Log(title = "人员管理", businessType = BusinessType.INSERT)
    @PostMapping("/importData")
    public AjaxResult importData(@RequestParam("file") MultipartFile file) throws IOException {
        //获取操作人员ID
        Long userId = getUserId();
        //报错行数统计
        List<Integer> failRow = new ArrayList<Integer>();
        Workbook workbook = ExcelUtils.getWorkBook(file);
        Sheet sheet = workbook.getSheetAt(0);
        List<TStaffmgr> list = new ArrayList<TStaffmgr>();
        //字典查询
        List<SysDictData> plant = iSysDictTypeService.selectDictDataByType("PLANT_DIVIDE");
        List<SysDictData> sex = iSysDictTypeService.selectDictDataByType("sys_user_sex");
        List<SysDictData> staff = iSysDictTypeService.selectDictDataByType("STAFF_UNIT");
        List<SysDictData> team = iSysDictTypeService.selectDictDataByType("TEAM_DIVIDE");
        List<SysDictData> actualpost = iSysDictTypeService.selectDictDataByType("ACTUALPOST");
        List<SysDictData> education = iSysDictTypeService.selectDictDataByType("EDUCATION");
        List<SysDictData> enAbility = iSysDictTypeService.selectDictDataByType("ENGLISHABILITY");
        //部门查询
        List<SysDept> dept = iSysDeptService.selectDeptList(new SysDept());
        int rowNum = sheet.getPhysicalNumberOfRows();
        int failNumber = 0;
        for (int i = 1; i < rowNum; i++) {
            try {
                logger.info("读取行数：" + i);
                Row row = sheet.getRow(i);
                int cellNum = row.getLastCellNum();
                TStaffmgr entity = new TStaffmgr();
                for (int j = 0; j < cellNum; j++) {
                    Cell cell = row.getCell(j);
                    if (cell == null) {
                        continue;
                    }
                    String cellValue = ExcelUtils.getCellValue(cell);
                    logger.info("cellValue:" + cellValue);
                    if (j == 0) {
                        for (SysDictData p : plant) {
                            if (p.getDictLabel().equals(cellValue)) {
                                entity.setPlantCode(p.getDictValue());//装置名称
                            }
                        }
                    } else if (j == 1) {
                        entity.setStaffid(cellValue);//员工编号
                    } else if (j == 2) {
                        entity.setName(cellValue);//员工姓名
                    } else if (j == 3) {
                        for (SysDictData p : sex) {
                            if (p.getDictLabel().equals(cellValue)) {
                                entity.setSex(p.getDictValue());//性别

                            }
                        }
                    } else if (j == 4) {
                        if (cellValue.length() > 3) {
                            entity.setBirthday(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//出生日期
                        }
                    } else if (j == 5) {
                        for (SysDictData p : staff) {
                            if (p.getDictLabel().equals(cellValue)) {
                                entity.setUnit(p.getDictValue());//部门
                            }
                        }
                    } else if (j == 6) {
                        for (SysDictData p : team) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setTeam(p.getDictValue());//班值
                            }
                        }
                    } else if (j == 7) {
                        for (SysDictData p : actualpost) {
                            if (p.getDictLabel().equals(cellValue)) {
                                entity.setActualpost(p.getDictValue());//实际岗位
                            }
                        }
                    } else if (j == 8) {
                        entity.setContact(cellValue);//联系方式
                    } else if (j == 9) {
                        for (SysDictData p : education) {
                            if (p.getDictLabel().equals(cellValue)) {
                                entity.setEducation(p.getDictValue());//学历
                            }
                        }
                    } else if (j == 10) {
                        for (SysDictData p : enAbility) {
                            if (p.getDictLabel().equals(cellValue)) {
                                entity.setEnAbility(p.getDictValue());//英语能力
                            }
                        }
                    } else if (j == 11) {
                        entity.setMail(cellValue);//邮箱
                    } else if (j == 12) {
                        for (SysDept d : dept) {
                            if (d.getDeptName().equals(cellValue)) {
                                entity.setDeptId(d.getDeptId());//部门编号
                            }
                        }
                    } else if (j == 13) {
                        entity.setRemarks(cellValue);//备注
                    }
                }
                entity.setCreaterCode(userId.toString());
                logger.info("entity:" + entity);
                list.add(entity);
            } catch (Exception e) {
                failNumber++;
                logger.info("e:" + e);
                failRow.add(i + 1);
            }
        }
        int successNumber = 0;
        int failNum = 0;
        for (TStaffmgr t : list
        ) {
            failNum++;
            try {
                tStaffmgrService.insertTStaffmgr(t);
                if (t.getUnit().equals("10") || t.getUnit().equals("18") || t.getUnit().equals("20")) {
                    TTrainingrecords tTrainingrecords = new TTrainingrecords();
                    tTrainingrecords.setStaffId(t.getId());
                    tTrainingrecords.setPlantCode(t.getPlantCode());
                    tTrainingrecords.setName(t.getName());
                    tTrainingrecords.setEmployeeid(t.getStaffid());
                    tTrainingrecords.setClasses(t.getTeam());
                    tTrainingrecords.setDeptId(t.getDeptId());
                    tTrainingrecordsService.insertTTrainingrecords(tTrainingrecords);
                }
                if (!t.getTeam().equals("18")) {
                    TWorklicense tWorklicense = new TWorklicense();
                    tWorklicense.setPlantCode(t.getPlantCode());
                    tWorklicense.setClasses(t.getTeam());
                    tWorklicense.setName(t.getName());
                    tWorklicense.setEmployeeid(t.getStaffid());
                    tWorklicense.setPost(t.getActualpost());
                    tWorklicense.setDeptId(t.getDeptId());
                    tWorklicenseService.insertTWorklicense(tWorklicense);
                }
                if (t.getUnit().equals("10")) {
                    SimpleDateFormat sdfYear = new SimpleDateFormat("yyyy");
                    TTrainingRegular regular = new TTrainingRegular();
                    regular.setYear(sdfYear.format(new Date()));
                    List<TTrainingRegular> tTrainingRegulars = tTrainingRegularService.selectTTrainingRegularList(regular);
                    for (TTrainingRegular r : tTrainingRegulars) {
                        if (r.getNotPlan().equals("true")) {
                            String[] posts = r.getActualpostId().split(",");
                            for (String post : posts) {
                                if (post.equals(t.getActualpost())) {
                                    TTraining training = tTrainingService.selectTTrainingByRegularId(r.getId());
                                    if (training.getStartDate() == null) {
                                        TTrainingDevice tTrainingDevice = new TTrainingDevice();
                                        tTrainingDevice.setStaffId(t.getStaffid());
                                        tTrainingDevice.setRegularId(training.getId());
                                        tTrainingDevice.setStartDate(r.getPlanTrainingdate());
                                        tTrainingDevice.setSupplementary("0");
                                        tTrainingDeviceService.insertTTrainingDevice(tTrainingDevice);
                                    } else {
                                        TTrainingDevice tTrainingDevice = new TTrainingDevice();
                                        tTrainingDevice.setStaffId(t.getStaffid());
                                        tTrainingDevice.setRegularId(training.getId());
                                        tTrainingDevice.setSupplementary("2");
                                        tTrainingDeviceService.insertTTrainingDevice(tTrainingDevice);
                                    }
                                    TTrainingNon tTrainingNon = new TTrainingNon();
                                    tTrainingNon.setStaffId(t.getStaffid());
                                    tTrainingNon.setTrainingId(training.getId());
                                    tTrainingNon.setIsNew("1");
                                    tTrainingNonService.insertTTrainingNon(tTrainingNon);
                                }
                            }
                        }
                    }
                }
                successNumber++;
            } catch (Exception e) {
                failNumber++;
                logger.info("e:" + e);
                failRow.add(failNum + 1);
            }
        }
        logger.info("list:" + JSON.toJSONString(list));
        logger.info("successNumber:" + String.valueOf(successNumber));
        logger.info("failNumber:" + String.valueOf(failNumber));
        logger.info("failRow:" + String.valueOf(failRow));
        return AjaxResult.success(String.valueOf(successNumber), failRow);
    }

    /**
     * 证件照上传
     */
    @PostMapping("/uploadPhoto")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file, String pType, String pId) throws IOException {
        if (!file.isEmpty()) {
            String url = FileUploadUtils.upload(RuoYiConfig.getFilePath("/" + pType), file);
            TStaffmgr staffmgr = tStaffmgrService.selectTStaffmgrById(Long.parseLong(pId));
            staffmgr.setPhoto(url);
            tStaffmgrService.updateTStaffmgr(staffmgr);
            return AjaxResult.success();
        }
        return AjaxResult.error("上传失败，请联系管理员");
    }
}
