package cn.net.cpzslibs.label;

import com.jymf.common.LableUtil;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

public class JPlabelUtil {
	
	private static final String LAB_PRE = "http://zs.jingpai.com/";
	
	private JPlabelUtil(){}
	
	public static String buildLabId(String year, long l){
		String lStr = String.valueOf(l);
		char[] yearNums = year.toCharArray();
		
		char[] labNums = new char[22];
		char[] lNums = lStr.toCharArray();
		char[] ckNums = LableUtil.getCheckNum(lStr).substring(lStr.length()).toCharArray();
		
		labNums[0] = String.valueOf(new Random().nextInt(9)+1).toCharArray()[0];
		labNums[1] = lNums[0];
		labNums[2] = String.valueOf(new Random().nextInt(10)).toCharArray()[0];
		labNums[3] = lNums[1];
		labNums[4] = String.valueOf(new Random().nextInt(10)).toCharArray()[0];
		labNums[5] = lNums[2];
		labNums[6] = String.valueOf(new Random().nextInt(10)).toCharArray()[0];
		labNums[7] = lNums[3];
		labNums[8] = lNums[4];
		labNums[9] = yearNums[0];
		labNums[10] = lNums[5];
		labNums[11] = lNums[6];
		labNums[12] = yearNums[1];
		labNums[13] = lNums[7];
		labNums[14] = lNums[8];
		labNums[15] = ckNums[0];
		labNums[16] = lNums[9];
		labNums[17] = ckNums[1];
		labNums[18] = lNums[10];
		labNums[19] = ckNums[2];
		labNums[20] = lNums[11];
		labNums[21] = ckNums[3];
		
		return new String(labNums);
	}
	
	public static void buildLabFile(long sNum, long eNum, long count){
	    File file = new File(String.format("D://zsm_%d_%d.txt", System.currentTimeMillis(), count));

	    if (!file.exists()) {
	      try {
	        file.createNewFile();
	      } catch (IOException e) {
	        e.printStackTrace();
	      }
	    }
		    
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
		String year = sdf.format(new Date()).substring(2, 4);
		
		BufferedWriter writer = null;
		try {
			writer = new BufferedWriter(new FileWriter(file));
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		
		for(long i=sNum; i<=eNum; i++){
			String lid = buildLabId(year, sNum);
			String labId = String.format("%s%s      %s%s", LAB_PRE, lid, LableUtil.getConsCode(lid),"\r\n");
			
			try {
				writer.write(labId);
			} catch (IOException e1) {
				e1.printStackTrace();
				try {
					writer.close();
				} catch (IOException e2) {
					e2.printStackTrace();
				}
			}
			
			sNum++;
		}
		
		try {
			writer.flush();
		} catch (IOException e1) {
			e1.printStackTrace();
		} finally{
			try {
				writer.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}
}
