package com.brilliance.isc.common.wfmmod.service.impl;

import com.brilliance.isc.bo.Elccou;
import com.brilliance.isc.common.counter.service.CounterService;
import com.brilliance.isc.common.wfmmod.service.ElccouService;
import com.brilliance.isc.counter.config.CounterConfig;
import com.brilliance.isc.mda.dao.ElccouMapper;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.util.Date;

@Service
public class ElccouServiceImpl implements ElccouService {

    private Logger log = (Logger) LoggerFactory.getLogger(this.getClass());

    @Resource
    private ElccouMapper elccouMapper;
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private CounterService counterService;
    @Resource
    private CounterConfig counterConfig;


    /**
     * UNIQUE KEY `ELCCOU_IDX` (`COUDAT`,`COUNAM`)保证唯一
     * @param date
     * @param counam
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Override
    public long dbCounterELCCou(Date date, String counam) {
        Elccou elccou = elccouMapper.selectForUpdate(date, counam);
        if (null != elccou) {
            elccou.setCouval(elccou.getCouval() + elccou.getCoustp());
            elccouMapper.update(elccou);
            return elccou.getCouval();
        } else {
            try {
                elccou = new Elccou();
                elccou.setCoudat(date);
                elccou.setCounam(counam);
                elccou.setCoustp(counterConfig.getStep());
                elccou.setCouval(counterConfig.getStart());
                elccouMapper.insert(elccou);
                return elccou.getCouval();
            } catch (DuplicateKeyException se) {
                return dbCounterELCCou(date, counam);
            }
        }
    }
}
