package com.ruoyi.project.training.bccnew.controller;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.file.ExcelUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.training.bccnew.domain.TTsFirstplanTmpl;
import com.ruoyi.project.training.bccnew.service.ITTsFirstplanTmplService;
import org.apache.commons.collections4.CollectionUtils;
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.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * 进组培训模版Controller
 *
 * @author ssy
 * @date 2024-05-22
 */
@RestController
@RequestMapping("/bccnew/firstPlanTmpl")
public class TTsFirstplanTmplController extends BaseController {
    @Autowired
    private ITTsFirstplanTmplService tTsFirstplanTmplService;

    /**
     * 查询进组培训模版列表
     */
    @PreAuthorize("@ss.hasPermi('bccnew:firstPlanTmpl:list')")
    @GetMapping("/list")
    public AjaxResult list(TTsFirstplanTmpl tTsFirstplanTmpl) {
        return AjaxResult.success(tTsFirstplanTmplService.selectTTsFirstplanTmplList(tTsFirstplanTmpl));
    }

    /**
     * 导出进组培训模版列表
     */
    @PreAuthorize("@ss.hasPermi('bccnew:firstPlanTmpl:export')")
    @Log(title = "进组培训模版", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TTsFirstplanTmpl tTsFirstplanTmpl) {
        List<TTsFirstplanTmpl> list = tTsFirstplanTmplService.selectTTsFirstplanTmplList(tTsFirstplanTmpl);
        ExcelUtil<TTsFirstplanTmpl> util = new ExcelUtil<TTsFirstplanTmpl>(TTsFirstplanTmpl.class);
        return util.exportExcel(list, "firstPlanTmpl");
    }

    /**
     * 获取进组培训模版详细信息
     */
    @PreAuthorize("@ss.hasPermi('bccnew:firstPlanTmpl:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tTsFirstplanTmplService.selectTTsFirstplanTmplById(id));
    }

    /**
     * 新增进组培训模版
     */
    @PreAuthorize("@ss.hasPermi('bccnew:firstPlanTmpl:add')")
    @Log(title = "进组培训模版", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TTsFirstplanTmpl tTsFirstplanTmpl) {
        TTsFirstplanTmpl tmpl = new TTsFirstplanTmpl();
        tmpl.setTopic(tTsFirstplanTmpl.getTopic());
        if (CollectionUtils.isEmpty(tTsFirstplanTmplService.selectTTsFirstplanTmplList(tmpl))){
            tTsFirstplanTmplService.insertTTsFirstplanTmpl(tTsFirstplanTmpl);
        }
        return toAjax(tTsFirstplanTmplService.updateTTsFirstplanTmpl(tTsFirstplanTmpl));
    }

    /**
     * 修改进组培训模版
     */
    @PreAuthorize("@ss.hasPermi('bccnew:firstPlanTmpl:edit')")
    @Log(title = "进组培训模版", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TTsFirstplanTmpl tTsFirstplanTmpl) {
        return toAjax(tTsFirstplanTmplService.updateTTsFirstplanTmpl(tTsFirstplanTmpl));
    }

    /**
     * 删除进组培训模版
     */
    @PreAuthorize("@ss.hasPermi('bccnew:firstPlanTmpl:remove')")
    @Log(title = "进组培训模版", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tTsFirstplanTmplService.deleteTTsFirstplanTmplByIds(ids));
    }

    @Log(title = "附件上传", businessType = BusinessType.UPDATE)
    @PostMapping("/uploadFile/{id}")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file, @PathVariable Long id) throws IOException {
        if (!file.isEmpty()) {
            String url = FileUploadUtils.upload(RuoYiConfig.getFilePath("/bccnew"), file);
            TTsFirstplanTmpl entity = tTsFirstplanTmplService.selectTTsFirstplanTmplById(id);
            entity.setFileUrl(url);
            entity.setFileName(file.getOriginalFilename());
            tTsFirstplanTmplService.updateTTsFirstplanTmpl(entity);
            return AjaxResult.success(id);
        }
        return AjaxResult.error("上传失败，请联系管理员");
    }


    @PreAuthorize("@ss.hasPermi('training:firstPlanTmpl: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<TTsFirstplanTmpl> list = new ArrayList<>();
        int rowNum = sheet.getLastRowNum();
        int failNumber = 0;
        for (int i = 1; i <= rowNum; i++) {
            try {
                logger.info("读取行数：" + i);
                Row row = sheet.getRow(i);
                if (row == null) {
                    sheet.removeRow(row);
                    rowNum++;
                    continue;
                }
                int cellNum = row.getLastCellNum();
                TTsFirstplanTmpl entity = new TTsFirstplanTmpl();
                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 (j == 0) {
                        entity.setSortTmpl(Long.valueOf(cellValue));
                    } else if (j == 1) {
                        entity.setCourseCode(cellValue);
                    } else if (j == 2) {
                        entity.setTopic(cellValue);
                    } else if (j == 3) {
                        entity.setMaterialVer(cellValue);
                    } else if (j == 4) {
                        entity.setCourseHour(Double.valueOf(cellValue));
                    } else if (j == 5) {
                        entity.setTrainer(cellValue.replaceAll(" ",""));
                    } else if (j == 6) {
                        entity.setExamType(cellValue);
                    } else if (j == 7) {
                        entity.setTimerNeed(Double.valueOf(cellValue));
                    } else if (j == 8) {
                        entity.setRemarks(cellValue);
                    }
                }
                entity.setCreaterCode(userId.toString());
                entity.setCreatedate(new Date());
                logger.info("entity:" + entity);
                list.add(entity);
            } catch (Exception e) {
                failNumber++;
                failRow.add(i + 1);
            }
        }
        int successNumber = 0;
        int failNum = 0;
        for (TTsFirstplanTmpl t : list) {
            failNum++;
            try {
                add(t);
                successNumber++;
            } catch (Exception e) {
                failNumber++;
                failRow.add(failNum + 1);
                logger.info("e=============:{}",e.getMessage());
            }
        }
        logger.info("list:" + JSON.toJSONString(list));
        logger.info("successNumber:{}", successNumber);
        logger.info("failNumber:{}", failNumber);
        logger.info("failRow:{}", failRow);
        return AjaxResult.success(String.valueOf(successNumber), failRow);
    }
}
