package com.ruoyi.project.training.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

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.service.ISysDeptService;
import com.ruoyi.project.system.service.ISysDictTypeService;
import com.ruoyi.project.training.domain.TTrainingCompanylevel;
import com.ruoyi.project.training.mapper.TTrainingCompanylevelMapper;
import com.ruoyi.project.training.mapper.TTrainingHisparticipantsMapper;
import com.ruoyi.project.training.service.ITTrainingCompanylevelService;
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.TTrainingHisparticipants;
import com.ruoyi.project.training.service.ITTrainingHisparticipantsService;
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 2021-05-31
 */
@RestController
@RequestMapping("/training/hisparticipants")
public class TTrainingHisparticipantsController extends BaseController {
    @Autowired
    private ITTrainingHisparticipantsService tTrainingHisparticipantsService;
    @Resource
    private TTrainingHisparticipantsMapper tTrainingHisparticipantsMapper;
    @Autowired
    private ISysDeptService iSysDeptService;
    @Autowired
    private ISysDictTypeService iSysDictTypeService;
    @Autowired
    private ITTrainingCompanylevelService tTrainingCompanylevelService;

    /**
     * 查询人员-公司级培训历史列表
     */
    @PreAuthorize("@ss.hasPermi('training:hisparticipants:list')")
    @GetMapping("/list")
    public TableDataInfo list(TTrainingHisparticipants tTrainingHisparticipants) {
        startPage();
        List<TTrainingHisparticipants> list = tTrainingHisparticipantsService.selectTTrainingHisparticipantsList(tTrainingHisparticipants);
        return getDataTable(list);
    }

    /**
     * 导出人员-公司级培训历史列表
     */
    @PreAuthorize("@ss.hasPermi('training:hisparticipants:export')")
    @Log(title = "人员-公司级培训历史", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TTrainingHisparticipants tTrainingHisparticipants) {
        List<TTrainingHisparticipants> list = tTrainingHisparticipantsService.selectTTrainingHisparticipantsList(tTrainingHisparticipants);
        ExcelUtil<TTrainingHisparticipants> util = new ExcelUtil<TTrainingHisparticipants>(TTrainingHisparticipants.class);
        return util.exportExcel(list, "hisparticipants");
    }

    /**
     * 获取人员-公司级培训历史详细信息
     */
    @PreAuthorize("@ss.hasPermi('training:hisparticipants:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tTrainingHisparticipantsService.selectTTrainingHisparticipantsById(id));
    }

    /**
     * 新增人员-公司级培训历史
     */
    @PreAuthorize("@ss.hasPermi('training:hisparticipants:add')")
    @Log(title = "人员-公司级培训历史", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TTrainingHisparticipants tTrainingHisparticipants) {
        return toAjax(tTrainingHisparticipantsService.insertTTrainingHisparticipants(tTrainingHisparticipants));
    }

    /**
     * 修改人员-公司级培训历史
     */
    @PreAuthorize("@ss.hasPermi('training:hisparticipants:edit')")
    @Log(title = "人员-公司级培训历史", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TTrainingHisparticipants tTrainingHisparticipants) {
        return toAjax(tTrainingHisparticipantsService.updateTTrainingHisparticipants(tTrainingHisparticipants));
    }

