package com.fkzy.warn.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fkzy.warn.mapper.ReportMapper;
import com.fkzy.warn.model.EnterpriseInfo;
import com.fkzy.warn.model.Report;
import com.fkzy.warn.model.User;
import com.fkzy.warn.model.params.GenerateReportParams;
import com.fkzy.warn.service.EnterpriseInfoService;
import com.fkzy.warn.service.ReportService;
import com.fkzy.warn.common.constants.EntityConstants;
import com.fkzy.warn.common.request.RequestParameter;
import com.fkzy.warn.common.response.ApiResponse;
import com.fkzy.warn.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;

/**
 * @author zhangjing
 * @date 2023/10/16 18:17
 * @description
 */
@Service
public class ReportServiceImpl extends ServiceImpl<ReportMapper, Report> implements
    ReportService {

    @Resource
    EnterpriseInfoService enterpriseInfoService;
    @Resource
    UserService userService;
    @Resource
    ReportService reportService;


    @Override
    public ApiResponse saveModel(Report entity, String ticket) {
        save(entity);
        return new ApiResponse();
    }

    @Override
    public ApiResponse updateModel(Report entity,String ticket) {
        this.updateById(entity);
        return new ApiResponse();
    }

    @Override
    public ApiResponse deleteModel(List<String> ids) {
        Report entity = new Report();
        entity.setIsDel(EntityConstants.DEL);
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.in("id", ids);
        update(entity, wrapper);
        return new ApiResponse();
    }

    @Override
    public Page<Report> queryPage(RequestParameter parameter) {
        Report entity = parameter.getParameter().toJavaObject(Report.class);
        Page<Report> page = new Page<Report>(parameter.getCurrent(), parameter.getSize());
        page.setSearchCount(true);
        page.setOptimizeCountSql(true);
        QueryWrapper<Report> eWrapper = new QueryWrapper<Report>(entity);
        Page<Report> result = this.page(page, eWrapper);
        return result;
    }

    @Override
    public Map<String,Object> generateReport(GenerateReportParams params, String ticket) {
        Report report = getById(params.getId());
        Map<String,Object> result = new HashMap<>();
        QueryWrapper<EnterpriseInfo> enterpriseInfoQueryWrapper = new QueryWrapper<>();
        enterpriseInfoQueryWrapper.eq("CREDITCODE", report.getCreditCode());
        EnterpriseInfo enterpriseInfo = enterpriseInfoService.getOne(enterpriseInfoQueryWrapper);
        result.put("basicEnterprise",enterpriseInfo);
        return result;
    }

    @Override
    public void quarterlyReport() {
        List<User> user = userService.list();
        List<Report> reportList = new ArrayList<>();

        user.forEach(item->{
            Report report = new Report();
            report.setReportTime(new Date());

            report.setReportType(EntityConstants.QUARTER);
            report.setCompanyName(item.getCompanyName());
            report.setCreditCode(item.getCreditCode());
            report.setBusinessId(item.getId());
            //根据当前定时判断开始时间  1月1日    3月1日  6月1日   9月1日
            LocalDate start = calculateLastQuarterStartDate(LocalDate.now());
            report.setStartTime(Date.from(start.atStartOfDay(ZoneId.systemDefault()).toInstant()));
            report.setEndTime(new Date());
            report.setIsDel(0);
            report.setName(item.getCompanyName()+"-季度报告");
            reportList.add(report);
        });
        reportService.saveBatch(reportList);
    }
    private LocalDate calculateLastQuarterStartDate(LocalDate currentDate) {
        int currentMonth = currentDate.getMonthValue();
        int currentYear = currentDate.getYear();

        int startMonth;
        // 3月1日执行 -> 获取Q1开始日期 (1月1日)
        if (currentMonth == 3) {
            startMonth = 1;

        } else if (currentMonth == 6) {
            // 6月1日执行 -> 获取Q2开始日期 (4月1日)
            startMonth = 4;
        } else if (currentMonth == 9) {
            // 9月1日执行 -> 获取Q3开始日期 (7月1日)
            startMonth = 7;
        } else if (currentMonth == 12) {
            // 12月1日执行 -> 获取Q4开始日期 (10月1日)
            startMonth = 10;
        } else {
            // 如果任务在其他时间意外触发，返回一个默认值或抛出异常

            return currentDate.withDayOfMonth(1).withMonth(1);
            // 默认返回今年1月1日
        }

        return LocalDate.of(currentYear, startMonth, 1);
    }
}
