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.utils.file.ExcelUtils;
import com.ruoyi.rc.domain.TChapterTemplate;
import com.ruoyi.rc.domain.TQuestionnaire;
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 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.TQuestionnaireTemplate;
import com.ruoyi.rc.service.ITQuestionnaireTemplateService;
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/questionnairetemplate")
public class TQuestionnaireTemplateController extends BaseController
{
    @Autowired
    private ITQuestionnaireTemplateService tQuestionnaireTemplateService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysDictTypeService sysDictTypeService;

    /**
     * 查询问卷模板列表
     */
    @PreAuthorize("@ss.hasPermi('rc:questionnairetemplate:list')")
    @GetMapping("/list")
    public TableDataInfo list(TQuestionnaireTemplate tQuestionnaireTemplate)
    {
        startPage();
        List<TQuestionnaireTemplate> list = tQuestionnaireTemplateService.selectTQuestionnaireTemplateList(tQuestionnaireTemplate);
        for (TQuestionnaireTemplate obj : list) {
            String deptId = obj.getDeptId();
            if (StringUtils.isNotEmpty(deptId)) {
                if (deptId.indexOf(",") != -1) {
                    StringBuffer sb = new StringBuffer();
                    String[] ids = deptId.split(",");
                    for (String id : ids) {
                        SysDept sysDept = deptService.selectDeptById(Long.parseLong(id));
                        sb.append(sysDept.getDeptName()).append(" / ");
                    }
                    obj.setDeptName(sb.toString().substring(0, sb.length() - 3));
                } else {
                    obj.setDeptName(deptService.selectDeptById(Long.parseLong(deptId)).getDeptName());
                }
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出问卷模板列表
     */
    @PreAuthorize("@ss.hasPermi('rc:questionnairetemplate:export')")
    @Log(title = "问卷模板", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TQuestionnaireTemplate tQuestionnaireTemplate)
    {
        List<TQuestionnaireTemplate> list = tQuestionnaireTemplateService.selectTQuestionnaireTemplateList(tQuestionnaireTemplate);
        ExcelUtil<TQuestionnaireTemplate> util = new ExcelUtil<TQuestionnaireTemplate>(TQuestionnaireTemplate.class);
        util.exportExcel(response, list, "问卷模板数据");
    }

    /**
     * 获取问卷模板详细信息
     */
    @PreAuthorize("@ss.hasPermi('rc:questionnairetemplate:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(tQuestionnaireTemplateService.selectTQuestionnaireTemplateById(id));
    }

    /**
     * 新增问卷模板
     */
    @PreAuthorize("@ss.hasPermi('rc:questionnairetemplate:add')")
    @Log(title = "问卷模板", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TQuestionnaireTemplate tQuestionnaireTemplate)
    {
        if (StringUtils.isNull(tQuestionnaireTemplate.getDeptId()) || "".equals(tQuestionnaireTemplate.getDeptId())) {
            tQuestionnaireTemplate.setDeptId(getLoginUser().getDeptId().toString());
        }
        return toAjax(tQuestionnaireTemplateService.insertTQuestionnaireTemplate(tQuestionnaireTemplate));
    }

    /**
     * 修改问卷模板
     */
    @PreAuthorize("@ss.hasPermi('rc:questionnairetemplate:edit')")
    @Log(title = "问卷模板", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TQuestionnaireTemplate tQuestionnaireTemplate)
    {
        return toAjax(tQuestionnaireTemplateService.updateTQuestionnaireTemplate(tQuestionnaireTemplate));
    }

    /**
     * 删除问卷模板
     */
    @PreAuthorize("@ss.hasPermi('rc:questionnairetemplate:remove')")
    @Log(title = "问卷模板", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tQuestionnaireTemplateService.deleteTQuestionnaireTemplateByIds(ids));
    }

    @PostMapping("/importData")
    public AjaxResult importData(@RequestParam("file") MultipartFile file) throws IOException {
        List<SysDictData> typeDict = sysDictTypeService.selectDictDataByType("t_sec_sub_chap_type");
        //报错行数统计
        List<Integer> failRow = new ArrayList<>();
        Workbook workbook = ExcelUtils.getWorkBook(file);
        Sheet sheet = workbook.getSheetAt(0);
        List<TQuestionnaireTemplate> 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();
                TQuestionnaireTemplate entity = new TQuestionnaireTemplate();
                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.setChapterCode(cellValue);
                    } else if (j == 1) {
                        for (SysDictData data : typeDict) {
                            if (data.getDictLabel().equals(cellValue)) {
                                entity.setType(data.getDictValue());
                            }
                        }
                    } else if (j == 2) {
                        entity.setDirectory(cellValue);
                    } else if (j == 3) {
                        entity.setCode(Long.parseLong(cellValue));
                    } else if (j == 4) {
                        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 (TQuestionnaireTemplate t : list) {
            failNum++;
            try {
                TQuestionnaireTemplate obj = new TQuestionnaireTemplate();
                obj.setDirectory(t.getDirectory());
                obj.setCode(t.getCode());
                if (CollectionUtils.isEmpty(tQuestionnaireTemplateService.selectTQuestionnaireTemplateList(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);
    }
}
