package com.yeejoin.equipmanage.service.impl;

import com.yeejoin.equipmanage.common.entity.Equipment;
import com.yeejoin.equipmanage.common.entity.EquipmentCategory;
import com.yeejoin.equipmanage.mapper.EquipmentCategoryMapper;
import com.yeejoin.equipmanage.mapper.EquipmentMapper;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 生成装备定义code
 * @author as-wanglei
 *
 */
@Component
public class GenerateEquipmentCode {
	
	
	@Autowired
	private EquipmentMapper equipmentMapper;
	
	@Autowired
	private EquipmentCategoryMapper equipmentCategoryMapper;
	
	
	
	//装备分类Id
	private Long categoryId;
	
	//装备分类code长度
	private static final int CATECODELEN = 8;
	private String proviceCode ="44";
	
	/**
	 * 根据装备分类id生成装备定义code,装备分类code 8位，装备定义code 13位
	 * 生成规则暂定：
	 * 前8位为装备分类code，后5位随机
	 * 
	 * @param id 装备分类code
	 * @return 装备定义code
	 */
	public String generateEquipCode(Long categoryId){
		this.categoryId = categoryId;
		StringBuffer sbuffer = new StringBuffer();
		sbuffer.append(generatePrefix());
		sbuffer.append(generateSuffix());
		sbuffer.append(proviceCode);
		return sbuffer.toString();
	}
	/**
	 * 生成后缀，后缀不固定--目前随机生成
	 * @return
	 */
	private StringBuffer generateSuffix(){
		StringBuffer sbuffer = new StringBuffer();
		Map<String, Object> columnMap = new HashMap<String, Object>();
		columnMap.put("category_id", categoryId);
		List<Equipment> equipments = equipmentMapper.selectByMap(columnMap);
		
		//截取后5位
		List<String> codes = equipments.stream().map(e->e.getCode().substring(CATECODELEN,e.getCode().length()-2)).collect(Collectors.toList());
		//截取后5位
		String suffix = null;
		while(true){
			boolean same = false;
			suffix = RandomStringUtils.random(3, true, true);
//			suffix = RandomCodingUtil.generateShortCoding().substring(3).toUpperCase();
			for(String code : codes){
				if(code.equals(suffix)) {
					same = true;}
			}
			if(!same){
				break;
			}
		}
		sbuffer.append(suffix.toUpperCase());
		return sbuffer;
		
	}
	/**
	 * 生成前缀,前缀固定--为装备分类编码 8位
	 * @return
	 */
	private StringBuffer generatePrefix(){
		StringBuffer sbuffer = new StringBuffer();
		EquipmentCategory category = equipmentCategoryMapper.selectById(categoryId);
		if(category!=null){
			sbuffer.append(category.getCode());
		}
		return sbuffer;
	}
	
}

