package com.brilliance.isc.common.lock.impl;

import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import com.brilliance.isc.bo.Lck;
import com.brilliance.isc.common.lock.LockInfo;
import com.brilliance.isc.mda.dao.LckMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class LckComponent {
    private final Logger logger = LoggerFactory.getLogger(LckComponent.class);


    @Autowired
    private LckMapper lckMapper;

    public boolean tryInsert(LockInfo lockInfo) {
        Lck lck = lockInfo2Lck(lockInfo);
        try {
            int cnt = lckMapper.insert(lck);
            logger.info("锁定信息插入成功，影响行数:{}", cnt);
            return true;
        }catch(DuplicateKeyException e){
            logger.info("已存在锁{}",lockInfo.genLockKey());
        }
        finally {

        }
        return false;
    }

    public Lck lockInfo2Lck(LockInfo lockInfo){
        Lck dataLck = new Lck();
        dataLck.setLckdattim(new Date());
        dataLck.setLcktrn(lockInfo.getTrnName());
        dataLck.setLckusr(lockInfo.getUsrId());
        dataLck.setLckstr(lockInfo.genLockKey());
        if(lockInfo.isReentrant()){
            dataLck.setLckhld("");
        }else{
            dataLck.setLckhld("X");
        }
        return dataLck;
    }

    public LockInfo lck2Info(Lck dataLck){
        if(dataLck == null){
            return null;
        }
        LockInfo lockInfo = new LockInfo(dataLck.getLckstr());
        lockInfo.setTrnName(dataLck.getLcktrn());
        lockInfo.setUsrId(dataLck.getLckusr());

        if(dataLck.getLckhld() == null || dataLck.getLckhld().trim().isEmpty()){
            lockInfo.setReentrant(true);
        }else{
            lockInfo.setReentrant(false);
        }
        return lockInfo;
    }

    public LockInfo getLck(LockInfo lockInfo) {
        Lck lck = lckMapper.selectByLckStr(lockInfo.genLockKey());
        return lck2Info(lck);
    }

    public int deleteLck(LockInfo oldLockInfo) {
        return lckMapper.deleteByLckStr(oldLockInfo.genLockKey());
    }

    public int updateLockInfo(LockInfo lockInfo) {
        Lck lck = lockInfo2Lck(lockInfo);
        return lckMapper.updateLck(lck);
    }

    public int deleteLckByUserAndTrn(Lck lck) {
        return lckMapper.deleteLckByUserAndTrn(lck);
    }
}
