package com.ruoyi.web.controller.rc;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.rc.domain.*;
import com.ruoyi.rc.service.*;
import com.ruoyi.system.service.ISysDeptService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
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.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 审计记录Controller
 * 
 * @author ruoyi
 * @date 2024-07-19
 */
@RestController
@RequestMapping("/rc/audit")
public class TAuditController extends BaseController
{
    @Autowired
    private ITAuditService tAuditService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ITChapterService tChapterService;

    @Autowired
    private ITQuestionnaireService tQuestionnaireService;

    @Autowired
    private ITChapterTemplateService tChapterTemplateService;

    @Autowired
    private ITQuestionnaireTemplateService tQuestionnaireTemplateService;

    @Autowired
    private ITProgressService tProgressService;

    /**
     * 查询审计记录列表
     */
    @PreAuthorize("@ss.hasPermi('rc:audit:list')")
    @GetMapping("/list")
    public TableDataInfo list(TAudit tAudit)
    {
        startPage();
        List<TAudit> list = tAuditService.selectTAuditList(tAudit);
        for (TAudit 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:audit:export')")
    @Log(title = "审计记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TAudit tAudit)
    {
        List<TAudit> list = tAuditService.selectTAuditList(tAudit);
        ExcelUtil<TAudit> util = new ExcelUtil<TAudit>(TAudit.class);
        util.exportExcel(response, list, "审计记录数据");
    }

    /**
     * 获取审计记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('rc:audit:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        TAudit tAudit = tAuditService.selectTAuditById(id);
        String year = tAudit.getYear();
        if (year.length() > 4) {
            tAudit.setYear(year.substring(0, year.indexOf("-")));
        }
        return success(tAudit);
    }

    /**
     * 新增审计记录
     */
    @PreAuthorize("@ss.hasPermi('rc:audit:add')")
    @Log(title = "审计记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TAudit tAudit)
    {
        if (StringUtils.isNull(tAudit.getDeptId()) || "".equals(tAudit.getDeptId())) {
            tAudit.setDeptId(getLoginUser().getDeptId().toString());
        }
        int result = tAuditService.insertTAudit(tAudit);
        // 章节list
        List<TChapterTemplate> tChapterTemplates = tChapterTemplateService.selectTChapterTemplateList(new TChapterTemplate());
        for (TChapterTemplate tChapterTemplate : tChapterTemplates) {
            // 新增章节
            TChapter chapter = new TChapter();
            chapter.setAuditId(tAudit.getId());
            chapter.setCode(tChapterTemplate.getCode());
            chapter.setName(tChapterTemplate.getName());
            chapter.setDeptId(tAudit.getDeptId());
            tChapterService.insertTChapter(chapter);
            TQuestionnaireTemplate questionnaireTemplate = new TQuestionnaireTemplate();
            questionnaireTemplate.setChapterId(tChapterTemplate.getId());
            // 每个章节对应的问卷list
            List<TQuestionnaireTemplate> tQuestionnaireTemplates = tQuestionnaireTemplateService.selectTQuestionnaireTemplateList(questionnaireTemplate);
            for (TQuestionnaireTemplate tQuestionnaireTemplate : tQuestionnaireTemplates) {
                // 新增问卷
                TQuestionnaire questionnaire = new TQuestionnaire();
                questionnaire.setAuditId(tAudit.getId());
                questionnaire.setChapterId(chapter.getId());
                questionnaire.setType(tQuestionnaireTemplate.getType());
                questionnaire.setDirectory(tQuestionnaireTemplate.getDirectory());
                questionnaire.setCode(tQuestionnaireTemplate.getCode());
                questionnaire.setName(tQuestionnaireTemplate.getName());
                questionnaire.setDeptId(tAudit.getDeptId());
                tQuestionnaireService.insertTQuestionnaire(questionnaire);
                // 新增进度
                TProgress progress = new TProgress();
                progress.setAuditId(tAudit.getId());
                progress.setQuestionnaireId(questionnaire.getId());
                progress.setChapName(chapter.getName());
                progress.setCode(questionnaire.getCode()+"");
                progress.setName(questionnaire.getName());
                progress.setPreparation("1");
                progress.setApplyStatus("1");
                tProgressService.insertTProgress(progress);
            }
        }
        return toAjax(result);
    }

    /**
     * 修改审计记录
     */
    @PreAuthorize("@ss.hasPermi('rc:audit:edit')")
    @Log(title = "审计记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TAudit tAudit)
    {
        return toAjax(tAuditService.updateTAudit(tAudit));
    }

    /**
     * 删除审计记录
     */
    @PreAuthorize("@ss.hasPermi('rc:audit:remove')")
    @Log(title = "审计记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tAuditService.deleteTAuditByIds(ids));
    }
}
