package com.ruoyi.project.plant.controller;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
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.project.common.DataEntity;
import com.ruoyi.project.plant.domain.TStaffmgr;
import com.ruoyi.project.plant.domain.TStaffmgrRecord;
import com.ruoyi.project.plant.mapper.TStaffmgrMapper;
import com.ruoyi.project.plant.service.ITStaffmgrRecordService;
import com.ruoyi.project.plant.service.ITStaffmgrService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysDictTypeService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
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.*;

/**
 * 人员管理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 ISysUserService sysUserService;


    @Autowired
    private ITStaffmgrRecordService tStaffmgrRecordService;


    /**
     * 获取当前用户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("/selectTime")
    public TableDataInfo selectTime(TStaffmgr tStaffmgr)
    {
        ServletUtils.getParameter("sexs");
        startPage();
        List<TStaffmgr> list = tStaffmgrService.selectRecordList(tStaffmgr);
        List<TTrainingParticipants> tTrainingParticipants = tTrainingParticipantsService.selectTTrainingParticipantsList(new TTrainingParticipants());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        for (int i = 0; i < list.size(); i++) {
            double time = 0;
            for (TTrainingParticipants t : tTrainingParticipants) {
                if (t.getStaffId().equals(list.get(i).getStaffid())) {
                    if (t.getStartDate() != null) {
                        if (sdf.format(t.getStartDate()).equals(sdf.format(new Date()))) {
                            if (t.getTrainingDuration() != null) {
                                time = time + Double.parseDouble(t.getTrainingDuration());
                            }
                        }
                    }
                }
            }
            list.get(i).setTrainingTime(String.valueOf(time));
        }
        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 List<TStaffmgr> leftList(TStaffmgr tStaffmgr)
    {
        List<TStaffmgr> list = tStaffmgrService.selectLeftTStaffmgrList(tStaffmgr);
        return list;
    }

    //学历统计
    @GetMapping("/eduData")
    public List<DataEntity> eduData(Map param)
    {
        param.put("params" , new HashMap<>());
        Map<String,Object> data = new HashMap();
        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("/engData")
    public List<DataEntity> engData(Map param)
    {
        param.put("params" , new HashMap<>());
        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(Map param)
    {
        param.put("params" , new HashMap<>());
        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("/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.setCreaterCode(getUserId().toString());
        int i = tStaffmgrService.insertTStaffmgr(tStaffmgr);

        TStaffmgrRecord record = new TStaffmgrRecord();
        record.setStaffmgrId(tStaffmgr.getId());
        record.setType("入职");
        record.setContent("入职");
        record.setRemarks("入职");
        record.setActionDate(new Date());
        record.setCreatedate(new Date());
        record.setCreaterCode(getUserId().toString());
        tStaffmgrRecordService.insertTStaffmgrRecord(record);
        return toAjax(i);
    }

    /**
     * 修改人员管理
     */
    @PreAuthorize("@ss.hasPermi('plant:staffmgr:edit')")
    @Log(title = "人员管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TStaffmgr tStaffmgr)
    {
        tStaffmgr.setPhoto(null);
        tStaffmgr.setUpdaterCode(getUserId().toString());
        tStaffmgr.setUpdatedate(new Date());
        return toAjax(tStaffmgrService.updateTStaffmgr(tStaffmgr));
    }

    /**
     * 删除人员管理
     */
    @PreAuthorize("@ss.hasPermi('plant:staffmgr:remove')")
    @Log(title = "人员管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        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)
    {
        return toAjax(tStaffmgrService.deleteLeftTStaffmgrByIds(id));
    }

    /**
     * 复职离职人员
     */
    @PreAuthorize("@ss.hasPermi('plant:staffmgr:remove')")
    @Log(title = "人员管理", businessType = BusinessType.DELETE)
    @GetMapping("/reLeft/{id}")
    public AjaxResult reLeft(@PathVariable Long id)
    {
        TStaffmgrRecord record = new TStaffmgrRecord();
        record.setStaffmgrId(id);
        record.setType("复职");
        record.setContent("复职");
        record.setRemarks("复职");
        record.setActionDate(new Date());
        record.setCreatedate(new Date());
        record.setCreaterCode(getUserId().toString());
        tStaffmgrRecordService.insertTStaffmgrRecord(record);
        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.getPhysicalNumberOfCells();
                TStaffmgr entity = new TStaffmgr();
                for (int j = 0; j < cellNum; j++) {
                    Cell cell = row.getCell(j);
                    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) {
                        for (SysDictData p : staff) {
                            if (p.getDictLabel().equals(cellValue)) {
                                entity.setUnit(p.getDictValue());//部门
                            }
                        }
                    } else if (j == 5) {
                        for (SysDictData p : team) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setTeam(p.getDictValue());//班值
                            }
                        }
                    } else if (j == 6) {
                        for (SysDictData p : actualpost) {
                            if (p.getDictLabel().equals(cellValue)) {
                                entity.setActualpost(p.getDictValue());//实际岗位
                            }
                        }
                    } else if (j == 7) {
                        entity.setContact(cellValue);//联系方式
                    } else if (j == 8) {
                        for (SysDictData p : education) {
                            if (p.getDictLabel().equals(cellValue)) {
                                entity.setEducation(p.getDictValue());//学历
                            }
                        }
                    }  else if (j == 9) {
                        entity.setMail(cellValue);//邮箱
                    } else if (j == 10) {
                        for (SysDept d : dept) {
                            if (d.getDeptName().equals(cellValue)) {
                                entity.setDeptId(d.getDeptId());//部门编号
                            }
                        }
                    }  else if (j == 11) {
                        if (cellValue.length() > 3) {
                            String birthday = cellValue.substring(6, 10)+"-"+cellValue.substring(10,12)+"-"+cellValue.substring(12,14);
                            entity.setBirthday(new SimpleDateFormat(DateUtils.getDateFormat(birthday)).parse(birthday));//出生日期
                        }
                        entity.setIdCard(cellValue);//身份证号
                    }   else if (j == 12) {
                        entity.setAddress(cellValue);//地址
                    }   else if (j == 13) {
                        entity.setSpeciality(cellValue);//专业
                    }  else if (j == 14) {
                        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 {
                add(t);
                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("上传失败，请联系管理员");
    }
}
