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.TTsLjplanTmpl;
import com.ruoyi.project.training.bccnew.domain.TTsLjplanTmplContent;
import com.ruoyi.project.training.bccnew.service.ITTsLjplanTmplContentService;
import com.ruoyi.project.training.bccnew.service.ITTsLjplanTmplService;
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/ljPlan")
public class TTsLjplanTmplController extends BaseController {
    @Autowired
    private ITTsLjplanTmplService tTsLjplanTmplService;
    @Autowired
    private ITTsLjplanTmplContentService tTsLjplanTmplContentService;

    /**
     * 查询裂解培训模版列表
     */
    @PreAuthorize("@ss.hasPermi('bccnew:ljPlan:list')")
    @GetMapping("/list")
    public AjaxResult list(TTsLjplanTmpl tTsLjplanTmpl) {
        return AjaxResult.success(tTsLjplanTmplService.selectTTsLjplanTmplList(tTsLjplanTmpl));
    }

    /**
     * 导出裂解培训模版列表
     */
    @PreAuthorize("@ss.hasPermi('bccnew:ljPlan:export')")
    @Log(title = "裂解培训模版", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TTsLjplanTmpl tTsLjplanTmpl) {
        List<TTsLjplanTmpl> list = tTsLjplanTmplService.selectTTsLjplanTmplList(tTsLjplanTmpl);
        ExcelUtil<TTsLjplanTmpl> util = new ExcelUtil<TTsLjplanTmpl>(TTsLjplanTmpl.class);
        return util.exportExcel(list, "ljPlan");
    }

    /**
     * 获取裂解培训模版详细信息
     */
    @PreAuthorize("@ss.hasPermi('bccnew:ljPlan:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tTsLjplanTmplService.selectTTsLjplanTmplById(id));
    }

    /**
     * 新增裂解培训模版
     */
    @PreAuthorize("@ss.hasPermi('bccnew:ljPlan:add')")
    @Log(title = "裂解培训模版", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TTsLjplanTmpl tTsLjplanTmpl) {
        TTsLjplanTmpl tmpl = new TTsLjplanTmpl();
        tmpl.setTopic(tTsLjplanTmpl.getTopic());
        List<TTsLjplanTmpl> tTsLjplanTmpls = tTsLjplanTmplService.selectTTsLjplanTmplList(tmpl);
        TTsLjplanTmplContent content = new TTsLjplanTmplContent();
        content.setCourseDay(tTsLjplanTmpl.getCourseDay());
        content.setContent(tTsLjplanTmpl.getContent());
        content.setSortTmpl(tTsLjplanTmpl.getSortTmpl());
        tTsLjplanTmpl.setCourseDay(null);
        if (CollectionUtils.isEmpty(tTsLjplanTmpls)) {
            tTsLjplanTmplService.insertTTsLjplanTmpl(tTsLjplanTmpl);
            content.setPid(tTsLjplanTmpl.getId());
            return toAjax(tTsLjplanTmplContentService.insertTTsLjplanTmplContent(content));
        } else {
            TTsLjplanTmpl item = tTsLjplanTmpls.get(0);
            content.setPid(item.getId());
            return toAjax(tTsLjplanTmplContentService.insertTTsLjplanTmplContent(content));
        }
    }

    /**
     * 修改裂解培训模版
     */
    @PreAuthorize("@ss.hasPermi('bccnew:ljPlan:edit')")
    @Log(title = "裂解培训模版", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TTsLjplanTmpl tTsLjplanTmpl) {
        return toAjax(tTsLjplanTmplService.updateTTsLjplanTmpl(tTsLjplanTmpl));
    }

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


    @PreAuthorize("@ss.hasPermi('training:ljPlan: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<TTsLjplanTmpl> 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();
                TTsLjplanTmpl entity = new TTsLjplanTmpl();
                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) {
                e.printStackTrace();
                failNumber++;
                failRow.add(i + 1);
            }
        }
        int successNumber = 0;
        int failNum = 0;
        for (TTsLjplanTmpl t : list) {
            failNum++;
            try {
                add(t);
                successNumber++;
            } catch (Exception e) {
                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);
    }
}
