package com.ruoyi.web.controller.rc;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.rc.domain.*;
import com.ruoyi.rc.mapper.TAuditMapper;
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;
import sun.util.resources.cldr.es.CalendarData_es_AR;

/**
 * 审计记录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;

    @Autowired
    private ITOpenItemService itOpenItemService;

    @Autowired
    private TAuditMapper tAuditMapper;

    /**
     * 查询当前年份审计装置列表
     */
    @GetMapping("/getAuditDeptList")
    public AjaxResult getAuditDeptList() {
        TAudit audit = new TAudit();
        Calendar calendar = Calendar.getInstance();
        int i = calendar.get(Calendar.YEAR);
        audit.setYear(i+"");
        List<TAudit> tAudits = tAuditMapper.selectAllTAuditList(audit);
        return success(tAudits);
    }

    /**
     * 上级领导页面：查询首页顶部四个方框数据
     */
    @GetMapping("/homeData")
    public AjaxResult getHomeData() {
        HashMap map = new HashMap();

        // 当前登录用户所在部门最近一次审计记录
        TAudit audit = new TAudit();
        audit.setDeptId(getLoginUser().getDeptId().toString());
        TAudit latest = tAuditService.selectTAuditLatest(audit);
        if (latest != null) {
            Long auditId = latest.getId();

            int homeData1 = tAuditMapper.selectHomeData1();
            BigDecimal homeData2 = tAuditMapper.selectHomeData2();
            int homeData3 = tAuditMapper.selectHomeData3(auditId);
            int homeData4 = tAuditMapper.selectHomeData4(auditId);

            map.put("homeData1", homeData1);
            map.put("homeData2", homeData2);
            map.put("homeData3", homeData3);
            map.put("homeData4", homeData4);

            return AjaxResult.success(map);
        } else {
            return AjaxResult.success();
        }
    }

    /**
     * 普通员工页面：查询首页柱状图数据
     */
    @GetMapping("/bar")
    public AjaxResult getBar() {
        TAudit audit = new TAudit();
        audit.setDeptId(getLoginUser().getDeptId().toString());
        TAudit latest = tAuditService.selectTAuditLatest(audit);
        HashMap<String, String> map = new HashMap<String, String>();
        if(latest != null) {
            int code0Count = 0;
            int code1Count = 0;
            int code2Count = 0;
            int code3Count = 0;
            int code4Count = 0;
            int code5Count = 0;
            int code6Count = 0;
            int code7Count = 0;
            int code8Count = 0;
            int code9Count = 0;
            int code0CompleteCount = 0;
            int code1CompleteCount = 0;
            int code2CompleteCount = 0;
            int code3CompleteCount = 0;
            int code4CompleteCount = 0;
            int code5CompleteCount = 0;
            int code6CompleteCount = 0;
            int code7CompleteCount = 0;
            int code8CompleteCount = 0;
            int code9CompleteCount = 0;
            BigDecimal code0CompleteProgress = new BigDecimal(BigInteger.ZERO);
            BigDecimal code1CompleteProgress = new BigDecimal(BigInteger.ZERO);
            BigDecimal code2CompleteProgress = new BigDecimal(BigInteger.ZERO);
            BigDecimal code3CompleteProgress = new BigDecimal(BigInteger.ZERO);
            BigDecimal code4CompleteProgress = new BigDecimal(BigInteger.ZERO);
            BigDecimal code5CompleteProgress = new BigDecimal(BigInteger.ZERO);
            BigDecimal code6CompleteProgress = new BigDecimal(BigInteger.ZERO);
            BigDecimal code7CompleteProgress = new BigDecimal(BigInteger.ZERO);
            BigDecimal code8CompleteProgress = new BigDecimal(BigInteger.ZERO);
            BigDecimal code9CompleteProgress = new BigDecimal(BigInteger.ZERO);
            Long auditId = latest.getId();
            TChapter chapter = new TChapter();
            chapter.setAuditId(auditId);
            List<TChapter> tChapters = tChapterService.selectTChapterList(chapter);
            for (TChapter tChapter : tChapters) {
                String code = tChapter.getCode();
                int index = code.indexOf(".");
                if (index != -1) {
                    code = code.substring(0, index);
                    TQuestionnaire questionnaire = new TQuestionnaire();
                    questionnaire.setChapterId(tChapter.getId());
                    List<TQuestionnaire> tQuestionnaires = tQuestionnaireService.selectTQuestionnaireList(questionnaire);
                    for (TQuestionnaire tQuestionnaire : tQuestionnaires) {
                        boolean flag = "1".equals(tQuestionnaire.getCompletionStatus());
                        switch (code) {
                            case "0": code0Count++; if (flag) {code0CompleteCount++;} break;
                            case "1": code1Count++; if (flag) {code1CompleteCount++;} break;
                            case "2": code2Count++; if (flag) {code2CompleteCount++;} break;
                            case "3": code3Count++; if (flag) {code3CompleteCount++;} break;
                            case "5": code4Count++; if (flag) {code4CompleteCount++;} break;
                            case "6": code5Count++; if (flag) {code5CompleteCount++;} break;
                            case "7": code6Count++; if (flag) {code6CompleteCount++;} break;
                            case "8": code7Count++; if (flag) {code7CompleteCount++;} break;
                            case "9": code8Count++; if (flag) {code8CompleteCount++;} break;
                            case "10": code9Count++; if (flag) {code9CompleteCount++;} break;
                        }
                    }
                }
            }
            if (code0Count != 0) {code0CompleteProgress = new BigDecimal(code0CompleteCount).divide(new BigDecimal(code0Count), 4, BigDecimal.ROUND_HALF_UP);}
            if (code1Count != 0) {code1CompleteProgress = new BigDecimal(code1CompleteCount).divide(new BigDecimal(code1Count), 4, BigDecimal.ROUND_HALF_UP);}
            if (code2Count != 0) {code2CompleteProgress = new BigDecimal(code2CompleteCount).divide(new BigDecimal(code2Count), 4, BigDecimal.ROUND_HALF_UP);}
            if (code3Count != 0) {code3CompleteProgress = new BigDecimal(code3CompleteCount).divide(new BigDecimal(code3Count), 4, BigDecimal.ROUND_HALF_UP);}
            if (code4Count != 0) {code4CompleteProgress = new BigDecimal(code4CompleteCount).divide(new BigDecimal(code4Count), 4, BigDecimal.ROUND_HALF_UP);}
            if (code5Count != 0) {code5CompleteProgress = new BigDecimal(code5CompleteCount).divide(new BigDecimal(code5Count), 4, BigDecimal.ROUND_HALF_UP);}
            if (code6Count != 0) {code6CompleteProgress = new BigDecimal(code6CompleteCount).divide(new BigDecimal(code6Count), 4, BigDecimal.ROUND_HALF_UP);}
            if (code7Count != 0) {code7CompleteProgress = new BigDecimal(code7CompleteCount).divide(new BigDecimal(code7Count), 4, BigDecimal.ROUND_HALF_UP);}
            if (code8Count != 0) {code8CompleteProgress = new BigDecimal(code8CompleteCount).divide(new BigDecimal(code8Count), 4, BigDecimal.ROUND_HALF_UP);}
            if (code9Count != 0) {code9CompleteProgress = new BigDecimal(code9CompleteCount).divide(new BigDecimal(code9Count), 4, BigDecimal.ROUND_HALF_UP);}
            map.put("code0", code0CompleteProgress.toString());
            map.put("code1", code1CompleteProgress.toString());
            map.put("code2", code2CompleteProgress.toString());
            map.put("code3", code3CompleteProgress.toString());
            map.put("code5", code4CompleteProgress.toString());
            map.put("code6", code5CompleteProgress.toString());
            map.put("code7", code6CompleteProgress.toString());
            map.put("code8", code7CompleteProgress.toString());
            map.put("code9", code8CompleteProgress.toString());
            map.put("code10", code9CompleteProgress.toString());
        } else {
            map.put("code0", "0");
            map.put("code1", "0");
            map.put("code2", "0");
            map.put("code3", "0");
            map.put("code5", "0");
            map.put("code6", "0");
            map.put("code7", "0");
            map.put("code8", "0");
            map.put("code9", "0");
            map.put("code10", "0");
        }
        return success(map);
    }

    /**
     * 普通员工页面：查询首页饼图数据
     */
    @GetMapping("/pie")
    public AjaxResult getPie() {
//        int count = 0;
//        int completeCount = 0;
//        BigDecimal progress = new BigDecimal(BigInteger.ZERO);
//        TAudit audit = new TAudit();
//        audit.setDeptId(getLoginUser().getDeptId().toString());
//        TAudit latest = tAuditService.selectTAuditLatest(audit);
//        if (latest != null) {
//            Long auditId = latest.getId();
//            TChapter chapter = new TChapter();
//            chapter.setAuditId(auditId);
//            List<TChapter> tChapters = tChapterService.selectTChapterList(chapter);
//            for (TChapter tChapter : tChapters) {
//                TQuestionnaire questionnaire = new TQuestionnaire();
//                questionnaire.setChapterId(tChapter.getId());
//                List<TQuestionnaire> tQuestionnaires = tQuestionnaireService.selectTQuestionnaireList(questionnaire);
//                for (TQuestionnaire tQuestionnaire : tQuestionnaires) {
//                    TOpenItem openItem = new TOpenItem();
//                    openItem.setQuestionnaireId(tQuestionnaire.getId());
//                    List<TOpenItem> tOpenItems = itOpenItemService.selectTOpenItemList(openItem);
//                    for (TOpenItem tOpenItem : tOpenItems) {
//                        count++;
//                        String status = tOpenItem.getStatus();
//                        if ("4".equals(status)) {
//                            completeCount++;
//                        }
//                    }
//                }
//            }
//            if (count != 0) {
//                progress = new BigDecimal(completeCount).divide(new BigDecimal(count), 4, BigDecimal.ROUND_HALF_UP);
//            }
//
//        }
        TAudit audit = new TAudit();
        audit.setDeptId(getLoginUser().getDeptId().toString());
        TAudit latest = tAuditService.selectTAuditLatest(audit);
        Double result = new Double("0");
        if (latest != null) {
            result = tAuditMapper.selectHomeDataPie(latest.getId());
        }
        return success(result);
    }

    /**
     * 查询当前登录用户所在部门最近一次审计记录
     */
    @GetMapping("/current")
    public AjaxResult getCurrent() {
        TAudit audit = new TAudit();
        audit.setDeptId(getLoginUser().getDeptId().toString());
        TAudit latest = tAuditService.selectTAuditLatest(audit);
        return success(latest);
    }

    /**
     * 查询审计记录列表
     */
    @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());
                questionnaire.setCompletionStatus("2");
                questionnaire.setYear(tAudit.getYear());
                tQuestionnaireService.insertTQuestionnaire(questionnaire);
                // 新增进度
                TProgress progress = new TProgress();
                progress.setAuditId(tAudit.getId());
                progress.setQuestionnaireId(questionnaire.getId());
                progress.setCode(questionnaire.getCode()+"");
                progress.setName(questionnaire.getName());
                progress.setPreparation("1");
                progress.setApplyStatus("1");
                String name = chapter.getName();
                String code = chapter.getCode();
                if (StringUtils.isNotNull(code) && StringUtils.isNotNull(name)) {
                    int dotNum = this.getDotNum(code);
                    if (dotNum == 0) {//章节
                        progress.setSecSubChapName("-");
                        progress.setSubChapName("-");
                        progress.setChapName(code + " " + name);
                    } else if (dotNum == 1) {//细分章节
                        progress.setSecSubChapName("-");
                        progress.setSubChapName(code + " " + name);
                        String chapCode = code.substring(0, code.indexOf("."));
                        progress.setChapName(chapCode + " " + tChapterTemplateService.selectNameByCode(chapCode));
                    } else {//二级细分章节
                        progress.setSecSubChapName(code + " " + name);
                        String subChapCode = code.substring(0, code.lastIndexOf("."));
                        progress.setSubChapName(subChapCode + " " + tChapterTemplateService.selectNameByCode(subChapCode));
                        String chapCode = subChapCode.substring(0, subChapCode.indexOf("."));
                        progress.setChapName(chapCode + " " + tChapterTemplateService.selectNameByCode(chapCode));
                    }
                }
                tProgressService.insertTProgress(progress);
            }
        }
        return toAjax(result);
    }

    public int getDotNum(String code) {
        int num = 0;
        int i = code.indexOf(".");
        if (i != -1) {
            String[] split = code.split("\\.");
            num = split.length - 1;
        }
        return num;
    }

    /**
     * 修改审计记录
     */
    @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));
    }
}
