package org.jeecg.modules.quartz.job;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.quartz.utils.HolidayUtil;
import org.jeecg.modules.system.app.dto.TeachingDayDTO;
import org.jeecg.modules.system.app.entity.AppSite;
import org.jeecg.modules.system.app.entity.AppSitePlace;
import org.jeecg.modules.system.app.entity.AppSitePriceRules;
import org.jeecg.modules.system.app.entity.AppTeachingTime;
import org.jeecg.modules.system.app.service.IAppSitePlaceService;
import org.jeecg.modules.system.app.service.IAppSitePriceRulesService;
import org.jeecg.modules.system.app.service.IAppSiteService;
import org.jeecg.modules.system.app.service.IAppTeachingTimeService;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author wzq
 * @date 2025/7/15 10:28
 * @description
 */
@Slf4j
@AllArgsConstructor
@Component
public class OrTeachingJobService {

    private final IAppSitePriceRulesService appSitePriceRulesService;

    private final IAppTeachingTimeService appTeachingTimeService;

    private final IAppSitePlaceService appSitePlaceService;

    private final IAppSiteService appSiteService;

    //@Scheduled(cron = "0 00 15 ? * *")
    @Transactional(rollbackFor = Exception.class)
    public void execute() throws ParseException {
        log.info("开始执行定时任务");
//        int year = DateUtils.getYear();
        int year = 2024;
        Map<String, List<String>> HolidayMap = HolidayUtil.getYearHoliday(String.valueOf(year));
        // 设置开始日期和结束日期
        Date beginDate = DateUtils.str2Date((year + 1) + "-01-01 00:00:00", new SimpleDateFormat("yyyy-MM-dd"));
        Date endDate = DateUtils.str2Date((year + 2) + "-01-01 00:00:00", new SimpleDateFormat("yyyy-MM-dd"));
        // 获取开始日期和结束日期之间的所有日期
        List<Date> dateList = HolidayUtil.getDaysBetweenDates(beginDate, endDate);
        //部门、场地、教学日（teaching）、
        //1、查询所有的学校
        LambdaQueryWrapper<AppSite> wrapper = Wrappers.<AppSite>lambdaQuery().eq(AppSite::getType, 0).eq(AppSite::getStatus, 0);
        List<AppSite> appSiteList = appSiteService.list(wrapper);
        List<AppSitePriceRules> appSitePriceRulesList = new ArrayList<>();
        if(!appSiteList.isEmpty()){
            //教学日列表
            List<AppTeachingTime> appteachingList = new ArrayList<>();
            //2、遍历查询所有的学校
            for (AppSite site : appSiteList) {
                //根据学校查询场地
                AppSitePlace appSitePlace = appSitePlaceService.getOne(Wrappers.<AppSitePlace>lambdaQuery().eq(AppSitePlace::getOrgCode, site.getOrgCode()));
                // 遍历生成一对多教学时段
                for (Date localDate : dateList) {
                    AppTeachingTime appTeachingTime = new AppTeachingTime();
                    appTeachingTime
                            .setTenantId(site.getTenantId())
                            //localDate 转 Date
                            .setDay(localDate)
                            .setOrgCode(site.getOrgCode());
                    //格式‘yyyy-MM-dd’
                    String yearHoliday = null;
                    try {
                        List<String> holiday = HolidayMap.get("holiday");
                        List<String> extraWorkDay = HolidayMap.get("extraWorkDay");
                        yearHoliday = HolidayUtil.isWorkingDay(DateUtils.formatDate(localDate, "yyyy-MM-dd"),holiday,extraWorkDay);
                    } catch (ParseException e) {
                        throw new RuntimeException(e);
                    }
                    if("0".equals(yearHoliday)){
                        log.info("是教学日");
                        appTeachingTime.setIsTeaching(0);
                    }else{
                        log.info("非教学日");
                        appTeachingTime.setIsTeaching(1);
                    }
                    //添加到集合中
                    appteachingList.add(appTeachingTime);
                    //如果开放时段列表不为空(教学日/非教学日)，根据开放时段批量存储，开放时段记录
                    if (StringUtils.isNotEmpty(site.getTeachingDay()) && appTeachingTime.getIsTeaching() == 0){
                        JSONObject jsonObject = JSONObject.parseObject(site.getTeachingDay());
                        List<TeachingDayDTO> data = jsonObject.getJSONArray("data").toJavaList(TeachingDayDTO.class);
                        data.forEach(item -> {
                            String startTime = item.getStartTime();
                            String endTime = item.getEndTime();
                            AppSitePriceRules appSitePriceRules = new AppSitePriceRules();
                            appSitePriceRules
                                    .setOrgCode(site.getOrgCode())
                                    .setTenantId(site.getTenantId())
                                    .setSitePlaceId(appSitePlace.getId())
                                    .setType(0)
                                    .setDateOfSale(localDate)
                                    .setStartTime(DateUtils.str2Date(startTime, new SimpleDateFormat("HH:mm")))
                                    .setEndTime(DateUtils.str2Date(endTime, new SimpleDateFormat("HH:mm")))
                                    .setDayOfWeek(HolidayUtil.getWeekOfDate(localDate))
                                    .setIsTeaching(appTeachingTime.getIsTeaching())
                                    .setCategoryId(site.getCategoryId())
                                    .setCreateBy("admin")
                                    .setStatus(CommonConstant.STATUS_NORMAL)
                                    .setDelFlag(CommonConstant.STATUS_NORMAL)
                            ;
                            appSitePriceRulesList.add(appSitePriceRules);
                        });
                    }
                    if (ObjectUtils.isNotEmpty(site.getNoTeachingDay())&& appTeachingTime.getIsTeaching() == 1){
                        List<TeachingDayDTO> data = JSONObject.parseObject(site.getNoTeachingDay()).getJSONArray("data").toJavaList(TeachingDayDTO.class);
                        data.forEach(item -> {
                            String startTime = item.getStartTime();
                            String endTime = item.getEndTime();
                            AppSitePriceRules appSitePriceRules = new AppSitePriceRules();
                            appSitePriceRules
                                    .setOrgCode(site.getOrgCode())
                                    .setTenantId(site.getTenantId())
                                    .setSitePlaceId(appSitePlace.getId())
                                    .setType(0)
                                    .setDateOfSale(localDate)
                                    .setStartTime(DateUtils.str2Date(startTime, new SimpleDateFormat("HH:mm")))
                                    .setEndTime(DateUtils.str2Date(endTime, new SimpleDateFormat("HH:mm")))
                                    .setDayOfWeek(HolidayUtil.getWeekOfDate(localDate))
                                    .setIsTeaching(appTeachingTime.getIsTeaching())
                                    .setCategoryId(site.getCategoryId())
                                    .setCreateBy("admin")
                                    .setStatus(CommonConstant.STATUS_NORMAL)
                                    .setDelFlag(CommonConstant.STATUS_NORMAL)
                            ;
                            appSitePriceRulesList.add(appSitePriceRules);
                        });
                    }
                }
            }
            //存放集合
            appTeachingTimeService.saveBatch(appteachingList);
            //存放开放时段列表
            appSitePriceRulesService.insertList(appSitePriceRulesList);
        }
    }
}