package com.ruoyi.project.training.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.file.ExcelUtils;
import com.ruoyi.project.system.domain.SysDept;
import com.ruoyi.project.system.domain.SysDictData;
import com.ruoyi.project.system.service.ISysDeptService;
import com.ruoyi.project.system.service.ISysDictTypeService;
import org.apache.poi.ss.usermodel.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.training.domain.TNewemployee;
import com.ruoyi.project.training.service.ITNewemployeeService;
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;
import org.springframework.web.multipart.MultipartFile;

/**
 * 新员工培训Controller
 *
 * @author ruoyi
 * @date 2020-12-08
 */
@RestController
@RequestMapping("/training/newemployee")
public class TNewemployeeController extends BaseController
{
    @Autowired
    private ITNewemployeeService tNewemployeeService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;

    /**
     * 查询新员工培训列表
     */
    @PreAuthorize("@ss.hasPermi('training:newemployee:list')")
    @GetMapping("/list")
    public TableDataInfo list(TNewemployee tNewemployee)
    {
        startPage();
        List<TNewemployee> list = tNewemployeeService.selectTNewemployeeList(tNewemployee);
        return getDataTable(list);
    }

    /**
     * 导出新员工培训列表
     */
    @PreAuthorize("@ss.hasPermi('training:newemployee:export')")
    @Log(title = "新员工培训", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TNewemployee tNewemployee)
    {
        List<TNewemployee> list = tNewemployeeService.selectTNewemployeeList(tNewemployee);
        ExcelUtil<TNewemployee> util = new ExcelUtil<TNewemployee>(TNewemployee.class);
        return util.exportExcel(list, "newemployee");
    }

    /**
     * 获取新员工培训详细信息
     */
    @PreAuthorize("@ss.hasPermi('training:newemployee:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tNewemployeeService.selectTNewemployeeById(id));
    }

    /**
     * 新增新员工培训
     */
    @PreAuthorize("@ss.hasPermi('training:newemployee:add')")
    @Log(title = "新员工培训", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TNewemployee tNewemployee)
    {
        tNewemployee.setCreaterCode(getUserId().toString());
        return toAjax(tNewemployeeService.insertTNewemployee(tNewemployee));
    }

    /**
     * 修改新员工培训
     */
    @PreAuthorize("@ss.hasPermi('training:newemployee:edit')")
    @Log(title = "新员工培训", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TNewemployee tNewemployee)
    {
        tNewemployee.setUpdaterCode(getUserId().toString());
        tNewemployee.setUpdatedate(new Date());
        return toAjax(tNewemployeeService.updateTNewemployee(tNewemployee));
    }

    /**
     * 删除新员工培训
     */
    @PreAuthorize("@ss.hasPermi('training:newemployee:remove')")
    @Log(title = "新员工培训", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tNewemployeeService.deleteTNewemployeeByIds(ids));
    }

    /**
     * 批量导入新员工培训
     */
    @PreAuthorize("@ss.hasPermi('training:newemployee: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<TNewemployee> list = new ArrayList<TNewemployee>();
        //字典查询
        List<SysDictData> plant = iSysDictTypeService.selectDictDataByType("PLANT_DIVIDE");
        //部门查询
        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();
                TNewemployee entity = new TNewemployee();
                for (int j = 0; j < cellNum; j++) {
                    Cell cell = row.getCell(j);
                    //  cell.setCellType(CellType.STRING);
                    String cellValue = ExcelUtils.getCellValue(cell);
                    logger.info("cellValue:" + cellValue);
                    if (j == 0) {
                        for (SysDictData p : plant) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setPlantCode(p.getDictValue());//装置名称
                            }
                        }
                    } else if (j == 1) {
                        entity.setName(cellValue);//新员工姓名
                    } else if (j == 2) {
                        entity.setNewPostDepartment(cellValue);//新员工岗位/部门
                    } else if (j == 3) {
                        entity.setMaster(cellValue);//推荐导师
                    } else if (j == 4) {
                        entity.setMasterPostDepartment(cellValue);//推荐导师岗位/部门
                    } else if (j == 5) {
                        entity.setAgreement(cellValue);//师徒协议
                    } else if (j == 6) {
                        if (cellValue.length() > 3) {
                            entity.setStarttime(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//开始学习期限
                        }
                    } else if (j == 7) {
                        if (cellValue.length() > 3) {
                            entity.setEndtime(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//结束学习期限
                        }
                    } else if (j == 8) {
                        entity.setTargetplan(cellValue);//导师带徒目标及计划
                    } else if (j == 9) {
                        entity.setEvaluation(cellValue);//导师带徒考评表
                    } else if (j == 10) {
                        for (SysDept d : dept) {
                            if (d.getDeptName().equals(cellValue.trim())) {
                                entity.setDeptId(d.getDeptId());//部门编号
                            }
                        }
                    } else if (j == 11) {
                        entity.setRemarks(cellValue);//备注
                    }
                }
                entity.setCreaterCode(userId.toString());
                logger.info("entity:" + entity);
                list.add(entity);
            }catch (Exception e){
                failNumber++;
                failRow.add(i+1);
            }
        }
        int successNumber = 0;
        int failNum = 0;
        for (TNewemployee t : list
        ) {
            failNum++;
            try {
                tNewemployeeService.insertTNewemployee(t);
                successNumber++;
            }catch (Exception e){
                failNumber++;
                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);
    }
}
