package com.dk.mdm.service.core;

import com.dk.common.infrastructure.annotaiton.Pagination;
import com.dk.common.infrastructure.enums.ErrorCodeEnum;
import com.dk.common.model.pojo.PageList;
import com.dk.common.response.ResponseResultUtil;
import com.dk.common.response.ResponseResultVO;
import com.dk.mdm.infrastructure.convert.core.FactoryConvert;
import com.dk.mdm.mapper.core.FactoryMapper;
import com.dk.mdm.model.pojo.core.Factory;
import com.dk.mdm.model.query.core.FactoryQuery;
import com.dk.mdm.model.response.core.FactoryResponse;
import com.dk.common.service.BaseService;
import com.dk.common.mapper.BaseMapper;
import com.dk.mdm.model.vo.core.FactoryVO;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class FactoryService extends BaseService<Factory> {

	@Override
	public BaseMapper<Factory> getRepository() {
		return factoryMapper;
	}

	@Autowired
	private FactoryMapper factoryMapper;

	@Autowired
	private FactoryConvert factoryConvert;

	/**
	 * @desc : 重写主键
	 * @author : 周兴
	 * @date : 2023/1/4 20:29
	 */
	@Override
	public String getPrimaryKey() {
		return "fty_id";
	}

	/**
	 * @desc : 条件查询
	 * @author : 周兴
	 * @date : 2023/1/4 9:27
	 */
	@Pagination
	public ResponseResultVO<PageList<FactoryResponse>> selectByCond(FactoryQuery factoryQuery) {
		return super.mergeListWithCount(factoryQuery, factoryMapper.selectByCond(factoryQuery), factoryMapper.countByCond(factoryQuery));
	}

	/**
	 * @desc   : 保存方法
	 * @author : 周兴
	 * @date   : 2023/1/4 9:27
	 */
	@Transactional(
			rollbackFor = {Exception.class}
	)
	public ResponseResultVO<?> insert(FactoryVO factoryVO) {
		// 转化实体
		Factory factory = factoryConvert.convertToPo(factoryVO);
		// 判断编码是否重复
		Long count = factoryMapper.selectByCode(factory);
		if(count > 0){
			return ResponseResultUtil.error(ErrorCodeEnum.FACTORY_CODE_EXISTS.getCode(),
					ErrorCodeEnum.FACTORY_CODE_EXISTS.getMessage());
		}
		return super.insert(factory);
	}

	/**
	 * @desc   : 编辑方法
	 * @author : 周兴
	 * @date   : 2023/1/4 9:27
	 */
	@Transactional(
			rollbackFor = {Exception.class}
	)
	public ResponseResultVO<Boolean> update(FactoryVO factoryVO) {
		// 转化实体
		Factory factory = factoryConvert.convertToPo(factoryVO);
		// 判断编码是否重复
		Long count = factoryMapper.selectByCode(factory);
		if(count > 0){
			return ResponseResultUtil.error(ErrorCodeEnum.FACTORY_CODE_EXISTS.getCode(),
					ErrorCodeEnum.FACTORY_CODE_EXISTS.getMessage());
		}
		return super.update(factory);
	}
}
