package com.ruoyi.project.training.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

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.spring.SpringUtils;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.security.service.TokenService;
import com.ruoyi.project.plant.domain.TStaffmgr;
import com.ruoyi.project.plant.mapper.TStaffmgrMapper;
import com.ruoyi.project.sems.domain.TSpecdevDt;
import com.ruoyi.project.sems.domain.TSpecdevGl;
import com.ruoyi.project.sems.his.domain.TApproveSpecModify;
import com.ruoyi.project.system.domain.SysDept;
import com.ruoyi.project.system.domain.SysDictData;
import com.ruoyi.project.training.mapper.TWorkcertificateCbpsMapper;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.runtime.ProcessInstance;
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.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.TWorkcertificateCbps;
import com.ruoyi.project.training.service.ITWorkcertificateCbpsService;
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 2023-07-14
 */
@RestController
@RequestMapping("/training/workcertificateCbps")
public class TWorkcertificateCbpsController extends BaseController
{
    @Autowired
    private ITWorkcertificateCbpsService tWorkcertificateCbpsService;
    @Resource
    private TWorkcertificateCbpsMapper tWorkcertificateCbpsMapper;
    @Resource
    private TStaffmgrMapper tStaffmgrMapper;

    /**
     * 查询作业证书一览列表
     */
    @PreAuthorize("@ss.hasPermi('training:workcertificate:list')")
    @GetMapping("/list")
    public TableDataInfo list(TWorkcertificateCbps tWorkcertificateCbps)
    {
        try {
            //  同步人员
            syncData();
        }catch (Exception e) {
            logger.error(JSON.toJSONString(e));
        };
        startPage();
        List<TWorkcertificateCbps> list = tWorkcertificateCbpsService.selectTWorkcertificateCbpsList(tWorkcertificateCbps);
        return getDataTable(list);
    }

    public AjaxResult syncData() {
        List<String> delList = tWorkcertificateCbpsMapper.queryNeedDeleteIds();
        if (delList.size() > 0){
            for (String id : delList
                 ) {
                tWorkcertificateCbpsMapper.deleteTWorkcertificateCbpsByStaffId(id);
            }
        }

        List<String> addList = tWorkcertificateCbpsMapper.queryNeedInsertIds();
        if (addList.size() > 0) {
            for (String id: addList
                 ) {
                TStaffmgr staffmgr = tStaffmgrMapper.selectTStaffmgrByStaffId(id);
                TWorkcertificateCbps t = new TWorkcertificateCbps();
                t.setEmployeeid(staffmgr.getStaffid());
                t.setClasses(staffmgr.getTeam());
                t.setName(staffmgr.getName());
                t.setDeptId(staffmgr.getDeptId());
                t.setPlantCode(staffmgr.getPlantCode());
                tWorkcertificateCbpsMapper.insertTWorkcertificateCbps(t);
            }
        }
        return AjaxResult.success();
    }

    /**
     * 导出作业证书一览列表
     */
    @PreAuthorize("@ss.hasPermi('training:workcertificate:export')")
    @Log(title = "作业证书一览", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TWorkcertificateCbps tWorkcertificateCbps)
    {
        List<TWorkcertificateCbps> list = tWorkcertificateCbpsService.selectTWorkcertificateCbpsList(tWorkcertificateCbps);
        ExcelUtil<TWorkcertificateCbps> util = new ExcelUtil<TWorkcertificateCbps>(TWorkcertificateCbps.class);
        return util.exportExcel(list, "workcertificateCbps");
    }

    /**
     * 获取作业证书一览详细信息
     */
    @PreAuthorize("@ss.hasPermi('training:workcertificate:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tWorkcertificateCbpsService.selectTWorkcertificateCbpsById(id));
    }

    /**
     * 新增作业证书一览
     */
    @PreAuthorize("@ss.hasPermi('training:workcertificate:add')")
    @Log(title = "作业证书一览", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TWorkcertificateCbps tWorkcertificateCbps)
    {
        return toAjax(tWorkcertificateCbpsService.insertTWorkcertificateCbps(tWorkcertificateCbps));
    }

    /**
     * 修改作业证书一览
     */
    @PreAuthorize("@ss.hasPermi('training:workcertificate:edit')")
    @Log(title = "作业证书一览", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TWorkcertificateCbps tWorkcertificateCbps)
    {
        return toAjax(tWorkcertificateCbpsService.updateTWorkcertificateCbps(tWorkcertificateCbps));
    }

    /**
     * 删除作业证书一览
     */
    @PreAuthorize("@ss.hasPermi('training:workcertificate:remove')")
    @Log(title = "作业证书一览", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tWorkcertificateCbpsService.deleteTWorkcertificateCbpsByIds(ids));
    }

    /**
     * 批量导入
     */
    @PreAuthorize("@ss.hasPermi('training:workcertificate:add')")
    @Log(title = "cbps作业证书一览批量导入", 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<TWorkcertificateCbps> list = new ArrayList<TWorkcertificateCbps>();

        int rowNum = sheet.getPhysicalNumberOfRows();
        int failNumber = 0;
        for (int i = 3; i < rowNum; i++) {
            try {
                logger.info("读取行数：" + i);
                Row row = sheet.getRow(i);
                int cellNum = row.getLastCellNum();
                TWorkcertificateCbps entity = new TWorkcertificateCbps();
                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 (cellValue.equals("NA")) {
                        continue;
                    }
                    if (j == 0) {
                        //序号
                    } else if (j == 4) {
                        entity.setEmployeeid(cellValue);//员工号
                    }else if (j == 7) {
                        //压力容器
                        entity.setContainerDate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                    }else if (j == 8) {
                        entity.setContainerLifespan(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                    }else if (j == 9) {
                        //压力管道
                        entity.setPipeDate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                    }else if (j == 10) {
                        entity.setPipeLifespan(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                    }else if (j == 11) {
                        //技术工人上岗证
                        entity.setWorkerDate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                    }else if (j == 12) {
                        entity.setWorkerLifespan(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                    }else if (j == 13) {
                        //班组长安全培训
                        entity.setForemanDate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                    }else if (j == 14) {
                        entity.setForemanLifespan(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                    }else if (j == 15) {
                        //制冷与空调
                        entity.setAcDate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                    }else if (j == 16) {
                        entity.setAcLifespan(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                    }else if (j == 17) {
                        //建筑物消防员职业资格证
                        entity.setFirefighterDate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                    }else if (j == 18) {
                        entity.setFirefighterLifespan(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                    }else if (j == 19) {
                        //专职安全管理人员
                        entity.setSafetyDate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                    }else if (j == 20) {
                        entity.setSafetyLifespan(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                    }else if (j == 21) {
                        //tds
                        entity.setTdsDate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                    }else if (j == 22) {
                        entity.setTdsLifespan(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                    }
                }
                logger.info("entity:" + entity);
                list.add(entity);
            } catch (Exception e) {
                failNumber++;
                logger.info("e:" + JSON.toJSONString(e));
                failRow.add(i + 1);
            }
        }


        int successNumber = 0;
        int failNum = 0;
        for (TWorkcertificateCbps t : list
        ) {
            failNum++;
            try {
                int n = tWorkcertificateCbpsMapper.updateTWorkcertificateCbpsByStaffId(t);
                if (n == 0) {
                    throw new Exception("未找到人员");
                }
                successNumber++;
            }catch (Exception e){
                failNumber++;
                logger.info("e:" + e);
                failRow.add(failNum + 1);
            }
        }
        return AjaxResult.success(String.valueOf(successNumber), failRow);
    }



}
