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.service.ITTsFlplanTmplContentService;
import com.ruoyi.project.training.bccnew.service.ITTsFlplanTmplService;
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("/training/flPlan")
public class TTsFlplanTmplController extends BaseController {
    @Autowired
    private ITTsFlplanTmplService tTsFlplanTmplService;
    @Autowired
    private ITTsFlplanTmplContentService tTsFlplanTmplContentService;

    /**
     * 查询分离培训模版列表
     */
    @PreAuthorize("@ss.hasPermi('bccnew:flPlan:list')")
    @GetMapping("/list")
    public AjaxResult list(TTsFlplanTmpl tTsFlplanTmpl) {
        return AjaxResult.success(tTsFlplanTmplService.selectTTsFlplanTmplList(tTsFlplanTmpl));
    }

    /**
     * 导出分离培训模版列表
     */
    @PreAuthorize("@ss.hasPermi('bccnew:flPlan:export')")
    @Log(title = "分离培训模版", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TTsFlplanTmpl tTsFlplanTmpl) {
        List<TTsFlplanTmpl> list = tTsFlplanTmplService.selectTTsFlplanTmplList(tTsFlplanTmpl);
        ExcelUtil<TTsFlplanTmpl> util = new ExcelUtil<TTsFlplanTmpl>(TTsFlplanTmpl.class);
        return util.exportExcel(list, "flPlan");
    }

    /**
     * 获取分离培训模版详细信息
     */
    @PreAuthorize("@ss.hasPermi('bccnew:flPlan:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tTsFlplanTmplService.selectTTsFlplanTmplById(id));
    }

    /**
     * 新增分离培训模版
     */
    @PreAuthorize("@ss.hasPermi('bccnew:flPlan:add')")
    @Log(title = "分离培训模版", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TTsFlplanTmpl tTsFlplanTmpl) {
        TTsFlplanTmpl tmpl = new TTsFlplanTmpl();
        tmpl.setTopic(tTsFlplanTmpl.getTopic());
        List<TTsFlplanTmpl> tTsFlplanTmpls = tTsFlplanTmplService.selectTTsFlplanTmplList(tmpl);
        TTsFlplanTmplContent content = new TTsFlplanTmplContent();
        content.setCourseDay(tTsFlplanTmpl.getCourseDay());
        content.setContent(tTsFlplanTmpl.getContent());
        content.setSortTmpl(tTsFlplanTmpl.getSortTmpl());
        tTsFlplanTmpl.setCourseDay(null);
        if (CollectionUtils.isEmpty(tTsFlplanTmpls)) {
            tTsFlplanTmplService.insertTTsFlplanTmpl(tTsFlplanTmpl);
            content.setPid(tTsFlplanTmpl.getId());
            return toAjax(tTsFlplanTmplContentService.insertTTsFlplanTmplContent(content));
        } else {
            TTsFlplanTmpl item = tTsFlplanTmpls.get(0);
            content.setPid(item.getId());
            return toAjax(tTsFlplanTmplContentService.insertTTsFlplanTmplContent(content));
        }
    }

    /**
     * 修改分离培训模版
     */
    @PreAuthorize("@ss.hasPermi('bccnew:flPlan:edit')")
    @Log(title = "分离培训模版", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TTsFlplanTmpl tTsFlplanTmpl) {
        return toAjax(tTsFlplanTmplService.updateTTsFlplanTmpl(tTsFlplanTmpl));
    }

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

    @PreAuthorize("@ss.hasPermi('bccnew:flPlan: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<TTsFlplanTmpl> list = new ArrayList<>();
        List<TTsFlplanTmplContent> contents = new ArrayList<>();
        int rowNum = sheet.getLastRowNum();
        int failNumber = 0;
        String topic = "";
        boolean flag = false;
        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();
                TTsFlplanTmpl entity = new TTsFlplanTmpl();
                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 (TTsFlplanTmpl 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);
    }
}
