package com.cwbuyer.lib;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

import com.cwbuyer.format.IDateDialog;
import com.pwbuyer.main.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;

@SuppressLint({ "SimpleDateFormat", "InflateParams" })
public class DateUtil {
	
	// 將時間轉換成 DateTime
	public static String getDateTime(Calendar calendar1) {
		StringBuilder resultStr = new StringBuilder().append("");
		Integer nYear = calendar1.get(Calendar.YEAR);
		Integer nMonth = calendar1.get(Calendar.MONTH);
		Integer nDay = calendar1.get(Calendar.DAY_OF_MONTH);
		Integer nHour = calendar1.get(Calendar.HOUR_OF_DAY);
		Integer nMinute = calendar1.get(Calendar.MINUTE);
		Integer nSecond = calendar1.get(Calendar.SECOND);
		resultStr = new StringBuilder().append(nYear).append("-")
				.append(Utilis.formatDate(nMonth + 1)).append("-")
				.append(Utilis.formatDate(nDay)).append(" ")
				.append(Utilis.formatDate(nHour)).append(":")
				.append(Utilis.formatDate(nMinute)).append(":")
				.append(Utilis.formatDate(nSecond));
		
		return resultStr.toString();
	}

	/* 計算兩個日期所差的天數 */
	public static long computerDiffTime(Calendar calendar1, Calendar calendar2) {
		long d1 = calendar1.getTimeInMillis() / 1000;
		long d2 = calendar2.getTimeInMillis() / 1000;
		long sec = 0;

		if (d2 > d1) {
			sec = d2 - d1;
		} else {
			sec = d1 - d2;
		}
		return sec;
	}

	/* 將秒數轉換成String 12:30:01 */
	public static String toTimeFormat(long sec) {
		StringBuffer buf = new StringBuffer();
		int nHour;
		int nMinute;
		
		nHour = (int) (sec / (60 * 60));
		sec = sec % (60 * 60);

		nMinute = (int) (sec / 60);
		sec = sec % 60;

		return buf.append(Utilis.formatDate(nHour)).append(":")
				.append(Utilis.formatDate(nMinute)).append(":")
				.append(Utilis.formatDate((int) sec)).toString();
	}
	
  /* 傳入日期如20090101及週期、格式字符串如yyyyMMdd回傳下次日期 */
  public static String getNextDate(String date, int period, String format) {
    int mYear = Integer.parseInt(date.substring(0, 4));
    int mMonth = Integer.parseInt(date.substring(4, 6));
    int mDay = Integer.parseInt(date.substring(6, 8));
    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(format);
    String nextDate = "";
    Calendar calendar = Calendar.getInstance();
    calendar.set(mYear, mMonth - 1, mDay);
    calendar.add(Calendar.DAY_OF_YEAR, period);
    nextDate = sdf.format(calendar.getTime());
    return nextDate;
  }
  
  //取得目前的日期
  @SuppressLint("SimpleDateFormat")
public static  String getFormatDate(){
	  final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
	     SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
	        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
	        Date today = Calendar.getInstance().getTime();
	        return dateFormat.format(today);
  }
  
  //取得目前的日期
  public static  String getCurrentDate(){
		StringBuilder resultStr = new StringBuilder().append("");
		Calendar c = Calendar.getInstance();
		Integer mYear = c.get(Calendar.YEAR);
		Integer mMonth = c.get(Calendar.MONTH);
		Integer mDay = c.get(Calendar.DAY_OF_MONTH);
		resultStr = new StringBuilder().append(mYear).append("/")
				.append(Utilis.formatDate(mMonth + 1)).append("/").append(Utilis.formatDate(mDay));
		return resultStr.toString();
  }
	
  //取得目前的日期
  public static  String getCurrentDateDb(){
		StringBuilder resultStr = new StringBuilder().append("");
		Calendar c = Calendar.getInstance();
		Integer mYear = c.get(Calendar.YEAR);
		Integer mMonth = c.get(Calendar.MONTH);
		Integer mDay = c.get(Calendar.DAY_OF_MONTH);
		resultStr = new StringBuilder().append(mYear).append("-")
				.append(Utilis.formatDate(mMonth + 1)).append("-").append(Utilis.formatDate(mDay));
		return resultStr.toString();
  }
  
