package cn.ezhizao.project.business.conversion.controller;

import java.time.LocalDate;
import java.time.YearMonth;
import java.time.ZoneId;
import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.ezhizao.common.utils.poi.ExcelUtil;
import cn.ezhizao.framework.aspectj.lang.annotation.Log;
import cn.ezhizao.framework.aspectj.lang.enums.BusinessType;
import cn.ezhizao.framework.web.controller.BaseController;
import cn.ezhizao.framework.web.domain.AjaxResult;
import cn.ezhizao.framework.web.page.TableDataInfo;
import cn.ezhizao.project.business.conversion.domain.BizProductDrawingConversion;
import cn.ezhizao.project.business.conversion.service.IBizProductDrawingConversionService;
import cn.ezhizao.project.business.product.domain.BizProduct;
import cn.ezhizao.project.business.product.service.IBizProductService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
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;

/**
 * 产品电子化率记录Controller
 *
 * @author ezhizao
 * @date 2024-07-16
 */
@RestController
@RequestMapping("/business/conversion")
public class BizProductDrawingConversionController extends BaseController
{
    @Resource
    private IBizProductDrawingConversionService bizProductDrawingConversionService;

    @Resource
    private IBizProductService productService;

    /**
     * 查询产品电子化率记录列表
     */
    @GetMapping("/list")
    @Log(title = "产品电子化率记录查询", businessType = BusinessType.INSERT)
    @Transactional
    public AjaxResult list(BizProductDrawingConversion bizProductDrawingConversion) throws NoSuchFieldException, IllegalAccessException
    {
        if (bizProductDrawingConversion.getYear()!=null ){
            int year = Integer.parseInt(bizProductDrawingConversion.getYear());
            // 将 LocalDate 转换为 Date
            LocalDate startLocalDate = YearMonth.of(year, 1).atDay(1);
            LocalDate endLocalDate = YearMonth.of(year, 12).atEndOfMonth();

            // 使用 atStartOfDay 将 LocalDate 转换为 Date
            Date startTime = Date.from(startLocalDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
            Date endTime = Date.from(endLocalDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

            bizProductDrawingConversion.setStartTime(startTime);
            bizProductDrawingConversion.setEndTime(endTime);
        }
        List<BizProductDrawingConversion> list = bizProductDrawingConversionService.getList(bizProductDrawingConversion);

        List<BizProductDrawingConversion> bizProductDrawingConversions = filterByMonth(list);


        //判断上个月有没有数据，如果没有将从最新一条数据到现在的数据补齐
        if (!bizProductDrawingConversions.isEmpty()){
            // 找到具有最新日期的对象
            BizProductDrawingConversion conversionDate = null;
            Date latestDate = new Date(0); // 假设的最早可能日期
            for (BizProductDrawingConversion conversion : bizProductDrawingConversions) {
                if (conversion.getDate().after(latestDate)) {
                    latestDate = conversion.getDate();
                    conversionDate = conversion;
                }
            }
            if (!isDateInLastMonth(conversionDate.getDate()) || !isDateInCurrentMonth(conversionDate.getDate())){
                //获取中间差了多少月
                List<Integer> months = getIntermediateMonths(conversionDate.getDate(), new Date());
                List<BizProductDrawingConversion> itemList =   new ArrayList<>();

                for (Integer month : months) {
                    Calendar startCalendar = Calendar.getInstance();
                    startCalendar.setTime(conversionDate.getDate());
                    startCalendar.set(Calendar.MONTH, month - 1); // 设置为当前遍历到的月份
                    startCalendar.set(Calendar.DAY_OF_MONTH, 1); // 设置为该月第一天

                    Calendar endCalendar = Calendar.getInstance();
                    endCalendar.setTime(startCalendar.getTime());
                    endCalendar.add(Calendar.MONTH, 1); // 增加一个月
                    endCalendar.set(Calendar.DAY_OF_MONTH, 0); // 设置为增加后的月的最后一天
                    BizProduct product = new BizProduct();
                    product.setStartTime(startCalendar.getTime());
                    product.setEndTime(endCalendar.getTime());
                    int procuctDrawing = productService.getProcuctDrawing(product);
                    //查询出这个月份的电子化上传个数
                    BizProductDrawingConversion item = new BizProductDrawingConversion();
                    item.setDate(endCalendar.getTime()); // 假设你将endTime设置在date属性上

                    // 你可能还需要设置startTime属性
                    item.setStartTime(startCalendar.getTime());
                    item.setNumber(200L);
                    item.setQuantity((long) procuctDrawing);
                    itemList.add(item);

                    // 打印startTime和endTime，用于调试
                    System.out.println("Start Time: " + startCalendar.getTime());
                    System.out.println("End Time: " + endCalendar.getTime());

            }
                bizProductDrawingConversionService.saveBatch(itemList);

                //重新查询结果集
                if (bizProductDrawingConversion.getYear()!=null ){
                    int year = Integer.parseInt(bizProductDrawingConversion.getYear());
                    // 将 LocalDate 转换为 Date
                    LocalDate startLocalDate = YearMonth.of(year, 1).atDay(1);
                    LocalDate endLocalDate = YearMonth.of(year, 12).atEndOfMonth();

                    // 使用 atStartOfDay 将 LocalDate 转换为 Date
                    Date startTime = Date.from(startLocalDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
                    Date endTime = Date.from(endLocalDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

                    bizProductDrawingConversion.setStartTime(startTime);
                    bizProductDrawingConversion.setEndTime(endTime);
                }
                List<BizProductDrawingConversion> newList = bizProductDrawingConversionService.getList(bizProductDrawingConversion);
                 bizProductDrawingConversions = filterByMonth(newList);
            }
        }
        return success(bizProductDrawingConversions);
    }


    public static List<Integer> getIntermediateMonths(Date startDate, Date endDate) {
        Calendar start = Calendar.getInstance();
        start.setTime(startDate);
        start.add(Calendar.MONTH, 1); // 从起始月份的下一个月开始

        Calendar end = Calendar.getInstance();
        end.setTime(endDate);

        List<Integer> months = new ArrayList<>();
        for (int month = start.get(Calendar.MONTH) + 1; month <= end.get(Calendar.MONTH) + 1; month++) {
            months.add(month);
        }

        return months;
    }
    public static boolean isDateInLastMonth(Date date) {
        Calendar now = Calendar.getInstance();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        // 获取当前月份
        int currentMonth = now.get(Calendar.MONTH);

        // 检查给定日期的月份是否是当前月份的上个月
        return calendar.get(Calendar.MONTH) == currentMonth - 1;
    }
    public static boolean isDateInCurrentMonth(Date date) {
        Calendar now = Calendar.getInstance(); // 获取当前日期和时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date); // 设置要检查的日期

        // 获取当前月份
        int currentMonth = now.get(Calendar.MONTH);

        // 检查给定日期的月份是否是当前月份
        return calendar.get(Calendar.MONTH) == currentMonth;
    }
    public static List<BizProductDrawingConversion> filterByMonth(List<BizProductDrawingConversion> list) {
        Map<Integer, BizProductDrawingConversion> latestRecords = new HashMap<>();

        for (BizProductDrawingConversion record : list) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(record.getDate());
            int month = cal.get(Calendar.MONTH) + 1; // Calendar.MONTH 是从0开始的，所以需要+1
            int year = cal.get(Calendar.YEAR);

            // 将月份和年份组合成一个唯一的键
            int key = (year * 100) + month;

            if (!latestRecords.containsKey(key) || record.getDate().after(latestRecords.get(key).getDate())) {
                latestRecords.put(key, record);
            }
        }

        // 将 Map 转换为 List 返回
        return new ArrayList<>(latestRecords.values());
    }

    /**
     * 导出产品电子化率记录列表
     */
    @PreAuthorize("@ss.hasPermi('business:conversion:export')")
    @Log(title = "产品电子化率记录导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizProductDrawingConversion bizProductDrawingConversion) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizProductDrawingConversion);
        List<BizProductDrawingConversion> list = bizProductDrawingConversionService.getList(bizProductDrawingConversion);
        ExcelUtil<BizProductDrawingConversion> util = new ExcelUtil<BizProductDrawingConversion>(BizProductDrawingConversion.class);
        util.exportExcel(response, list, "产品电子化率记录数据");
    }

    /**
     * 获取产品电子化率记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:conversion:query')")
    @Log(title = "产品电子化率记录查询详细信息", businessType = BusinessType.EXPORT)
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(bizProductDrawingConversionService.getById(id));
    }

    /**
     * 新增产品电子化率记录
     */
    @Log(title = "产品电子化率记录新增", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizProductDrawingConversion bizProductDrawingConversion) throws NoSuchFieldException, IllegalAccessException
    {
        bizProductDrawingConversion.setDate(new Date());
        return toAjax(bizProductDrawingConversionService.save(bizProductDrawingConversion));
    }

    /**
     * 修改产品电子化率记录
     */
    @PreAuthorize("@ss.hasPermi('business:conversion:edit')")
    @Log(title = "产品电子化率记录修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizProductDrawingConversion bizProductDrawingConversion) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizProductDrawingConversion);
        return toAjax(bizProductDrawingConversionService.updateById(bizProductDrawingConversion));
    }

    /**
     * 删除产品电子化率记录
     */
    @PreAuthorize("@ss.hasPermi('business:conversion:remove')")
    @Log(title = "产品电子化率记录删除", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids)
    {
        return toAjax(bizProductDrawingConversionService.removeBatchByIds(ids));
    }
}
