package com.jeeplus.finance.projectReportArchive.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeeplus.common.excel.ExcelOptions;
import com.jeeplus.common.excel.annotation.ExportMode;
import com.jeeplus.common.utils.ResponseUtil;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.finance.invoice.util.EasyPoiUtil;
import com.jeeplus.finance.projectReportArchive.service.CwProjectReportArchiveService;
import com.jeeplus.finance.projectReportArchive.service.dto.CwProjectReportArchiveDTO;
import com.jeeplus.finance.projectReportArchive.service.dto.CwProjectReportArchiveExportDTO;
import com.jeeplus.finance.projectReportArchive.service.dto.ReportDTO;
import com.jeeplus.flowable.feign.IFlowableApi;
import com.jeeplus.logging.annotation.ApiLog;
import com.jeeplus.logging.constant.enums.LogTypeEnum;
import com.jeeplus.sys.feign.IDictApi;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * 财务项目报告归档
 */
@RestController
@Api("财务项目报告归档")
@RequestMapping(value = "/cwProjectReportArchive")
public class CwProjectReportArchiveController {

    @Resource
    private CwProjectReportArchiveService cwProjectReportArchiveService;

    /**
     * 查询财务项目报告归档信息列表
     * @param cwProjectReportArchiveDTO
     * @param page
     * @return
     */
    @ApiLog("查询财务项目报告归档信息列表")
    @PreAuthorize("hasAuthority('cwProjectReportArchive:list')")
    @GetMapping("list")
    public ResponseEntity<IPage<CwProjectReportArchiveDTO>> data(CwProjectReportArchiveDTO cwProjectReportArchiveDTO, Page<CwProjectReportArchiveDTO> page) throws Exception {
        IPage<CwProjectReportArchiveDTO> result = new Page<CwProjectReportArchiveDTO>();
        result = cwProjectReportArchiveService.findList (page, cwProjectReportArchiveDTO);
        // 2. 定义对比日期：2026-03-24
        LocalDate compareDate = LocalDate.of(2026, 3, 24);
        result.getRecords().stream().forEach(i -> {
            // 获取每条记录的创建时间（Date 类型）
            Date createDate = i.getCwprCreateTime();

            // Date 转 LocalDate
            LocalDate createLocalDate = createDate.toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDate();

            // 核心判断：创建时间 > 2026-03-24 → false，否则 true
            boolean flag = !createLocalDate.isAfter(compareDate);
            i.setProjectExecutorFlag(flag);
        });
        return ResponseEntity.ok (result);
    }

    /**
     * 查询审计报告信息列表
     * @param reportDTO
     * @param page
     * @return
     * @throws Exception
     */
    @GetMapping("reportList")
    public ResponseEntity<IPage<ReportDTO>> findReportList(ReportDTO reportDTO, Page<ReportDTO> page) throws Exception {
        IPage<ReportDTO> result = new Page<ReportDTO>();
        result = cwProjectReportArchiveService.findReportList (page, reportDTO);
        return ResponseEntity.ok (result);
    }

    /**
     * 查询报告是否已归档
     * @param reportNo
     * @return
     */
    @GetMapping("findReportUse")
    public ResponseEntity<Boolean> findReportUse(String reportNo) {
        return ResponseEntity.ok (cwProjectReportArchiveService.findReportUse (reportNo));
    }

    /**
     * 查询财务项目报告归档详情
     * @param id
     * @return
     */
    @ApiLog("查询财务项目报告归档详情")
    @PreAuthorize ("hasAnyAuthority('cwProjectReportArchive:view','cwProjectReportArchive:add','cwProjectReportArchive:edit')")
    @GetMapping("queryById")
    public ResponseEntity queryById(@RequestParam("id") String id) {
        CwProjectReportArchiveDTO cwProjectReportArchiveDTO = cwProjectReportArchiveService.queryById ( id );
        return ResponseEntity.ok (cwProjectReportArchiveDTO);
    }

    /**
     * 保存财务项目报告归档信息
     * @param cwProjectReportArchiveDTO
     * @return
     */
    @ApiLog(value = "修改/新增财务项目报告归档信息", type = LogTypeEnum.SAVE)
    @PreAuthorize("hasAnyAuthority('cwProjectReportArchive:add','cwProjectReportArchive:edit')")
    @PostMapping("save")
    public ResponseEntity save(@Valid @RequestBody CwProjectReportArchiveDTO cwProjectReportArchiveDTO) throws Exception {
        cwProjectReportArchiveService.save(cwProjectReportArchiveDTO);
        return ResponseEntity.ok ("操作成功");
    }

    /**
     * 保存财务项目报告归档信息-流程
     * @param cwProjectReportArchiveDTO
     * @return
     */
    @ApiLog(value = "保存财务项目报告归档信息-流程", type = LogTypeEnum.SAVE)
    // @PreAuthorize("hasAnyAuthority('cwProjectReportArchive:add','cwProjectReportArchive:edit')")
    @PostMapping("saveForm")
    public ResponseEntity saveForm(@Valid @RequestBody CwProjectReportArchiveDTO cwProjectReportArchiveDTO) throws Exception {
        String id = cwProjectReportArchiveService.saveForm(cwProjectReportArchiveDTO);
        return ResponseUtil.newInstance().add("businessTable", "cw_project_report_archive").add("businessId", id).ok ("操作成功");
    }

