package com.ho.flow.common;

import com.ho.common.tools.constant.RedisKeyConstant;
import com.ho.common.tools.exception.BaseResponseCode;
import com.ho.common.tools.exception.BusinessException;
import com.ho.common.tools.service.RedisService;
import com.ho.common.tools.util.CodeUtil;
import com.ho.flow.constant.WorkOrderConstant;
import com.ho.flow.mapper.BusiIdControlMapper;
import com.ho.flow.vo.BusiIdControl;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author fancl
 * @desc:
 * @date 2023/1/23
 */
@Component
@Slf4j
public class FlowTool {

    @Autowired
    RedisService redisService;

    @Autowired
    BusiIdControlMapper busiMapper;

    @Autowired
    RedissonClient redissonClient;

    //获取工单id
    public String getNextWorkOrderId(String type) {
        //类型必须为已经定义的
        if (!WorkOrderConstant.IdTypeWorkOrder.equals(type)) {
            throw new BusinessException(BaseResponseCode.WORK_ORDER_ID_TYPE_NOT_RIGHT);
        }
        //定义锁
        RLock lock = null;
        //返回的工单号
        Long id = null;
        try {
            lock = redissonClient.getLock(RedisKeyConstant.LOCK_KEY_WORK_ORDER);
            //获取锁,没有获取到锁的阻塞在lock.lock() 这行
            lock.lock();
            BusiIdControl busiIdControl = busiMapper.selectByType(type);
            //首次直接变为2,因为1已经返回被使用了
            if (busiIdControl != null) {
                Long currentValue = busiIdControl.getCurrentValue();
                id = currentValue;
                //每次返回数值后+1
                busiIdControl.setCurrentValue(++currentValue);
                busiMapper.update(busiIdControl);
            } else {
                id = 1L;
                //没有对象，创建一条记录
                BusiIdControl busi = new BusiIdControl();
                busi.setIdType(type);
                busi.setCurrentValue(2L);
                busiMapper.insert(busi);
            }
        } finally {
            if (lock != null && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
        log.info("工单id: {}", id);
        String workSn = CodeUtil.getCode(CodeUtil.WORK_ORDER_PREFIX, String.valueOf(id), 10, "0");
        log.info("工单号: {}", workSn);
        return workSn;
    }
}
