package com.yunyan.web.controller.business;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.yunyan.business.constant.BusinessCacheConstants;
import com.yunyan.business.document.y22.pojo.finalExcelY22.ExcelDeptInfoVo;
import com.yunyan.business.document.y23.budget.pojo.budgetY23.update.UpdateBudgetP3Vo;
import com.yunyan.business.pojo.admin.dto.*;
import com.yunyan.business.pojo.admin.vo.*;
import com.yunyan.business.service.*;
import com.yunyan.common.annotation.Anonymous;
import com.yunyan.common.core.redis.RedisCache;
import com.yunyan.common.exception.ServiceException;
import com.yunyan.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.yunyan.common.annotation.Log;
import com.yunyan.common.core.controller.BaseController;
import com.yunyan.common.core.domain.AjaxResult;
import com.yunyan.common.enums.BusinessType;
import com.yunyan.business.domain.FinalData;
import com.yunyan.common.utils.poi.ExcelUtil;
import com.yunyan.common.core.page.TableDataInfo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.yunyan.common.core.domain.AjaxResultVo;

/**
 * 报告数据Controller
 *
 * @author yunyan
 * @date 2023-07-27
 */
@Slf4j
@Api(tags = "1.0.1报告数据")
@RestController
@RequestMapping("/final/finalData")
public class FinalDataController extends BaseController
{
    @Autowired
    private IFinalDataService finalDataService;

    @Autowired
    private ISyncService syncService;

    @Autowired
    private IFinalDataUpdateDataService finalDataUpdateDataService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ICommonUtilService commonUtilService;

    @Autowired
    private IReportDeptService reportDeptService;

    @Autowired
    private IBudgetDataUpdateDataService budgetDataUpdateDataService;

    @Autowired
    private IFinalImport2023Service iFinalImport2023Service;

    @Autowired
    private IReportFileService reportFileService;

    /**
     * 查询报告数据列表
     */
    @ApiOperation(value="查询报告数据列表", notes="查询报告数据列表")
    @PreAuthorize("@ss.hasPermi('final:finalData:list')")
    @GetMapping("/list")
    public TableDataInfo<FinalDataListVo> list(FinalDataListDto dto)
    {
        startPage();
        List<FinalDataListVo> list = finalDataService.selectFinalDataList(dto);
        return getDataTable(list);
    }

