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.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.service.ISysDeptService;
import com.ruoyi.project.system.service.ISysDictTypeService;
import com.ruoyi.project.training.domain.*;
import com.ruoyi.project.training.mapper.TTrainingrecordsMapper;
import com.ruoyi.project.training.service.ITTrainingParticipantsService;
import org.apache.poi.ss.usermodel.*;
import org.apache.velocity.util.ArrayListWrapper;
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.service.ITTrainingrecordsService;
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;

import javax.annotation.Resource;

/**
 * 培训成绩Controller
 *
 * @author ruoyi
 * @date 2020-12-02
 */
@RestController
@RequestMapping("/training/trainingrecords")
public class TTrainingrecordsController extends BaseController
{
    @Autowired
    private ITTrainingrecordsService tTrainingrecordsService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;

    @Autowired
    private ITStaffmgrService tStaffmgrService;

    @Autowired
    private ITTrainingParticipantsService tTrainingParticipantsService;
    @Resource
    private TTrainingrecordsMapper tTrainingrecordsMapper;
    @Resource
    private TStaffmgrMapper tStaffmgrMapper;

    /**
     * 查询培训成绩列表
     */
    @PreAuthorize("@ss.hasPermi('training:trainingrecords:list')")
    @GetMapping("/list")
    public TableDataInfo list(TTrainingrecords tTrainingrecords)
    {
        try {
            //  同步人员
            syncData();
        }catch (Exception e) {
            logger.error(JSON.toJSONString(e));
        };
        startPage();
        List<TTrainingrecords> list = tTrainingrecordsService.selectTTrainingrecordsList(tTrainingrecords);
        return getDataTable(list);
    }

    public AjaxResult syncData() {
        List<String> delList = tTrainingrecordsMapper.queryNeedDeleteIds();
        if (delList.size() > 0){
            for (String id : delList
            ) {
                TTrainingrecords del = tTrainingrecordsMapper.selectTTrainingrecordsBystaffId(Long.parseLong(id));
                tTrainingrecordsMapper.deleteTTrainingrecordsById(del.getId());
            }
        }
        List<String> addList = tTrainingrecordsMapper.queryNeedInsertIds();
        if (addList.size() > 0) {
            for (String id: addList
            ) {
                TStaffmgr tStaffmgr = tStaffmgrMapper.selectTStaffmgrByStaffId(id);
                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);
            }
        }

