package cn.ibizlab.businesscentral.core.extensions.service;

import cn.ibizlab.businesscentral.core.odoo_ir.domain.Ir_sequence_date_range;
import cn.ibizlab.businesscentral.core.odoo_ir.filter.Ir_sequence_date_rangeSearchContext;
import cn.ibizlab.businesscentral.core.odoo_ir.service.impl.Ir_sequenceServiceImpl;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import cn.ibizlab.businesscentral.core.odoo_ir.domain.Ir_sequence;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Primary;

import java.sql.Timestamp;
import java.util.*;

/**
 * 实体[序列] 自定义服务对象
 */
@Slf4j
@Primary
@Service("Ir_sequenceExService")
public class Ir_sequenceExService extends Ir_sequenceServiceImpl {

    @Override
    protected Class currentModelClass() {
        return com.baomidou.mybatisplus.core.toolkit.ReflectionKit.getSuperClassGenericType(this.getClass().getSuperclass(), 1);
    }

    /**
     * 自定义行为[Alter_sequence]用户扩展
     *
     * @param et
     * @return
     */
    @Override
    @Transactional
    public Ir_sequence alter_sequence(Ir_sequence et) {
        String select_sequence = String.format("select relname from pg_class where relkind='S' and relname='ir_sequence_%03d'", "S", et.getId());
        List<JSONObject> sequences = this.select(select_sequence, null);
        if (sequences.size() == 0)
            return et;
        StringBuffer alert_swquence = new StringBuffer();
        alert_swquence.append(String.format("alter sequence ir_sequence_%03d", et.getId()));
        if (et.getNumberIncrement() != null)
            alert_swquence.append(String.format(" increment by %d", et.getNumberIncrement()));
        if (et.getNumberNext() != null)
            alert_swquence.append(String.format(" restart with %d", et.getNumberNext()));
        this.select(alert_swquence.toString(), null);
        return super.alter_sequence(et);
    }

    /**
     * 自定义行为[Create_sequence]用户扩展
     *
     * @param et
     * @return
     */
    @Override
    @Transactional
    public Ir_sequence create_sequence(Ir_sequence et) {
        String create_sequence = String.format("create sequence ir_sequence_%03d increment by %s start with %s", et.getId(), et.getNumberIncrement(), et.getNumberNext());
        this.select(create_sequence, null);
        return super.create_sequence(et);
    }

    /**
     * 自定义行为[Drop_sequence]用户扩展
     *
     * @param et
     * @return
     */
    @Override
    @Transactional
    public Ir_sequence drop_sequence(Ir_sequence et) {
        String drop_sequence = String.format("drop sequence if exists ir_sequence_%03d restrict ", et.getId());
        this.select(drop_sequence, null);
        return super.drop_sequence(et);
    }

    /**
     * 自定义行为[Get_next]用户扩展
     *
     * @param et
     * @return
     */
    @Override
    @Transactional
    public Ir_sequence get_next(Ir_sequence et) {
        if (et.getUseDateRange() == null && !et.getUseDateRange()) {
            int number_next = 0;
            //标准 序列
            if (StringUtils.compare(et.getImplementation(), "standard") == 0) {
                this.select_nextval(et);
                number_next = et.getNextVal();
            } else {
                //no_gap
                this.update_nogap(et);
                number_next = et.getNumberNext();
            }
            et.setNextChar(String.format("%s%s%s", et.getPrefix() == null ? "" : et.getPrefix(), String.format("%0" + et.getPadding() + "d", number_next), et.getSuffix() == null ? "" : et.getSuffix()));
        } else {
            if (true)
                throw new RuntimeException("暂未实现");
            Timestamp seq_date = et.get("sequence_date") == null ? null : (Timestamp) et.get("sequence_date");
            // 带有时间范围
            Ir_sequence_date_rangeSearchContext ctx = new Ir_sequence_date_rangeSearchContext();
            ctx.setN_sequence_id_eq(et.getId());

            List<Ir_sequence_date_range> sequence_date_ranges = irSequenceDateRangeService.searchDefault(ctx).getContent();
            Ir_sequence_date_range sequence_date_range = null;
            if (sequence_date_ranges.size() == 0) {
                sequence_date_range = new Ir_sequence_date_range();
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.MONTH, 0);
                calendar.set(Calendar.DAY_OF_MONTH, 0);
                calendar.set(Calendar.HOUR, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MILLISECOND, 0);
                sequence_date_range.setDateFrom(new Timestamp(calendar.getTimeInMillis()));
                calendar.add(Calendar.YEAR, 1);
                calendar.add(Calendar.DAY_OF_MONTH, -1);
                sequence_date_range.setDateTo(new Timestamp(calendar.getTimeInMillis()));
                sequence_date_range.setSequenceId(et.getId());
                sequence_date_range.setNumberNext(0);
                irSequenceDateRangeService.create(sequence_date_range);
            } else {
                sequence_date_range = sequence_date_ranges.get(0);
            }
            int number_next = 0;
            //标准 序列
            if (StringUtils.compare(et.getImplementation(), "standard") == 0) {
                irSequenceDateRangeService.select_nextval(sequence_date_range);
                number_next = sequence_date_range.getNextVal();
            } else {
                //no_gap
                irSequenceDateRangeService.update_nogap(sequence_date_range);
                number_next = sequence_date_range.getNextVal();
            }
            et.setNextChar(String.format("%s%s%s", et.getPrefix() == null ? "" : et.getPrefix(), String.format("%0" + et.getPadding() + "d", number_next), et.getSuffix() == null ? "" : et.getSuffix()));
        }

        return super.get_next(et);
    }

    /**
     * 自定义行为[Get_next_by_code]用户扩展
     *
     * @param et
     * @return
     */
    @Override
    @Transactional
    public Ir_sequence get_next_by_code(Ir_sequence et) {
        if (false) {
            et.setCompanyId(0l);
        }

        et = this.getOne(new QueryWrapper<Ir_sequence>().setEntity(et));

        return super.get_next(et);
    }

    /**
     * 自定义行为[Predict_nextval]用户扩展
     *
     * @param et
     * @return
     */
    @Override
    @Transactional
    public Ir_sequence predict_nextval(Ir_sequence et) {
        return super.predict_nextval(et);
    }

    /**
     * 自定义行为[Select_nextval]用户扩展
     *
     * @param et
     * @return
     */
    @Override
    @Transactional
    public Ir_sequence select_nextval(Ir_sequence et) {
        List<JSONObject> data = this.select(String.format("SELECT nextval('ir_sequence_%03d')", et.getId()), null);
        int nextval = data.get(0).getInteger("nextval");
        et.setNextVal(nextval);
        return super.select_nextval(et);
    }

    /**
     * 自定义行为[Update_nogap]用户扩展
     *
     * @param et
     * @return
     */
    @Override
    @Transactional
    public Ir_sequence update_nogap(Ir_sequence et) {
        et.setNumberNext(et.getNumberNext() + et.getNumberIncrement());
        this.update(et);
        return super.update_nogap(et);
    }
}

