package cn.iocoder.yudao.module.server.controller.admin.interviewarticle;

import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.server.controller.admin.rectifyinforeport.vo.RectifyInfoReportPageReqVO;
import cn.iocoder.yudao.module.server.dal.dataobject.rectifyinforeport.RectifyInfoReportDO;
import cn.iocoder.yudao.module.system.dal.dataobject.dept.DeptDO;
import cn.iocoder.yudao.module.system.service.dept.DeptService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.annotation.security.PermitAll;
import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.YearMonth;
import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;

import cn.iocoder.yudao.module.server.controller.admin.interviewarticle.vo.*;
import cn.iocoder.yudao.module.server.dal.dataobject.interviewarticle.InterviewArticleDO;
import cn.iocoder.yudao.module.server.service.interviewarticle.InterviewArticleService;

@Tag(name = "管理后台 - 访谈稿")
@RestController
@RequestMapping("/server/interview-article")
@Validated
public class InterviewArticleController {

    @Resource
    private InterviewArticleService interviewArticleService;
    @Resource
    private DeptService deptService;

    @PostMapping("/create")
    @Operation(summary = "创建访谈稿")
    @PreAuthorize("@ss.hasPermission('server:interview-article:create')")
    public CommonResult<Long> createInterviewArticle(@Valid @RequestBody InterviewArticleSaveReqVO createReqVO) {
        Long deptId = SecurityFrameworkUtils.getLoginUserDeptId();
        if(deptId!=null){
            DeptDO dept = deptService.getDept(deptId);
            createReqVO.setDepartmentName(dept.getName());
            createReqVO.setDepartmentId(deptId);
        }
        createReqVO.setPubtime(LocalDateTime.now());
        return success(interviewArticleService.createInterviewArticle(createReqVO));
    }

    @PostMapping("/update")
    @Operation(summary = "更新访谈稿")
    @PreAuthorize("@ss.hasPermission('server:interview-article:update')")
    public CommonResult<Boolean> updateInterviewArticle(@Valid @RequestBody InterviewArticleSaveReqVO updateReqVO) {
        interviewArticleService.updateInterviewArticle(updateReqVO);
        return success(true);
    }

    @PostMapping("/delete")
    @Operation(summary = "删除访谈稿")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('server:interview-article:delete')")
    public CommonResult<Boolean> deleteInterviewArticle(@RequestParam("id") Long id) {
        interviewArticleService.deleteInterviewArticle(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得访谈稿")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('server:interview-article:query')")
    public CommonResult<InterviewArticleRespVO> getInterviewArticle(@RequestParam("id") Long id) {
        InterviewArticleDO interviewArticle = interviewArticleService.getInterviewArticle(id);
        return success(BeanUtils.toBean(interviewArticle, InterviewArticleRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得访谈稿分页")
    @PreAuthorize("@ss.hasPermission('server:interview-article:query')")
    public CommonResult<PageResult<InterviewArticleRespVO>> getInterviewArticlePage(@Valid InterviewArticlePageReqVO pageReqVO) {
        PageResult<InterviewArticleDO> pageResult = interviewArticleService.getInterviewArticlePage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, InterviewArticleRespVO.class));
    }

    @Operation(summary = "首页面板")
    @PermitAll
    @RequestMapping("/indexdata")
    public CommonResult<JSONObject> indexdata(@Valid InterviewArticlePageReqVO pageReqVO) {
        JSONObject indexData = new JSONObject();

        // 总上报数
        indexData.put("totalCount", countByTimeRange(null, null));

        // 本年上报数
        LocalDateTime startOfYear = LocalDate.now().withDayOfYear(1).atStartOfDay();
        LocalDateTime endOfYear = LocalDate.of(LocalDate.now().getYear(), 12, 31).atTime(23, 59, 59);
        indexData.put("yearCount", countByTimeRange(startOfYear, endOfYear));

        // 本季度上报数
        indexData.put("quarterCount", countByTimeRange(
                getStartOfCurrentQuarter(), getEndOfCurrentQuarter()));

        // 本月上报数
        LocalDateTime startOfMonth = LocalDate.now().withDayOfMonth(1).atStartOfDay();
        LocalDateTime endOfMonth = YearMonth.from(LocalDate.now()).atEndOfMonth().atTime(23, 59, 59);
        indexData.put("monthCount", countByTimeRange(startOfMonth, endOfMonth));

        // 每月上报数（本年1~12月）
        List<Long> monthCountList = new ArrayList<>();
        int currentYear = LocalDate.now().getYear();
        for (int month = 1; month <= 12; month++) {
            LocalDateTime start = LocalDate.of(currentYear, month, 1).atStartOfDay();
            LocalDateTime end = YearMonth.of(currentYear, month).atEndOfMonth().atTime(23, 59, 59);
            monthCountList.add(countByTimeRange(start, end));
        }
        indexData.put("monthCountList", monthCountList);


        return success(indexData);
    }
    private Long countByTimeRange(LocalDateTime start, LocalDateTime end) {
        InterviewArticlePageReqVO pageReqVO = new InterviewArticlePageReqVO();
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);

        if (start != null && end != null) {
            pageReqVO.setCreateTime(new LocalDateTime[]{start, end});
        }
        return interviewArticleService.getInterviewArticlePage(pageReqVO).getTotal(); // 使用分页结果的总数
    }
    private LocalDateTime getStartOfCurrentQuarter() {
        Month currentMonth = LocalDate.now().getMonth();
        int startMonth = (currentMonth.firstMonthOfQuarter().getValue());
        return LocalDate.of(LocalDate.now().getYear(), startMonth, 1).atStartOfDay();
    }

    private LocalDateTime getEndOfCurrentQuarter() {
        Month currentMonth = LocalDate.now().getMonth();
        int endMonth = currentMonth.firstMonthOfQuarter().getValue() + 2;
        YearMonth ym = YearMonth.of(LocalDate.now().getYear(), endMonth);
        return ym.atEndOfMonth().atTime(23, 59, 59);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出访谈稿 Excel")
    @PreAuthorize("@ss.hasPermission('server:interview-article:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportInterviewArticleExcel(@Valid InterviewArticlePageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<InterviewArticleDO> list = interviewArticleService.getInterviewArticlePage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "访谈稿.xls", "数据", InterviewArticleRespVO.class,
                        BeanUtils.toBean(list, InterviewArticleRespVO.class));
    }

}