        return AjaxResult.success();
    }

    /**
     * 导出培训成绩列表
     */
    @PreAuthorize("@ss.hasPermi('training:trainingrecords:export')")
    @Log(title = "培训成绩", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TTrainingrecords tTrainingrecords)
    {
        List<TTrainingrecords> list = tTrainingrecordsService.selectTTrainingrecordsList(tTrainingrecords);
        ExcelUtil<TTrainingrecords> util = new ExcelUtil<TTrainingrecords>(TTrainingrecords.class);
        return util.exportExcel(list, "trainingrecords");
    }

    /**
     * 导出培训成绩列表
     */
    @PreAuthorize("@ss.hasPermi('training:trainingrecords:export')")
    @Log(title = "培训成绩", businessType = BusinessType.EXPORT)
    @GetMapping("/exportTrainingTime")
    public AjaxResult exportTrainingTime()
    {
        List<TTrainingTime> tTrainingTimes = new ArrayList<>();
        TStaffmgr tStaffmgr = new TStaffmgr();
        tStaffmgr.setUnits("10,18");
        List<TStaffmgr> list = tStaffmgrService.selectTStaffmgrList(tStaffmgr);
        List<TTrainingParticipants> tTrainingParticipants = tTrainingParticipantsService.selectTTrainingParticipantsList(new TTrainingParticipants());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        for (int i = 0; i < list.size(); i++) {
            TTrainingTime tTrainingTime = new TTrainingTime();
            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());
                            }
                        }
                    }
                }
            }
            tTrainingTime.setStaffid(list.get(i).getStaffid());
            tTrainingTime.setName(list.get(i).getName());
            tTrainingTime.setTeam(list.get(i).getTeam());
            tTrainingTime.setActualpost(list.get(i).getActualpost());
            tTrainingTime.setTrainingTime(String.valueOf(time));
            tTrainingTimes.add(tTrainingTime);
        }
        ExcelUtil<TTrainingTime> util = new ExcelUtil<TTrainingTime>(TTrainingTime.class);
        return util.exportExcel(tTrainingTimes, "trainingtime");
    }

    /**
     * 获取培训成绩详细信息
     */
    @PreAuthorize("@ss.hasPermi('training:trainingrecords:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tTrainingrecordsService.selectTTrainingrecordsById(id));
    }

    /**
     * 新增培训成绩
     */
    @PreAuthorize("@ss.hasPermi('training:trainingrecords:add')")
    @Log(title = "培训成绩", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TTrainingrecords tTrainingrecords)
    {
        tTrainingrecords.setCreaterCode(getUserId().toString());
        return toAjax(tTrainingrecordsService.insertTTrainingrecords(tTrainingrecords));
    }

    /**
     * 修改培训成绩
     */
    @PreAuthorize("@ss.hasPermi('training:trainingrecords:edit')")
    @Log(title = "培训成绩", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TTrainingrecords tTrainingrecords)
    {
        tTrainingrecords.setUpdaterCode(getUserId().toString());
        tTrainingrecords.setUpdatedate(new Date());
        return toAjax(tTrainingrecordsService.updateTTrainingrecords(tTrainingrecords));
    }

    /**
     * 删除培训成绩
     */
    @PreAuthorize("@ss.hasPermi('training:trainingrecords:remove')")
    @Log(title = "培训成绩", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tTrainingrecordsService.deleteTTrainingrecordsByIds(ids));
    }

    /**
     * 批量导入培训成绩
     */
    @PreAuthorize("@ss.hasPermi('training:trainingrecords: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<TTrainingrecords> list = new ArrayList<TTrainingrecords>();
        //字典查询
        List<SysDictData> plant = iSysDictTypeService.selectDictDataByType("PLANT_DIVIDE");
        List<SysDictData> team = iSysDictTypeService.selectDictDataByType("TEAM_DIVIDE");
        List<SysDictData> training = iSysDictTypeService.selectDictDataByType("TRAINING_QUALIFY");
        //部门查询
        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();
                TTrainingrecords entity = new TTrainingrecords();
                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.setEmployeeid(cellValue);//员工号
                    } else if (j == 43) {
                        for (SysDictData p : team) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setClasses(p.getDictValue());//班值
                            }
                        }
                    } else if (j == 4) {
                        for (SysDictData t : training) {
                            if (t.getDictLabel().equals(cellValue.trim())) {
                                entity.setOnboard(t.getDictValue());//公司入职培训
                            }
                        }
                    } else if (j == 5) {
                        for (SysDictData t : training) {
                            if (t.getDictLabel().equals(cellValue.trim())) {
                                entity.setTds(t.getDictValue());//TDS
                            }
                        }
                    } else if (j == 6) {
                        for (SysDictData t : training) {
                            if (t.getDictLabel().equals(cellValue.trim())) {
                                entity.setPostCard(t.getDictValue());//上岗证复证
                            }
                        }
                    } else if (j == 7) {
                        for (SysDictData t : training) {
                            if (t.getDictLabel().equals(cellValue.trim())) {
                                entity.setCraft(t.getDictValue());//工艺培训
                            }
                        }
                    } else if (j == 8) {
                        for (SysDept d : dept) {
                            if (d.getDeptName().equals(cellValue.trim())) {
                                entity.setDeptId(d.getDeptId());//部门编号
                            }
                        }
                    } else if (j == 9) {
                        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 (TTrainingrecords t : list
        ) {
            failNum++;
            try {
                tTrainingrecordsService.insertTTrainingrecords(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);
    }
}
