/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.modular.base.baseSeason.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.date.ChineseDate;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.listener.CommonDataChangeEventCenter;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.core.enums.BaseDataTypeEnum;
import vip.xiaonuo.core.param.OrgIdParam;
import vip.xiaonuo.modular.base.baseSeason.entity.BaseSeason;
import vip.xiaonuo.modular.base.baseSeason.mapper.BaseSeasonMapper;
import vip.xiaonuo.modular.base.baseSeason.param.*;
import vip.xiaonuo.modular.base.baseSeason.service.BaseSeasonService;

import javax.validation.constraints.NotBlank;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.temporal.TemporalAdjusters;
import java.util.List;

/**
 * 季节Service接口实现类
 *
 * @author newspaper
 * @date  2023/12/18 11:14
 **/
@Service
public class BaseSeasonServiceImpl extends ServiceImpl<BaseSeasonMapper, BaseSeason> implements BaseSeasonService {
    @Override
    public BaseSeason getSeason(BaseSeasonTypeParam baseSeasonTypeParam) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
        LocalDate currentDate = LocalDate.now();
        // 获取下一年的二月的最后一天
        LocalDate nextYearFebruaryLastDay = currentDate
                .plusYears(1)          // 加一年
                .withMonth(Month.FEBRUARY.getValue())  // 设置月份为二月
                .with(TemporalAdjusters.lastDayOfMonth());  // 获取月份的最后一天

