package com.lightinit.hsdataplatformresdir.impl;

import com.lightinit.hsdataplatformresdir.mapper.SecurekeyMapper;
import com.lightinit.hsdataplatformresdir.entity.BaseExample;
import com.lightinit.hsdataplatformresdir.entity.Securekey;
import com.lightinit.hsdataplatformresdir.service.ISecureKeyService;
import com.lightinit.hsdataplatformresdir.spring.DynamicDataContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * Created by Lantinit on 2018/1/31.
 */
@Service
public class SecureKeyServiceImpl implements ISecureKeyService {
    @Autowired
    private SecurekeyMapper securekeyMapper;
    @Override
    public long QueryCount(String keyword) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        BaseExample example=new BaseExample();
        return securekeyMapper.countByExample(example);
    }

    @Override
    public List<Securekey> QueryList(String keyword, int page, int rows) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        BaseExample example=new BaseExample();
        example.setOrderByClause("SecureKeyID desc");
        BaseExample.Page _page=new BaseExample.Page();
        if(rows>0) {
            _page.setPageSize(rows);
            _page.setPageNo(page);
            example.setPage(_page);
        }
        return securekeyMapper.selectByExample(example);
    }

    @Override
    public boolean Update(Securekey record) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return securekeyMapper.updateByPrimaryKey(record)>0;
    }

    @Override
    public boolean Delete(long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return securekeyMapper.deleteByPrimaryKey(id)>0;
    }

    @Override
    public boolean Insert(Securekey record) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return securekeyMapper.insert(record)>0;
    }

    @Override
    public Securekey QueryOne(long id) {
        return securekeyMapper.selectByPrimaryKey(id);
    }

    @Override
    public Securekey QueryOne(String username) {
        if(StringUtils.isEmpty(username))
            return null;
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        BaseExample example=new BaseExample();
        example.setOrderByClause("SecureKeyID desc");
        example.setWhereClause("UserName='"+username+"' AND ExpiresDateTime>=NOW()");
        BaseExample.Page _page=new BaseExample.Page();
        _page.setPageSize(1);
        _page.setPageNo(1);
        example.setPage(_page);
        List<Securekey> securekeyList=securekeyMapper.selectByExample(example);
        return (securekeyList!=null && securekeyList.size()>0)?securekeyList.get(0):null;
    }
}