    /**
     * 删除财务项目报告归档信息
     * @param ids
     * @return
     */
    @ApiLog(value = "删除财务项目报告归档信息", type = LogTypeEnum.SAVE)
    @PreAuthorize ("hasAuthority('cwProjectReportArchive:del')")
    @DeleteMapping("delete")
    public ResponseEntity delete(String ids) {
        return cwProjectReportArchiveService.deleteByIds(ids);
    }

    /**
     * 根据id修改状态值status
     * @param dto
     * @return
     */
    @ApiOperation(value = "根据id修改状态值status")
    @PostMapping(value = "/updateStatusById")
    public ResponseEntity<String> updateStatusById(@RequestBody CwProjectReportArchiveDTO dto) {
        String s = cwProjectReportArchiveService.updateStatusById(dto);
        return ResponseEntity.ok(s);
    }

    /**
     * 导出报告归档数据
     *
     * @param cwProjectReportArchiveDTO
     * @param page
     * @param response
     * @throws Exception
     */
    @ApiLog(value = "导出报告归档数据", type = LogTypeEnum.EXPORT)
    @GetMapping("export")
    @PreAuthorize ("hasAuthority('cwProjectReportArchive:export')")
    @ApiOperation(value = "导出报告归档数据")
    public void exportFile(CwProjectReportArchiveDTO cwProjectReportArchiveDTO, Page <CwProjectReportArchiveDTO> page, ExcelOptions options, HttpServletResponse response) throws Exception {
        String fileName = options.getFilename();
        String sheetName = options.getSheetName();
        List<CwProjectReportArchiveDTO> result = new ArrayList<>();
        if ( ExportMode.current.equals ( options.getMode() ) ) {
            result = cwProjectReportArchiveService.ExportList (page, cwProjectReportArchiveDTO).getRecords();
        } else if (ExportMode.selected.equals ( options.getMode() )) {
            result = cwProjectReportArchiveService.ExportList (page, cwProjectReportArchiveDTO).getRecords().stream ( ).filter ( item ->
                    options.getSelectIds ( ).contains ( item.getId ( ) )
            ).collect ( Collectors.toList ( ) );
        } else {
            page.setSize (-1);
            page.setCurrent (0);
            result = cwProjectReportArchiveService.ExportList (page, cwProjectReportArchiveDTO).getRecords();
        }

        if(result.size()>0){
            String cwStatusDatas = SpringUtil.getBean ( IDictApi.class ).getDictListMapByDict ("cw_archive_status");
            Map<String,Object> cwStatusDictValueDTOs = JSON.parseObject(cwStatusDatas, new TypeReference<Map<String,Object>>() {});

            for (CwProjectReportArchiveDTO info : result) {
                if(StringUtils.isNotBlank(info.getStatus())){
                    for (String key : cwStatusDictValueDTOs.keySet()) {
                        if(info.getStatus().equals(key)){
                            info.setStatus(String.valueOf(cwStatusDictValueDTOs.get(key)));
                            break;
                        }
                    }
                }
            }
        }

        /*result.stream().forEach(item -> {
            if (StringUtils.isNotBlank(item.getStatus())){
                item.setStatus(SpringUtil.getBean ( IDictApi.class ).getDictLabel(item.getStatus(),"cw_status",""));
            }
        });*/
        EasyPoiUtil.exportExcel ( result, sheetName,  sheetName, CwProjectReportArchiveDTO.class, fileName, response );

    }

