package com.ruoyi.web.controller.rc;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.file.ExcelUtils;
import com.ruoyi.system.service.ISysDeptService;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.system.service.ISysDictTypeService;
import com.ruoyi.system.service.ISysPostService;
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.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.rc.domain.TChapterTemplate;
import com.ruoyi.rc.service.ITChapterTemplateService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 章节模板Controller
 * 
 * @author ruoyi
 * @date 2024-07-31
 */
@RestController
@RequestMapping("/rc/chaptertemplate")
public class TChapterTemplateController extends BaseController
{
    @Autowired
    private ITChapterTemplateService tChapterTemplateService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysDictTypeService sysDictTypeService;

    /**
     * 查询全部章节模板列表
     */
    @PreAuthorize("@ss.hasPermi('rc:chaptertemplate:list')")
    @GetMapping("/listAll")
    public AjaxResult listAll(TChapterTemplate tChapterTemplate)
    {
        return success(tChapterTemplateService.selectTChapterTemplateList(tChapterTemplate));
    }

    /**
     * 查询章节模板列表
     */
    @PreAuthorize("@ss.hasPermi('rc:chaptertemplate:list')")
    @GetMapping("/list")
    public TableDataInfo list(TChapterTemplate tChapterTemplate)
    {
        startPage();
        List<TChapterTemplate> list = tChapterTemplateService.selectTChapterTemplateList(tChapterTemplate);
        return getDataTable(list);
    }

    /**
     * 导出章节模板列表
     */
    @PreAuthorize("@ss.hasPermi('rc:chaptertemplate:export')")
    @Log(title = "章节模板", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TChapterTemplate tChapterTemplate)
    {
        List<TChapterTemplate> list = tChapterTemplateService.selectTChapterTemplateList(tChapterTemplate);
        ExcelUtil<TChapterTemplate> util = new ExcelUtil<TChapterTemplate>(TChapterTemplate.class);
        util.exportExcel(response, list, "章节模板数据");
    }

    /**
     * 获取章节模板详细信息
     */
    @PreAuthorize("@ss.hasPermi('rc:chaptertemplate:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(tChapterTemplateService.selectTChapterTemplateById(id));
    }

    /**
     * 新增章节模板
     */
    @PreAuthorize("@ss.hasPermi('rc:chaptertemplate:add')")
    @Log(title = "章节模板", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TChapterTemplate tChapterTemplate)
    {
        if (StringUtils.isNull(tChapterTemplate.getDeptId()) || "".equals(tChapterTemplate.getDeptId())) {
            tChapterTemplate.setDeptId(getLoginUser().getDeptId().toString());
        }
        return toAjax(tChapterTemplateService.insertTChapterTemplate(tChapterTemplate));
    }

    /**
     * 修改章节模板
     */
    @PreAuthorize("@ss.hasPermi('rc:chaptertemplate:edit')")
    @Log(title = "章节模板", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TChapterTemplate tChapterTemplate)
    {
        return toAjax(tChapterTemplateService.updateTChapterTemplate(tChapterTemplate));
    }

    /**
     * 删除章节模板
     */
    @PreAuthorize("@ss.hasPermi('rc:chaptertemplate:remove')")
    @Log(title = "章节模板", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tChapterTemplateService.deleteTChapterTemplateByIds(ids));
    }

    @PostMapping("/importData")
    public AjaxResult importData(@RequestParam("file") MultipartFile file) throws IOException {
        //报错行数统计
        List<Integer> failRow = new ArrayList<>();
        Workbook workbook = ExcelUtils.getWorkBook(file);
        Sheet sheet = workbook.getSheetAt(0);
        List<TChapterTemplate> list = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        int rowNum = sheet.getPhysicalNumberOfRows();
        int failNumber = 0;
        for (int i = 1; i < rowNum; i++) {
            try {
                logger.info("读取行数：" + i);
                Row row = sheet.getRow(i);
                int cellNum = row.getLastCellNum();
                TChapterTemplate entity = new TChapterTemplate();
                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.setCode(cellValue);
                    } else if (j == 1) {
                        entity.setName(cellValue);
                    }
                }
                logger.info("entity:" + entity);
                list.add(entity);
            } catch (Exception e) {
                failNumber++;
                logger.info("e:" + JSON.toJSONString(e));
                failRow.add(i + 1);
            }
        }
        int successNumber = 0;
        int failNum = 0;
        for (TChapterTemplate t : list) {
            failNum++;
            try {
                TChapterTemplate obj = new TChapterTemplate();
                obj.setCode(t.getCode());
                if (CollectionUtils.isEmpty(tChapterTemplateService.selectTChapterTemplateList(obj))) {
                    add(t);
                    successNumber++;
                } else {
                    failNumber++;
                    logger.info("======================数据已存在");
                    failRow.add(failNum + 1);
                }
            } catch (Exception e) {
                failNumber++;
                logger.info("e:" + e);
                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);
    }
}
