package com.gic.haoban.manage.service.service.out.impl;

import com.gic.api.base.commons.Page;
import com.gic.commons.util.EntityUtil;
import com.gic.haoban.base.api.common.BasePageInfo;
import com.gic.haoban.common.utils.PageUtil;
import com.gic.haoban.common.utils.UuidUtil;
import com.gic.haoban.manage.api.dto.DictDTO;
import com.gic.haoban.manage.api.service.DictApiService;
import com.gic.haoban.manage.service.dao.mapper.DictMapper;
import com.gic.haoban.manage.service.entity.TabHaobanDict;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by tgs on 2020/2/9.
 */
@Service
public class DictApiServiceImpl implements DictApiService{
	@Autowired
	private DictMapper dictMapper;
	@Override
	public int saveDict(DictDTO dto) {
		if(StringUtils.isBlank(dto.getDictId())){
			//空，则新增
			dto.setDictId(UuidUtil.randomUUID());
			TabHaobanDict tab = EntityUtil.changeEntity(TabHaobanDict.class, dto);
			TabHaobanDict tab1 = dictMapper.selectByDictKey(dto.getDictKey());
			if(tab1!=null){
				return 8;
			}
			TabHaobanDict tab2 = dictMapper.selectByDictName(dto.getDictName());
			if(tab2!=null){
				return 9;
			}
			 dictMapper.insert(tab);
		}else{
			TabHaobanDict tab = EntityUtil.changeEntity(TabHaobanDict.class, dto);
			dictMapper.updateByPrimaryKeySelective(tab);
		}	
		return 1;
	}

	@Override
	public DictDTO findOneDict(String dictId) {
		TabHaobanDict tab = dictMapper.selectByPrimaryKey(dictId);
		if(tab == null){
			return null;
		}
		DictDTO dto = EntityUtil.changeEntity(DictDTO.class, tab);
		return dto;	
	}

	@Override
	public Page<DictDTO> pageList(BasePageInfo pageInfo) {
		PageHelper.startPage(pageInfo.getPageNum(), pageInfo.getPageSize());
		return PageUtil.changePageHelperToCurrentPage( dictMapper.pageList(),DictDTO.class);
	}

	@Override
	public void deleteOne(String dictId) {
		dictMapper.deleteByPrimaryKey(dictId);
	}

	@Override
	public List<DictDTO> queryList(List<String> dictKeys) {
		List<TabHaobanDict> list = dictMapper.queryList(dictKeys);
		return EntityUtil.changeEntityListByJSON(DictDTO.class, list);
	}

	@Override
	public DictDTO findOneDictByKey(String dictKey) {
		return EntityUtil.changeEntity(DictDTO.class, dictMapper.selectByDictKey(dictKey));
	}
}