    /**
     * 导出报告数据列表
     */
    @ApiOperation(value="导出报告数据列表", notes="导出报告数据列表")
    @PreAuthorize("@ss.hasPermi('final:finalData:export')")
    @Log(title = "导出报告数据列表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, @Validated FinalDataListDto dto)
    {
        //限制 导出 1000
        dto.setLimitRowNum(1000);
        List<FinalDataExportListVo> list = finalDataService.selectFinalDataExportList(dto);
        ExcelUtil<FinalDataExportListVo> util = new ExcelUtil<>(FinalDataExportListVo.class);
        util.exportExcel(response, list, "报告数据列表");
    }

    @ApiOperation(value="公开网址导出", notes="公开网址导出")
    @PreAuthorize("@ss.hasPermi('final:finalData:exportPublicSite')")
    @Log(title = "公开网址导出", businessType = BusinessType.EXPORT)
    @PostMapping("/exportPublicSite")
    public void exportPublicSite(HttpServletResponse response, @Validated FinalDataListDto dto)
    {
        dto.setPublicStatus(1);
        List<FinalDataPublicSiteListVo> list = finalDataService.selectFinalDataPublicSiteList(dto);
        ExcelUtil<FinalDataPublicSiteListVo> util = new ExcelUtil<>(FinalDataPublicSiteListVo.class);
        util.exportExcel(response, list, "公开网址数据");
    }

    /**
     * 获取报告数据详细信息
     */
    @ApiOperation(value="决算-获取报告数据的表格数据", notes="决算-获取报告数据的表格数据")
    @PreAuthorize("@ss.hasPermi('final:finalData:query')")
    @GetMapping(value = "/{id}")
    public AjaxResultVo<FinalDataTableVo> getInfo(@PathVariable("id") Long id)
    {
        return finalDataService.getTableInfo(id);
    }

    @ApiOperation(value="预算-获取报告数据的表格数据", notes="预算获取报告数据的表格数据")
    //@PreAuthorize("@ss.hasPermi('final:finalData:budgetQuery')")
    @PreAuthorize("@ss.hasPermi('final:finalData:query')")
    @GetMapping(value = "/budget/{id}")
    public AjaxResultVo<BudgetDataTableVo> getBudgetInfo(@PathVariable("id") Long id)
    {
        return finalDataService.getBudgetInfo(id);
    }

    /**
     * 修改报告数据
     */
    @Deprecated
    @ApiOperation(value="(废弃)修改报告数据", notes="修改报告数据")
    @PreAuthorize("@ss.hasPermi('final:finalData:edit')")
    @Log(title = "报告数据", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody FinalData dto)
    {
        return toAjax(finalDataService.updateById(dto));
    }

    /**
     * 删除报告数据
     */
    @ApiOperation(value="删除报告数据", notes="删除报告数据")
    @PreAuthorize("@ss.hasPermi('final:finalData:remove')")
    @Log(title = "报告数据", businessType = BusinessType.DELETE)
	@DeleteMapping("/remove/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(finalDataService.removeByIds(Arrays.asList(ids)));
    }

    @Log(title = "决算情况说明修改", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "1.决算情况说明修改",notes = "决算情况说明修改")
    @PreAuthorize("@ss.hasPermi('final:finalData:changeOverview')")
    @PutMapping("/changeOverview")
    public AjaxResultVo changeOverview(@Valid @RequestBody FinalDataTableDto dto){
        return finalDataService.changeOverview(dto);
    }

    @Log(title = "预算情况说明修改", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "2.预算情况说明修改",notes = "预算情况说明修改")
    @PreAuthorize("@ss.hasPermi('final:finalData:changeOverview:budget')")
    @PutMapping("/changeOverview/budget")
    public AjaxResultVo changeOverviewBudget(@Valid @RequestBody BudgetDataEditDto dto){
        return finalDataService.changeOverviewBudget(dto);
    }

    @Log(title = "预算审核的内容填写", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "2.预算的审核的内容填写",notes = "预算的审核的内容填写")
    //@PreAuthorize("@ss.hasPermi('final:finalData:changeOverview:budgetAuditText')")
    @PutMapping("/changeOverview/budgetAuditText")
    public AjaxResultVo changeOverviewBudgetAuditText(@Valid @RequestBody BudgetDataEditDto dto){
        return finalDataService.changeOverviewBudgetAuditText(dto);
    }

    @Log(title = "名词解释选择保存", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "1.0名词解释选择保存",notes = "名词解释选择修改")
    @PreAuthorize("@ss.hasPermi('final:finalData:termEdit')")
    @PutMapping("/termEdit")
    public AjaxResultVo termEdit( @Valid @RequestBody TermEditDto dto){
        return finalDataService.termEdit(dto);
    }

    /**
     *申请审核报告数据
     *
     * @author loovi
     * @date
     */
    @Log(title = "申请审核报告数据", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "2.申请审核报告数据",notes = "申请审核报告数据")
    @PreAuthorize("@ss.hasPermi('final:finalData:applyAudit')")
    @PutMapping("/applyAudit/{id}")
    public AjaxResultVo applyAuditFinalData( @PathVariable Long id){
        return finalDataService.applyAuditFinalData(id);
    }

    /**
    *
    *审核决算
    * @author loovi
    * @date
    */
    @Log(title = "审核决算", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "3.审核决算",notes = "审核决算")
    @PreAuthorize("@ss.hasAnyPermi('final:finalData:auditDept,final:finalData:audit,final:finalData:returnFillStatus')")
    @PutMapping("/audit")
    public AjaxResultVo auditFinalData(@Validated @RequestBody FinalAuditDto dto){
        return  finalDataService.auditFinalData(dto);

    }

    @Log(title = "批量审核/驳回", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "3.批量审核/驳回",notes = "批量审核/驳回")
    @PreAuthorize("@ss.hasAnyPermi('final:finalData:auditBatch')")
    @PutMapping("/auditBatch")
    public AjaxResultVo auditBatchFinalData(@Validated @RequestBody FinalAuditBatchDto dto){
        return  finalDataService.auditBatchFinalData(dto);

    }

    /**
    *公开网址填报
    *
    * @author loovi
    * @date
    */
    @Log(title = "公开网址填报", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "8.公开网址填报",notes = "公开网址填报")
    @PreAuthorize("@ss.hasPermi('final:finalData:websiteFill')")
    @PutMapping("/websiteFill")
    public AjaxResultVo websiteFill( @Validated @RequestBody WebsiteFillDto websiteFillDto){
        return finalDataService.websiteFill(websiteFillDto);
    }

    @ApiOperation(value = "8.0网址访问性检测",notes = "网址访问性检测")
    @PutMapping("/checkUrl")
    public AjaxResultVo checkUrl( @Validated @RequestBody CheckUrlDto dto){
        return finalDataService.checkUrl(dto);
    }

    /**
    *远程PDF与本地PDF文件比较
    *
    * @author loovi
    * @date
    */
    @Deprecated
    @Log(title = "(废弃, 网站填报时检查)文件一致性检查", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "(废弃, 网站填报时检查)文件一致性检查",notes = "远程PDF与本地PDF文件比较")
//    @PreAuthorize("@ss.hasPermi('final:finalData:PDFComparator')")
    @PutMapping("/PDFComparator/{id}")
    public AjaxResultVo PDFComparator(@PathVariable Long id) throws IOException {

        return finalDataService.PDFComparator(id);

    }

    @PostMapping(value = "/finalImportExcel")
    @ApiOperation(value="0.(数据采集)决算excel数据导入", notes="决算excel数据导入")
    @Log(title = "决算采集", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('final:finalData:finalImportExcel')")
    public AjaxResultVo finalImportExcel(@Validated @RequestBody FinalImportExcelDto dto) throws Exception
    {
        if(dto.getDataType()== 50) {
            return iFinalImport2023Service.finalImportExcelBudgetT5(dto);
        } else if(dto.getDataType()== 60) {
            return iFinalImport2023Service.finalImportExcelBudgetT6(dto);
        } else if(dto.getDataType()== 80) {
            return iFinalImport2023Service.finalImportExcelBudgetT8(dto);
        }
        syncService.finalImportExcel(dto);
        return AjaxResultVo.success("文件已上传，处理中，请稍后再查看~");
    }

    @PostMapping(value = "/budgetImportExcel")
    @ApiOperation(value="0.(数据采集)预算excel数据导入", notes="预算excel数据导入")
    @Log(title = "预算采集", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('final:finalData:budgetImportExcel')")
    public AjaxResultVo budgetImportExcel(@Validated @RequestBody FinalImportExcelDto dto) throws Exception
    {
        syncService.budgetImportExcel(dto);
        return AjaxResultVo.success("文件已上传，处理中，请稍后查看~");
    }

    @ApiOperation(value="4.预览/生成PDF", notes="预览/生成PDF")
    //@Log(title = "预决算生成PDF", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasAnyPermi('final:finalData:generatePDF,final:finalData:generatePDFView')")
    @GetMapping("/generatePDF/{id}")
    public AjaxResultVo<FinalDataGeneratePDFVo> generatePDF(@PathVariable("id") Long id) throws Exception
    {
        return finalDataService.generatePDF(id);
    }

    @ApiOperation(value="11.报告导出", notes="报告导出")
    @Log(title = "报告导出", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasAnyPermi('final:finalData:exportReport')")
    @GetMapping("/exportReport/{id}")
    public AjaxResultVo<FinalDataDownloadFileVo> exportReport(@PathVariable("id") Long id) throws Exception
    {
        return finalDataService.exportReport(id);
    }

    @ApiOperation(value="查询excel里的部门的人数信息", notes="查询excel里的部门的人数信息")
    @GetMapping(value = "/deptInfoPerson/{deptId}")
    public AjaxResultVo<ExcelDeptInfoVo> deptInfoPerson(@PathVariable Long deptId)
    {
        return finalDataService.finalDataService(deptId);
    }

    //todo 传权限标识到菜单上
    @ApiOperation(value="11.报告导出-选择", notes="报告导出-选择")
    @PreAuthorize("@ss.hasPermi('final:finalData:selectExportZip')")
    @PostMapping("/exportSelectZip")
    public void selectExportZip(HttpServletResponse response, @Validated FinalDataSelectExportDto dto) {
        finalDataService.selectExportZip(response, dto);
    }

    @ApiOperation(value="11.报告导出-区域全部", notes="报告导出-区域全部")
    @PreAuthorize("@ss.hasPermi('final:finalData:exportZip')")
    @PostMapping("/exportZip")
    public void exportZip(HttpServletResponse response, @Validated FinalDataExportDto dto) {
        finalDataService.exportZip(response, dto);
    }

    @ApiOperation(value="11.上传附件导出-区域全部", notes="上传附件导出-区域全部")
    @PreAuthorize("@ss.hasPermi('final:finalData:exportZipReportFile')")
    @PostMapping("/exportZipReportFile")
    public void exportZipReportFile(HttpServletResponse response, @Validated FinalDataExportDto dto) {
        reportFileService.exportZip(response, dto);
    }

    @Anonymous
    @ApiOperation(value="生成更改文档", notes="生成更改文档")
    //@PreAuthorize("@ss.hasPermi('final:finalData:finalDataGenerate')")
    @GetMapping("/finalDataGenerate")
    public void finalDataGenerate(String area, String s, String year, Integer type) {
        if(StringUtils.isBlank(s) || !s.equals("yungenarate38804")) {
            throw new ServiceException("非法操作, 请稍后再试~");
        }
        if(StringUtils.isBlank(year)) {
            throw new ServiceException("年份不能为空~");
        }
        if(Objects.isNull(type)) {
            throw new ServiceException("报告的类型不能为空~");
        }

        //判断 redis 是否存在 正在生成中
        String generateDocumentKey = BusinessCacheConstants.GENERATE_DOCUMENT_FINAL_FLAG + ":AREA:" + area;
        if (redisCache.hasKey(generateDocumentKey)) {
            log.error("文档在生成中, 请稍后再试~");
            throw new ServiceException("文档在批量生成中, 请稍后再试~");
        }
        finalDataUpdateDataService.finalDataGenerate(area, s, year, type);
    }

    @Log(title = "信息平台网址填报", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "10.信息平台网址填报",notes = "信息平台网址填报")
    @PreAuthorize("@ss.hasPermi('final:finalData:infositeFill')")
    @PutMapping("/infositeFill")
    public AjaxResultVo infositeFill( @Validated @RequestBody InfositeFillDto dto){
        return finalDataService.infositeFill(dto);
    }

    @ApiOperation(value="检测报告的公开网址的状态", notes="检测报告的公开网址的状态")
    @PreAuthorize("@ss.hasPermi('final:finalData:checkWebsiteFillStatue')")
    @GetMapping("/checkWebsiteFillStatue")
    public AjaxResultVo checkWebsiteFillStatue(FinalDataListDto dto)
    {
        commonUtilService.checkWebsiteFillRedisStatus(dto);
        syncService.checkWebsiteFillStatue(dto);
        return AjaxResultVo.success("提交成功，请稍后再查看~");
    }

    @Log(title = "预算的部门概况修改", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "3.0预算的部门概况修改",notes = "预算的部门概况修改")
    @PreAuthorize("@ss.hasAnyPermi('final:finalData:changeOverview,final:finalData:changeOverview:budget')")
    @PutMapping("/changeDeptOverview")
    public AjaxResultVo changeDeptOverview(@Valid @RequestBody SysDeptReportEditDto dto){
        return reportDeptService.changeDeptOverview(dto);
    }


}