        String orgId = baseSeasonTypeParam.getOrgId();
        Integer seasonType = Integer.valueOf(baseSeasonTypeParam.getSeasonType());
        BaseSeason baseSeason = this.getOne(new QueryWrapper<BaseSeason>().lambda().eq(BaseSeason::getOrgId, orgId).eq(BaseSeason::getSeasonType, seasonType));
        if (ObjectUtil.isEmpty(baseSeason)){
            baseSeason = new BaseSeason();
            baseSeason.setOrgId(orgId);
            baseSeason.setSeasonType(seasonType);
            switch (seasonType){
                case 0:
                    break;
                case 1:
                    baseSeason.setSpringStartTime(sdf.parse("03-21"));
                    baseSeason.setSpringEndTime(sdf.parse("06-21"));
                    baseSeason.setSummerStartTime(sdf.parse("06-22"));
                    baseSeason.setSummerEndTime(sdf.parse("09-22"));
                    baseSeason.setAutumnStartTime(sdf.parse("09-23"));
                    baseSeason.setAutumnEndTime(sdf.parse("12-21"));
                    baseSeason.setWinterStartTime(sdf.parse("12-22"));
                    baseSeason.setWinterEndTime(sdf.parse("03-20"));
                    break;
                case 2:
                    baseSeason.setSpringStartTime(sdf.parse("03-01"));
                    baseSeason.setSpringEndTime(sdf.parse("05-31"));
                    baseSeason.setSummerStartTime(sdf.parse("06-01"));
                    baseSeason.setSummerEndTime(sdf.parse("08-31"));
                    baseSeason.setAutumnStartTime(sdf.parse("09-01"));
                    baseSeason.setAutumnEndTime(sdf.parse("11-30"));
                    baseSeason.setWinterStartTime(sdf.parse("12-01"));
                    baseSeason.setWinterEndTime(Date.valueOf(nextYearFebruaryLastDay));
                    break;
                case 3:
                    break;
            }

            this.save(baseSeason);
        }
        return baseSeason;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(BaseSeasonEditParam baseSeasonEditParam) throws ParseException {
        String orgId = StpLoginUserUtil.getLoginUser().getOrgId();
        Integer seasonType = baseSeasonEditParam.getSeasonType();
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
        LocalDate currentDate = LocalDate.now();
        // 获取下一年的二月的最后一天
        LocalDate nextYearFebruaryLastDay = currentDate
                .plusYears(1)          // 加一年
                .withMonth(Month.FEBRUARY.getValue())  // 设置月份为二月
                .with(TemporalAdjusters.lastDayOfMonth());  // 获取月份的最后一天

        BaseSeason baseSeason;
        Integer status = baseSeasonEditParam.getStatus();
        if (seasonType == 0){
//          自定义
            baseSeason = this.queryEntity(baseSeasonEditParam.getId());
            BeanUtil.copyProperties(baseSeasonEditParam, baseSeason);
            if (baseSeason.getStatus() == 1){
                this.update(new UpdateWrapper<BaseSeason>().lambda().set(BaseSeason::getStatus,0)
                        .eq(BaseSeason::getOrgId,baseSeason.getOrgId()).ne(BaseSeason::getId,baseSeason.getId()));
            }
            this.updateById(baseSeason);
        }else {
//          其他
            baseSeason = this.getOne(new QueryWrapper<BaseSeason>().lambda().eq(BaseSeason::getOrgId, orgId).eq(BaseSeason::getSeasonType, seasonType));
            if (ObjectUtil.isEmpty(baseSeason)){
//              没有此类型
                baseSeason = new BaseSeason();
                baseSeason.setSeasonType(seasonType);
                baseSeason.setStatus(status);
                if (status == 1){
                    this.update(new UpdateWrapper<BaseSeason>().lambda().set(BaseSeason::getStatus,0)
                            .eq(BaseSeason::getOrgId,orgId));
                }
                switch (seasonType){
//              0:自定义 1:两分两至法 2:阳历划分法 3:四立划分法
                    case 1:
                        baseSeason.setSpringStartTime(sdf.parse("03-21"));
                        baseSeason.setSpringEndTime(sdf.parse("06-21"));
                        baseSeason.setSummerStartTime(sdf.parse("06-22"));
                        baseSeason.setSummerEndTime(sdf.parse("09-22"));
                        baseSeason.setAutumnStartTime(sdf.parse("09-23"));
                        baseSeason.setAutumnEndTime(sdf.parse("12-21"));
                        baseSeason.setWinterStartTime(sdf.parse("12-22"));
                        baseSeason.setWinterEndTime(sdf.parse("03-20"));
                        break;
                    case 2:
                        baseSeason.setSpringStartTime(sdf.parse("03-01"));
                        baseSeason.setSpringEndTime(sdf.parse("05-31"));
                        baseSeason.setSummerStartTime(sdf.parse("06-01"));
                        baseSeason.setSummerEndTime(sdf.parse("08-31"));
                        baseSeason.setAutumnStartTime(sdf.parse("09-01"));
                        baseSeason.setAutumnEndTime(sdf.parse("11-30"));
                        baseSeason.setWinterStartTime(sdf.parse("12-01"));
                        baseSeason.setWinterEndTime(Date.valueOf(nextYearFebruaryLastDay));
                        break;
                    case 3:
                        break;
                }
                this.save(baseSeason);
            }else {
//              存在
                baseSeason.setStatus(status);
                if (status == 1){
                    this.update(new UpdateWrapper<BaseSeason>().lambda().set(BaseSeason::getStatus,0)
                            .eq(BaseSeason::getOrgId,orgId).ne(BaseSeason::getId,baseSeason.getId()));
                }
                this.updateById(baseSeason);
            }
        }
        CommonDataChangeEventCenter.doUpdateWithData(BaseDataTypeEnum.SEASON.getValue(), JSONUtil.createArray().put(baseSeason));
    }

    @Override
    public BaseSeason queryEntity(String id) {
        BaseSeason baseSeason = this.getById(id);
        if(ObjectUtil.isEmpty(baseSeason)) {
            throw new CommonException("季节不存在，id值为：{}", id);
        }
        return baseSeason;
    }

    @Override
    public Integer getEnableSeason(OrgIdParam orgIdParam) {
        String orgId = orgIdParam.getOrgId();
        Integer seasonType = new Integer(0);
        BaseSeason baseSeason = this.getOne(new QueryWrapper<BaseSeason>().lambda().eq(BaseSeason::getStatus, 1).eq(BaseSeason::getOrgId, orgId));
        if (ObjectUtil.isNotEmpty(baseSeason)){
            seasonType = baseSeason.getSeasonType();
        }
        return seasonType;
    }

}