    /**
     * 导出
     *
     * @param response
     * @throws Exception
     */
    @ApiLog(value = "导出归档数据")
    @GetMapping("newExport")
    @ApiOperation(value = "导出归档数据")
    public void newExportFile(CwProjectReportArchiveDTO cwProjectReportArchiveDTO, Page <CwProjectReportArchiveDTO> page, ExcelOptions options,  HttpServletResponse response) throws Exception {
        page.setSize (-1);
        page.setCurrent (0);

        String cwReimbursementSourceTypeDatas = SpringUtil.getBean ( IDictApi.class ).getDictListMapByDict ("cw_entrust_type");
        Map<String,Object> cwReimbursementSourceTypeValueDTOs = JSON.parseObject(cwReimbursementSourceTypeDatas, new TypeReference<Map<String,Object>>() {});

        List<CwProjectReportArchiveExportDTO> result = cwProjectReportArchiveService.findExportList(page, cwProjectReportArchiveDTO).getRecords();

        
        List<CwProjectReportArchiveExportDTO> exports = new ArrayList<>();
        AtomicInteger counter = new AtomicInteger(1);
        result.forEach(re -> {
            //项目经理处理
            //if(StringUtils.isNotBlank(re.getProjectMasterName())){
            //    re.setProjectCreateName(re.getProjectMasterName());
            //}else{
            //    re.setProjectCreateName(re.getRealHeaderName());
            //}
            //字典值处理
            if(StringUtils.isNotBlank(re.getEntrustType())){
                for (String key : cwReimbursementSourceTypeValueDTOs.keySet()) {
                    if(re.getEntrustType().equals(key)){
                        re.setEntrustType(String.valueOf(cwReimbursementSourceTypeValueDTOs.get(key)));
                        break;
                    }
                }
            }
            //设置序号
            re.setIndex(counter.getAndIncrement());
            CwProjectReportArchiveExportDTO exportDTO = new CwProjectReportArchiveExportDTO();
            BeanUtils.copyProperties(re, exportDTO);
            exports.add(exportDTO);
        });
        DateTime now = DateUtil.date();
        String formattedDate = DateUtil.format(now, DatePattern.NORM_DATE_PATTERN);
        EasyPoiUtil.exportExcel ( result, "报告归档数据"+formattedDate,  "报告归档数据"+formattedDate, CwProjectReportArchiveExportDTO.class, "报告归档数据", response );
    }

    /**
     * 查询暂时未归档报告归档数据
     */
    @ApiLog(value = "查询暂时未归档报告归档数据")
    @GetMapping("getNotFiledYetList")
    @ApiOperation(value = "查询暂时未归档报告归档数据")
    public void getNotFiledYetList(){
        CwProjectReportArchiveDTO cwProjectReportArchiveDTO = new CwProjectReportArchiveDTO();
        cwProjectReportArchiveService.getNotFiledYetList(cwProjectReportArchiveDTO);
    }


    /**
     * 根据归档id查询该报告历史归档信息集合
     * @return
     */
    @ApiOperation(value = "根据归档id查询该报告历史归档信息集合")
    @GetMapping("/findHiById")
    public ResponseEntity findHiById(@RequestParam String id) {
        List<CwProjectReportArchiveDTO> hiById = cwProjectReportArchiveService.findHiById(id);
        return ResponseEntity.ok(hiById);
    }


    /**
     * 查询最后一条归档并作废的归档信息
     * @return
     */
    @ApiOperation(value = "查询最后一条归档并作废的归档信息")
    @GetMapping("/getLastAuditDateByReportId")
    public ResponseEntity getLastAuditDateByReportId(@RequestParam String reportId) {
        CwProjectReportArchiveDTO hiById = cwProjectReportArchiveService.getLastAuditDateByReportId(reportId);
        return ResponseEntity.ok(hiById);
    }


    /**
     * 根据id删除财务项目报告归档信息
     * @param id
     * @return
     */
    @ApiLog(value = "根据id删除财务项目报告归档信息", type = LogTypeEnum.SAVE)
    @DeleteMapping("deleteById")
    public ResponseEntity deleteById(String id) {
        return cwProjectReportArchiveService.deleteByIds(id);
    }


    /**
     * 查询一个月内财务项目报告归档信息列表
     * @param cwProjectReportArchiveDTO
     * @param page
     * @return
     */
    @ApiLog("查询一个月内财务项目报告归档信息列表")
    @GetMapping("findCompletedList")
    public ResponseEntity<IPage<CwProjectReportArchiveDTO>> findCompletedList(CwProjectReportArchiveDTO cwProjectReportArchiveDTO, Page<CwProjectReportArchiveDTO> page) throws Exception {
        IPage<CwProjectReportArchiveDTO> result = new Page<CwProjectReportArchiveDTO>();
        result = cwProjectReportArchiveService.findCompletedList (page, cwProjectReportArchiveDTO);
        return ResponseEntity.ok (result);
    }


    @ApiOperation(value = "查询最新盒号和报告文号")
    @GetMapping("/getFileBoxNumber")
    public ResponseEntity<CwProjectReportArchiveDTO> getFileBoxNumber(@RequestParam String reportType,@RequestParam String year) throws Exception{
        CwProjectReportArchiveDTO dto = cwProjectReportArchiveService.findByReportType(reportType,year);
        return ResponseEntity.ok(dto);
    }

    /**
     * 根据报告年份修改文档存放位置
     * @param dto
     * @return
     */
    @ApiOperation(value = "根据报告年份修改文档存放位置")
    @PostMapping(value = "/updatePlaceByYear")
    public ResponseEntity<Map<String, Object>> updatePlaceByYear(@RequestBody CwProjectReportArchiveDTO dto) {
        int rows = cwProjectReportArchiveService.updatePlaceByYear(dto);
        Map<String, Object> result = new HashMap<>();
        if (rows > 0) {
            result.put("code", 0); // 0 表示成功
            result.put("message", "操作成功，共转移 " + rows + " 条份报告");
        } else {
            result.put("code", 1); // 1 表示失败
            result.put("message", "未找到对应年份的数据");
        }
        return ResponseEntity.ok(result);
    }

}