    /**
     * 删除人员-公司级培训历史
     */
    @PreAuthorize("@ss.hasPermi('training:hisparticipants:remove')")
    @Log(title = "人员-公司级培训历史", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tTrainingHisparticipantsService.deleteTTrainingHisparticipantsByIds(ids));
    }

    /**
     * 培训历史导入
     */
    @Log(title = "培训历史导入", businessType = BusinessType.INSERT)
    @PostMapping("/importData")
    public AjaxResult importData(@RequestParam("file") MultipartFile file) throws IOException {
        //获取操作人员ID
        Long userId = getUserId();
        //报错行数统计
        CopyOnWriteArrayList<Integer> failRow = new CopyOnWriteArrayList<Integer>();
        Workbook workbook = ExcelUtils.getWorkBook(file);
        Sheet sheet = workbook.getSheetAt(0);
        CopyOnWriteArrayList<TTrainingHisparticipants> list = new CopyOnWriteArrayList<TTrainingHisparticipants>();
        //字典查询
        List<TTrainingCompanylevel> levelList = tTrainingCompanylevelService.selectTTrainingCompanylevelList(new TTrainingCompanylevel());

        //部门查询
        List<SysDept> dept = iSysDeptService.selectDeptList(new SysDept());
        int rowNum = sheet.getPhysicalNumberOfRows();
        AtomicInteger failNumber = new AtomicInteger();
        //线程池
        ExecutorService executorExcel = Executors.newFixedThreadPool(20);
        final CountDownLatch latchExcel = new CountDownLatch(rowNum-1); //相同线程数量的计数
        for (int i = 1; i < rowNum; i++) {
            final int finalI = i;
            executorExcel.execute(() -> {
                try {
                    logger.info("读取行数：" + finalI);
                    Row row = sheet.getRow(finalI);
                    int cellNum = row.getLastCellNum();
                    logger.info("总列数：" + cellNum);
                    TTrainingHisparticipants entity = new TTrainingHisparticipants();
                    for (int j = 0; j < cellNum; j++) {
                        Cell cell = row.getCell(j);
                        String cellValue = ExcelUtils.getCellValue(cell);
                        logger.info("cellValue:" + cellValue);
                        entity.setRemark(String.valueOf(finalI +1));
                        if (j == 0) {
                            entity.setStaffId(cellValue.trim());
                        } else if (j == 5) {
                            if (cellValue.length() > 3) {
                                entity.setStartDate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                            }
                        } else if (j == 6) {
                            if (cellValue.length() > 3) {
                                entity.setEndDate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                            }
                        } else if (j == 7) { //课程编号
                            entity.setCourseCode(cellValue.trim());
                            for (TTrainingCompanylevel t : levelList
                            ) {
                                if (t.getCourseCode().equals(cellValue.trim())) {
                                    entity.setCompanyId(t.getId());
                                }
                            }
                        } else if (j == 8) {
                            entity.setItem(cellValue);
                        } else if (j == 9) {
                            if (cellValue != "") {
                                entity.setScore(Double.parseDouble(cellValue.trim()));
                            }
                        } else if (j == 10) {
                            if (cellValue != "") {
                                entity.setOperationScore(Double.parseDouble(cellValue.trim()));
                            }
                        } else if (j == 11) {
                            entity.setTrainingPlace(cellValue);
                        } else if (j == 12) {
                            entity.setTrainingDuration(cellValue);
                        } else if (j == 13) {
                            entity.setTrainingCost(cellValue);
                        } else if (j == 14) {
                            entity.setBudget(cellValue);
                        } else if (j == 15) {
                            entity.setRemarks(cellValue);
                        }
                    }
                    entity.setCreaterCode(userId.toString());
                    list.add(entity);
                } catch (Exception e) {
                    logger.error("e", e);
                    failNumber.getAndIncrement();
                    failRow.add(finalI + 1);
                } finally {
                    latchExcel.countDown(); //线程计数
                }
            });
        }
        try {
            latchExcel.await(); //线程计数完毕后继续执行
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executorExcel.shutdown();

        //线程池
        ExecutorService executorService = Executors.newFixedThreadPool(30);
        final CountDownLatch latch = new CountDownLatch(list.size()); //相同线程数量的计数
        AtomicInteger successNumber = new AtomicInteger(0);
        AtomicInteger failNum =  new AtomicInteger(0);
        for (TTrainingHisparticipants t : list
        ) {
            failNum.getAndIncrement();
                executorService.execute(() -> {
                // -- 业务模块
                try {
                    tTrainingHisparticipantsMapper.insertTTrainingHisparticipants(t);
                    successNumber.getAndIncrement();
                } catch (Exception e) {
                    logger.error("e", e);
                    failNumber.getAndIncrement();
                    failRow.add(Integer.parseInt(t.getRemark()));
                }finally {
                    latch.countDown(); //线程计数
                }
            });
        }
        try {
            latch.await(); //线程计数完毕后继续执行
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executorService.shutdown();
        //去重
        tTrainingHisparticipantsMapper.duplicateHiParticipants();
        logger.info("list:" + list.size());
        logger.info("successNumber:" + String.valueOf(successNumber));
        logger.info("failNumber:" + String.valueOf(failNumber.get()));
        logger.info("failRow:" + String.valueOf(failRow));
        return AjaxResult.success(String.valueOf(successNumber), failRow);
    }
}
