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.TTsFlplanTmpl;
import com.ruoyi.project.training.bccnew.domain.TTsFlplanTmplContent;
import com.ruoyi.project.training.bccnew.domain.TTsFtplanTmpl;
import com.ruoyi.project.training.bccnew.domain.TTsFtplanTmplContent;
import com.ruoyi.project.training.bccnew.service.ITTsFtplanTmplContentService;
import com.ruoyi.project.training.bccnew.service.ITTsFtplanTmplService;
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-06-13
 */
@RestController
@RequestMapping("/bccnew/ftPlan")
public class TTsFtplanTmplController extends BaseController {
    @Autowired
    private ITTsFtplanTmplService tTsFtplanTmplService;
    @Autowired
    private ITTsFtplanTmplContentService tTsFtplanTmplContentService;

    /**
     * 查询芳烃培训模版列表
     */
    @PreAuthorize("@ss.hasPermi('bccnew:ftPlan:list')")
    @GetMapping("/list")
    public AjaxResult list(TTsFtplanTmpl tTsFtplanTmpl) {
        return AjaxResult.success(tTsFtplanTmplService.selectTTsFtplanTmplList(tTsFtplanTmpl));
    }

    /**
     * 导出芳烃培训模版列表
     */
    @PreAuthorize("@ss.hasPermi('bccnew:ftPlan:export')")
    @Log(title = "芳烃培训模版", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TTsFtplanTmpl tTsFtplanTmpl) {
        List<TTsFtplanTmpl> list = tTsFtplanTmplService.selectTTsFtplanTmplList(tTsFtplanTmpl);
        ExcelUtil<TTsFtplanTmpl> util = new ExcelUtil<TTsFtplanTmpl>(TTsFtplanTmpl.class);
        return util.exportExcel(list, "ftPlan");
    }

    /**
     * 获取芳烃培训模版详细信息
     */
    @PreAuthorize("@ss.hasPermi('bccnew:ftPlan:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tTsFtplanTmplService.selectTTsFtplanTmplById(id));
    }

    /**
     * 新增芳烃培训模版
     */
    @PreAuthorize("@ss.hasPermi('bccnew:ftPlan:add')")
    @Log(title = "芳烃培训模版", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TTsFtplanTmpl tTsFtplanTmpl) {
        TTsFtplanTmpl tmpl = new TTsFtplanTmpl();
        tmpl.setTopic(tTsFtplanTmpl.getTopic());
        List<TTsFtplanTmpl> tTsFtplanTmpls = tTsFtplanTmplService.selectTTsFtplanTmplList(tmpl);
        TTsFtplanTmplContent content = new TTsFtplanTmplContent();
        content.setCourseDay(tTsFtplanTmpl.getCourseDay());
        content.setContent(tTsFtplanTmpl.getContent());
        content.setSortTmpl(tTsFtplanTmpl.getSortTmpl());
        tTsFtplanTmpl.setCourseDay(null);
        if (CollectionUtils.isEmpty(tTsFtplanTmpls)) {
            tTsFtplanTmplService.insertTTsFtplanTmpl(tTsFtplanTmpl);
            content.setPid(tTsFtplanTmpl.getId());
            return toAjax(tTsFtplanTmplContentService.insertTTsFtplanTmplContent(content));
        } else {
            TTsFtplanTmpl item = tTsFtplanTmpls.get(0);
            content.setPid(item.getId());
            return toAjax(tTsFtplanTmplContentService.insertTTsFtplanTmplContent(content));
        }
    }

    /**
     * 修改芳烃培训模版
     */
    @PreAuthorize("@ss.hasPermi('bccnew:ftPlan:edit')")
    @Log(title = "芳烃培训模版", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TTsFtplanTmpl tTsFtplanTmpl) {
        return toAjax(tTsFtplanTmplService.updateTTsFtplanTmpl(tTsFtplanTmpl));
    }

    /**
     * 删除芳烃培训模版
     */
    @PreAuthorize("@ss.hasPermi('bccnew:ftPlan:remove')")
    @Log(title = "芳烃培训模版", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tTsFtplanTmplService.deleteTTsFtplanTmplByIds(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);
            TTsFtplanTmpl entity = tTsFtplanTmplService.selectTTsFtplanTmplById(id);
            entity.setFileUrl(url);
            entity.setFileName(file.getOriginalFilename());
            tTsFtplanTmplService.updateTTsFtplanTmpl(entity);
            return AjaxResult.success(id);
        }
        return AjaxResult.error("上传失败，请联系管理员");
    }


    @PreAuthorize("@ss.hasPermi('training:ftPlan: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<TTsFtplanTmpl> 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();
                TTsFtplanTmpl entity = new TTsFtplanTmpl();
                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.setDetailPlan(cellValue);
                    } else if (j == 2) {
                        entity.setTopic(cellValue);
                    } else if (j == 3) {
                        entity.setCourseDay(cellValue);
                    } else if (j == 4) {
                        entity.setContent(cellValue);
                    } else if (j == 5) {
                        entity.setTimerNeed(Double.valueOf(cellValue));
                    } else if (j == 6) {
                        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 (TTsFtplanTmpl t : list) {
            failNum++;
            try {
                add(t);
                successNumber++;
            } catch (Exception e) {
                e.printStackTrace();
                failNumber++;
                failRow.add(failNum + 1);
            }
        }
        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);
    }
}
