package com.njzscloud.common.sn;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njzscloud.common.core.ex.Exceptions;
import com.njzscloud.common.mp.support.PageParam;
import com.njzscloud.common.mp.support.PageResult;
import com.njzscloud.common.sn.contant.RollbackMode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.List;

/**
 * 递增编码表
 */
@Slf4j
public class IncSnService extends ServiceImpl<IncSnMapper, IncSnEntity> implements IService<IncSnEntity> {

    /**
     * 新增
     *
     * @param incSnEntity 数据
     */
    public void add(IncSnEntity incSnEntity) {
        this.save(incSnEntity);
    }

    /**
     * 修改
     *
     * @param incSnEntity 数据
     */
    public void modify(IncSnEntity incSnEntity) {
        this.updateById(incSnEntity);
    }

    /**
     * 删除
     *
     * @param ids Ids
     */
    @Transactional(rollbackFor = Exception.class)
    public void del(List<Long> ids) {
        this.removeBatchByIds(ids);
    }

    /**
     * 详情
     *
     * @param id Id
     * @return SysIncCodeEntity 结果
     */
    public IncSnEntity detail(Long id) {
        return this.getById(id);
    }

    /**
     * 分页查询
     *
     * @param incSnEntity 筛选条件
     * @param pageParam   分页参数
     * @return PageResult&lt;SysIncCodeEntity&gt; 分页结果
     */
    public PageResult<IncSnEntity> paging(PageParam pageParam, IncSnEntity incSnEntity) {
        return PageResult.of(this.page(pageParam.toPage(), Wrappers.<IncSnEntity>query(incSnEntity)));
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public Long inc(String code, String pici) {
        IncSnEntity incCodeEntity = this.getOne(Wrappers.<IncSnEntity>lambdaQuery()
                .eq(IncSnEntity::getCode, code));
        Assert.notNull(incCodeEntity, () -> Exceptions.exception("编码规则不存在"));
        long newVal = 0;

        long val = incCodeEntity.getVal();
        long maxVal = incCodeEntity.getMaxVal();

        if (val == maxVal) {
            Boolean allowOverflow = incCodeEntity.getAllowOverflow();
            if (allowOverflow == null) allowOverflow = Boolean.TRUE;
            if (allowOverflow) {
                newVal = incCodeEntity.getInitialVal();
            } else {
                throw Exceptions.exception("编码已到最大值，规则：{}，最大值：{}", code, maxVal);
            }
        }

        RollbackMode rollback = incCodeEntity.getRollback();
        if (rollback == null) rollback = RollbackMode.Wu;

        LocalDateTime now = LocalDateTime.now();
        LocalDateTime lastTime = incCodeEntity.getLastTime();
        if (lastTime == null) {
            lastTime = now;
        }

        switch (rollback) {
            case Wu: {
                newVal = val + incCodeEntity.getStep();
            }
            break;
            case Ri: {
                if (now.isBefore(lastTime)) {
                    throw Exceptions.exception("服务器时间回溯，无法生成编号");
                }
                LocalDateTime time1 = lastTime
                        .withHour(0).withMinute(0).withSecond(0).withNano(0); // 当天00:00:00

                LocalDateTime time2 = lastTime
                        .withHour(23).withMinute(59).withSecond(59).withNano(999_999_999); // 当天23:59:59.999999999

                if (time1.isBefore(time2)) {
                    newVal = incCodeEntity.getInitialVal();
                } else if (time1.isEqual(time2)) {
                    newVal = val + incCodeEntity.getStep();
                }
            }
            break;
            case Zhou: {
                if (now.isBefore(lastTime)) {
                    throw Exceptions.exception("服务器时间回溯，无法生成编号");
                }
                LocalDateTime time1 = lastTime
                        .with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY))
                        .withHour(0)
                        .withMinute(0)
                        .withSecond(0)
                        .withNano(0);
                LocalDateTime time2 = lastTime
                        .with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY))
                        .withHour(23)
                        .withMinute(59)
                        .withSecond(59)
                        .withNano(999_999_999);

                if (now.isBefore(time1) || now.isAfter(time2)) {
                    newVal = incCodeEntity.getInitialVal();
                } else {
                    newVal = val + incCodeEntity.getStep();
                }
            }
            break;
            case Yue: {
                if (now.isBefore(lastTime)) {
                    throw Exceptions.exception("服务器时间回溯，无法生成编号");
                }
                LocalDateTime time1 = lastTime
                        .with(TemporalAdjusters.firstDayOfMonth())
                        .withHour(0).withMinute(0).withSecond(0).withNano(0);
                LocalDateTime time2 = lastTime
                        .with(TemporalAdjusters.lastDayOfMonth())
                        .withHour(23).withMinute(59).withSecond(59).withNano(999_999_999);
                if (now.isBefore(time1) || now.isAfter(time2)) {
                    newVal = incCodeEntity.getInitialVal();
                } else {
                    newVal = val + incCodeEntity.getStep();
                }
            }
            break;
            case Nian: {
                if (now.isBefore(lastTime)) {
                    throw Exceptions.exception("服务器时间回溯，无法生成编号");
                }
                LocalDateTime time1 = lastTime
                        .with(TemporalAdjusters.firstDayOfYear())
                        .withHour(0).withMinute(0).withSecond(0).withNano(0);

                LocalDateTime time2 = lastTime
                        .with(TemporalAdjusters.lastDayOfYear())
                        .withHour(23).withMinute(59).withSecond(59).withNano(999_999_999);
                if (now.isBefore(time1) || now.isAfter(time2)) {
                    newVal = incCodeEntity.getInitialVal();
                } else {
                    newVal = val + incCodeEntity.getStep();
                }
            }
            break;
            case Pi: {
                Assert.notBlank(pici, () -> Exceptions.exception("批次号不能为空"));
                String lastPici = incCodeEntity.getLastPici();
                if (pici.equals(lastPici)) {
                    newVal = val + incCodeEntity.getStep();
                } else {
                    newVal = incCodeEntity.getInitialVal();
                }
            }
            break;
            default:
                throw Exceptions.exception("未知的回卷模式：{}", rollback);
        }

        this.updateById(new IncSnEntity().setId(incCodeEntity.getId())
                .setLastTime(now)
                .setLastPici(pici)
                .setVal(newVal));
        return newVal;
    }
}