  // 日期專用
  private static int mYear = 0;
  private static int mMonth = 0;
  private static int mDay = 0;
  
// 顯示 SpinerDialog
  @SuppressLint("InflateParams")
public static void showDateDialog(Context cnt, String title, Calendar c, final IDateDialog callback){
  	View view = LayoutInflater.from(cnt).inflate(R.layout.search_date_dialog, null, false);
  	mYear = c.get(Calendar.YEAR);
  	mMonth = c.get(Calendar.MONTH) + 1;
  	mDay = c.get(Calendar.DAY_OF_MONTH);
  	
  	DatePicker dp1 = (DatePicker)view.findViewById(R.id.dp1);
		dp1.init(mYear, mMonth - 1, mDay, new DatePicker.OnDateChangedListener() {
			@Override
			public void onDateChanged(DatePicker view, int year,
					int monthOfYear, int dayOfMonth) {
				mYear = year;
				mMonth = monthOfYear + 1;  //注意 : 不加的話當資料變動會少一個月
				mDay = dayOfMonth;
			}
		});
  	
		new AlertDialog.Builder(cnt).setTitle(title)
		.setView(view)
		.setPositiveButton("確認", new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int which) {
          	String startDay = "" + mYear + "-" + Utilis.formatDate("" + mMonth) + "-" + Utilis.formatDate("" + mDay);
          	callback.onDateDialogFinish(startDay, mYear, mMonth, mDay);
          }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int which) {
          }
        }).show();
  }
	
	// RETURN  1  前面的時間比較大
	// RETURN  -1 後面的時間比較大
	// RETURN  0  時間一樣
	  public static int compareTime(String date1, String date2){
			try{
				if(date1 == null && date2 == null){
					return 0;
				}else if(date1 == null && date2 != null){
					return -1;
				}else if(date1 != null && date2 == null){
					return 1;
				}
				if(date1.length() > 0 && date2.length() > 0){
					long lTime1 = toFormatTime (date1);
					long lTime2 = toFormatTime (date2);
					
					if(lTime1 > lTime2){
						return 1;
					}else if(lTime1 == lTime2){
						return 0;
					}else{ 
						return -1;
					}
				}else{
					if(date1.length() <= 0 && date2.length() <= 0){
						return 0;
					}else if(date1.length() > 0){
						return 1;
					}else{
						return -1;
					}
				}
			}catch(Exception e){
				return 1;
			}
		}
	  
	  // 2012/07/04
	  // 之後要再寫得更嚴謹
	  public static String toDBDate(String mDate){
		  return mDate.replace("/", "-");
	  }
	  
	  public static long toFormatTime(String time){
			// date = new String ("2011/01/06 12:31")
			//GregorianCalendar 注意月份的表示 一月是 0 二月是 1 , 以此類推 十二月是 11
			GregorianCalendar calendar = new GregorianCalendar(
				 Integer.parseInt(time.substring(0,4)),   // year
				 Integer.parseInt(time.substring(5,7)) - 1,   // month
				 Integer.parseInt(time.substring(8,10)),  // day
				 0, // hour
				 0, // minute
				 0); // second
			Date date = calendar.getTime();
			long lTime = date.getTime();
			return lTime;
		}
	  
	  // 取得日期差
	  public static int getDifferDay(String dateString1, String dateString2){
		  int diff = 0;
		  try{
			  SimpleDateFormat  sdf = new SimpleDateFormat( "yyyy/MM/dd");
			  Date   date1 =  sdf.parse(dateString1); 
			  Date   date2 =  sdf.parse(dateString2); 
			  diff = (int)((date1.getTime() -date2.getTime())/(1000*3600*24));
		  }catch(Exception e){
		  }
		  return diff;
	  }

	// 取得目前的日期不含符號
	public static  String getCurrentDateFormat(){
		StringBuilder resultStr = new StringBuilder().append("");
		Calendar c = Calendar.getInstance();
		Integer mYear = c.get(Calendar.YEAR);
		Integer mMonth = c.get(Calendar.MONTH);
		Integer mDay = c.get(Calendar.DAY_OF_MONTH);
		resultStr = new StringBuilder().append(mYear).append(Utilis.formatDate(mMonth + 1)).append(Utilis.formatDate(mDay));
		return resultStr.toString();
	}
	
	// 取得目前的日期不含符號  且年度只有後1碼
	public static  String getCurrentYearFormat1(){
		StringBuilder resultStr = new StringBuilder().append("");
		Calendar c = Calendar.getInstance();
		int mYear = c.get(Calendar.YEAR);
		int mMonth = c.get(Calendar.MONTH);
		int mDay = c.get(Calendar.DAY_OF_MONTH);
		resultStr = new StringBuilder().append((mYear % 100)).append(Utilis.formatDate(mMonth + 1)).append(Utilis.formatDate(mDay));
		return resultStr.toString();
	}
	
	// 取得當月的最後一天
	public static  String getCurrentLastDate(){
		StringBuilder resultStr = new StringBuilder().append("");
		Calendar c = Calendar.getInstance();
		c.set(Calendar.DAY_OF_MONTH, 1);
		c.add(Calendar.MONTH, 1);
		c.add(Calendar.DATE, -1);   // 關鍵
		
		Integer mYear = c.get(Calendar.YEAR);
		Integer mMonth = c.get(Calendar.MONTH);
		Integer mDay = c.get(Calendar.DAY_OF_MONTH);
		
		resultStr = new StringBuilder().append(mYear).append("/")
				.append(Utilis.formatDate(mMonth + 1)).append("/").append(Utilis.formatDate(mDay));
		return resultStr.toString();
	}
	
	
	// 如果更新日期 < now 才要去更新
	public static boolean compareDate(String now, String cdate){
		try{
			String[] timeNow = now.split("/");
			String[] time2 = cdate.split("/");
			
			if(Integer.valueOf(time2[0]) < Integer.valueOf(timeNow[0])){
				// 比較年
				return true;
			}else if(Integer.valueOf(time2[1]) < Integer.valueOf(timeNow[1])){
				// 比較月
				return true;
			}else if(Integer.valueOf(time2[2]) < Integer.valueOf(timeNow[2])){
				// 比較日
				return true;
			}else{
				return false;
			}
		}catch(Exception e){
			return false;
		}
	}

	// 如果更新日期 < now 才要去更新
	public static boolean compare_Date(String now, String cdate){
		try{
			String[] timeNow = now.split("-");
			String[] time2 = cdate.split("-");
			
			if(Integer.valueOf(time2[0]) < Integer.valueOf(timeNow[0])){
				// 比較年
				return true;
			}else if(Integer.valueOf(time2[1]) < Integer.valueOf(timeNow[1])){
				// 比較月
				return true;
			}else if(Integer.valueOf(time2[2]) < Integer.valueOf(timeNow[2])){
				// 比較日
				return true;
			}else{
				return false;
			}
		}catch(Exception e){
			return false;
		}
	}
	
	
	
	public static String getCurrentTime(){
		StringBuffer buf = new StringBuffer();
		Calendar c = Calendar.getInstance();
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH);
		int day = c.get(Calendar.DAY_OF_MONTH);
		int hour = c.get(Calendar.HOUR);
		int minute = c.get(Calendar.MINUTE);
		
		buf.append(year).append("/").append(month+1).append("/").append(day).append(" ");
		buf.append(hour).append(":").append(minute);
		
		return buf.toString();
	}
	
  
	
  // 增加日期
  public static String addDate(String date, int value){
	  try {
			int s=0; // "-"=1
			if (date.indexOf("-")>0) s=1;
			String[] dates;
			if (s==0) dates = date.split("/"); else dates = date.split("-"); 
			Calendar time = Calendar.getInstance();
			time.set(Calendar.YEAR, Integer.valueOf(dates[0]));
			time.set(Calendar.MONTH, Integer.valueOf(dates[1]) - 1);
			time.set(Calendar.DAY_OF_MONTH, Integer.valueOf(dates[2]));
			// 加了客戶等級的提示日期
			time.add(Calendar.DAY_OF_YEAR, value);

			int year = time.get(Calendar.YEAR);
			int month = time.get(Calendar.MONTH) + 1;
			int day = time.get(Calendar.DAY_OF_MONTH);
				return "" + year + "/" + Utilis.formatDate(month) + "/"
						+ Utilis.formatDate(day);
		} catch (Exception e) {
			return "";
		}  
  }
  
  // 增加月
  public static String addMonth(String date, int value){
	try {
		int s=0; // "-"=1
		if (date.indexOf("-")>0) s=1;
		String[] dates;
		if (s==0) dates = date.split("/"); else dates = date.split("-"); 
		Calendar time = Calendar.getInstance();
		time.set(Calendar.YEAR, Integer.valueOf(dates[0]));
		time.set(Calendar.MONTH, Integer.valueOf(dates[1])-1);
		time.set(Calendar.DAY_OF_MONTH, 1);
		time.add(Calendar.MONTH, value);
		time.add(Calendar.DATE, -1);   // 關鍵

		int year = time.get(Calendar.YEAR);
		int month = time.get(Calendar.MONTH);
		int day = time.get(Calendar.DAY_OF_MONTH);

		return "" + year + "/" + Utilis.formatDate(month + 1) + "/"
				+ Utilis.formatDate(day);
	} catch (Exception e) {
		return "";
	}
  }
  
  // 增加月
  public static String addMonth(String date, int value, boolean toFirst){
	try {
		int s=0; // "-"=1
		if (date.indexOf("-")>0) s=1;
		String[] dates;
		if (s==0) dates = date.split("/"); else dates = date.split("-"); 
		Calendar time = Calendar.getInstance();
		time.set(Calendar.YEAR, Integer.valueOf(dates[0]));
		time.set(Calendar.MONTH, Integer.valueOf(dates[1])-1);
		time.set(Calendar.DAY_OF_MONTH, Integer.valueOf(dates[2]));
		// 加了客戶等級的提示日期
		time.add(Calendar.MONTH, value);
		if(toFirst == true){
			time.set(Calendar.DAY_OF_MONTH, 1);
		}

		int year = time.get(Calendar.YEAR);
		int month = time.get(Calendar.MONTH);
		int day = time.get(Calendar.DAY_OF_MONTH);

		return "" + year + "/" + Utilis.formatDate(month + 1) + "/"
				+ Utilis.formatDate(day);
	} catch (Exception e) {
		return "";
	}
  }
  

  // 回傳系統時間至豪秒  201206061625000
  public static String getSystemTime(){
	  long currentTimeMillis = System.currentTimeMillis();
	  Date date = new Date(currentTimeMillis);
	  SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yMMddHHmmssSSS");
      String times = simpleDateFormat.format(date);
      return times;
  }

  /* 計算兩個日期所差的天數 */
  public static int computerDiffDate(long date1, long date2) {
    Calendar calendar1 = Calendar.getInstance();
    calendar1.setTimeInMillis(date1);

    Calendar calendar2 = Calendar.getInstance();
    calendar2.setTimeInMillis(date2);
    /* 先判斷是否同年 */
    int y1 = calendar1.get(Calendar.YEAR);
    int y2 = calendar2.get(Calendar.YEAR);

    int d1 = calendar1.get(Calendar.DAY_OF_YEAR);
    int d2 = calendar2.get(Calendar.DAY_OF_YEAR);
    int maxDays = 0;
    int day = 0;
    if (y1 - y2 > 0) {
      maxDays = calendar2.getActualMaximum(Calendar.DAY_OF_YEAR);
      day = d1 - d2 + maxDays;
    } else if (y1 - y2 < 0) {
      maxDays = calendar1.getActualMaximum(Calendar.DAY_OF_YEAR);
      day = d1 - d2 - maxDays;
    } else {
      day = d1 - d2;
    }
    return day;
  }
  
  /* 計算兩個日期所差的天數 */
  public static long computerDiffTime(long time1, long time2) {
    Calendar calendar1 = Calendar.getInstance();
    calendar1.setTimeInMillis(time1);

    Calendar calendar2 = Calendar.getInstance();
    calendar2.setTimeInMillis(time2);

    long d1 = calendar1.getTimeInMillis() / 1000;
    long d2 = calendar2.getTimeInMillis() / 1000;
    long sec = 0;

    if (d2 > d1) {
      sec = d2 - d1;
    } else {
      sec = d1 - d2;
    }
    
    return sec;
  }

  /* 傳入日期如20090101回傳日期的long值 */
  public static long getDateTime(String strDate) {
    return getDateByFormat(strDate, "yyyyMMdd").getTime();
  }

  /* 傳入日期的long值及格式字符串如yyyyMMdd */
  public static String getDateTime(String format, long millis) {
    java.util.Calendar calendar = java.util.Calendar.getInstance();
    calendar.setTimeInMillis(millis);
    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(format);
    return (sdf.format(calendar.getTime()));
  }

  public static int [] showSeason(final Context context,final int vid,final String batchPic,int aYear,int aSeason,final int mode){
	  	final int [] YN={aYear,aSeason};
        String [] mYear = new String[50];
        int addyear = 2012;
        for(int i = 0; i < 50; i ++){
        	mYear[i] = "" + (addyear + i);
        }
    	String[] mSeason = new String[]{"春天","夏天","秋天","冬天","四季"};
        
	  	
		AlertDialog.Builder dialog = new AlertDialog.Builder(context);
		final View root = ((Activity) context).getLayoutInflater().inflate(R.layout.dlg_season, null);
		ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(context, android.R.layout.simple_spinner_item, mSeason);
		adapter.setDropDownViewResource(R.layout.sst_simple_dropdown_item);
		Spinner spinner = (Spinner)root.findViewById(R.id.spinner_season);
		spinner.setAdapter(adapter);
		spinner.setSelection(aSeason);
		
		ArrayAdapter<CharSequence> adapterYeaer = new ArrayAdapter<CharSequence>(context, android.R.layout.simple_spinner_item, mYear);
		adapter.setDropDownViewResource(R.layout.sst_simple_dropdown_item);
		Spinner spinnerYear = (Spinner)root.findViewById(R.id.spinner_year);
		spinnerYear.setAdapter(adapterYeaer);
		spinnerYear.setSelection(getYearSelect(mYear,aYear));
		// 限制最多只能三個字
		dialog.setView(root);
		dialog.setTitle("選擇年度季節");
		dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
	          public void onClick(DialogInterface dialog, int which) {
	              String mYear [] = new String[50];
	              int addyear = 2012;
	              for(int i = 0; i < 50; i ++){
	              	mYear[i] = "" + (addyear + i);
	              }
	          		String[] mSeason = new String[]{"春天","夏天","秋天","冬天","四季"};
	        	  
	        	  Spinner spinnerYear = (Spinner)root.findViewById(R.id.spinner_year);
	        	  Spinner spinner = (Spinner)root.findViewById(R.id.spinner_season);
	        	  int aSeason = spinner.getSelectedItemPosition();
	        	  int aYear = Utilis.toInt(mYear[spinnerYear.getSelectedItemPosition()]);
	        	  YN[0]=aYear;
	        	  YN[1]=aSeason;
	        	  if (mode==0){
	        		  EditText edit = (EditText)((Activity) context).findViewById(vid);
	        		  edit.setText(""+mYear[spinnerYear.getSelectedItemPosition()] + "/"+ mSeason[spinner.getSelectedItemPosition()]);
	        	  }else if (mode==1){
	        		  Button edit = (Button)((Activity) context).findViewById(vid);
		        	  edit.setText(""+mYear[spinnerYear.getSelectedItemPosition()] + "/"+ mSeason[spinner.getSelectedItemPosition()]);
	        	  }else if (mode==2){
						SQLiteDatabase db = Utilis.getDB(context);
						try{
							db.beginTransaction();
							db.execSQL("update qdetail set UNIT2='"+YN[0]+"',SEASON='"+YN[1]+"' where BATCH='"+batchPic+"'");
							db.execSQL("update qitems set YEAR='"+YN[0]+"',SEASON='"+YN[1]+"' where BATCH='"+batchPic+"'");
				            db.setTransactionSuccessful();
						}
						catch(Exception e){
						}finally{
							db.endTransaction();
						}
						db.close();
	        	  }
	          }
		});
		dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	          public void onClick(DialogInterface dialog, int which) {
	          }
			});
		dialog.show();

		return YN; 
	}
  
  public static int getYearSelect(String mYear[],int year){
  	int index = 0;
  	boolean bFind = false;
  	String strYear = "" + year;
  	for(int i = 0; i < 50  &&  bFind == false; i ++ ){
  		if(mYear[i].equalsIgnoreCase(strYear)){
  			bFind = true;
  			index = i;
  		}
  	}
  	return index;
  }

  
  public static int [] getYearSeason(String format, long millis) {
	  int [] YS={4,2017};
	  
	  
	  
	    return YS;
	  }
  
  public static Date getDateByFormat(String strDate, String format) {
    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(format);
    try {
      return (sdf.parse(strDate));
    } catch (ParseException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return null;
    }
  }
}
