package com.yonge.cooleshow.biz.dal.service.impl;

import java.util.Date;
import java.util.List;

import com.yonge.cooleshow.biz.dal.enums.AppVersionStatusEnum;
import com.yonge.cooleshow.common.enums.YesOrNoEnum;
import com.yonge.toolset.mybatis.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yonge.cooleshow.biz.dal.dao.AppVersionInfoDao;
import com.yonge.cooleshow.biz.dal.entity.AppVersionInfo;
import com.yonge.cooleshow.biz.dal.service.AppVersionInfoService;
import com.yonge.toolset.mybatis.dal.BaseDAO;
import com.yonge.toolset.base.exception.BizException;

@Service
public class AppVersionInfoServiceImpl extends BaseServiceImpl<Long, AppVersionInfo> implements AppVersionInfoService {
	
	@Autowired
	private AppVersionInfoDao appVersionInfoDao;

	@Override
	public BaseDAO<Long, AppVersionInfo> getDAO() {
		return appVersionInfoDao;
	}

	@Override
	public List<AppVersionInfo> queryNewestByPlatform(String platform) {
		return appVersionInfoDao.queryNewestByPlatform(platform);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void add(AppVersionInfo appVersionInfo) {
		if(StringUtils.isEmpty(appVersionInfo.getPlatform())){
			throw new BizException("参数校验异常");
		}
		if (StringUtils.equals(appVersionInfo.getStatus(), "newest")) {
			//修改其他的为历史版本
			appVersionInfoDao.batchUpdateStatus(appVersionInfo.getPlatform());
		}
		appVersionInfoDao.insert(appVersionInfo);
	}

	@Override
	public void updateVersion(AppVersionInfo appVersionInfo) {
		if(StringUtils.isEmpty(appVersionInfo.getPlatform())){
			throw new BizException("参数校验异常");
		}
		if (StringUtils.equals(appVersionInfo.getStatus(), "newest")) {
			appVersionInfoDao.batchUpdateStatus(appVersionInfo.getPlatform());
		}
		appVersionInfo.setUpdateTime(new Date());
		appVersionInfoDao.update(appVersionInfo);
	}

	@Override
	public AppVersionInfo selectAppVersionInfo(String platform, String version) {
		return appVersionInfoDao.selectAppVersionInfo(platform, version);
	}

    @Override
    public YesOrNoEnum getAppAuditVersion(String platform, String version) {
		AppVersionInfo appVersionInfo = selectAppVersionInfo(platform, version);
		if (appVersionInfo != null
				&& AppVersionStatusEnum.AUDITING.getCode().equals(appVersionInfo.getStatus())) {
			return YesOrNoEnum.YES;
		} else {
			return YesOrNoEnum.NO;
		}
	}
}