package com.cwbuyer.code;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.cwbuyer.adapter.PricingAdapter.PriceData;
import com.cwbuyer.format.DefaultData;
import com.cwbuyer.format.EMode;
import com.cwbuyer.lib.Calculator;
import com.cwbuyer.lib.DBCloud;
import com.cwbuyer.lib.DBUtil;
import com.cwbuyer.lib.TbName;
import com.cwbuyer.lib.Utilis;
import com.pwbuyer.main.R;

// 定價策略
public class AddPricing  extends Activity{
	
	private final int COUNTRY_CODE = 1001;
	private int mMode = 0;
	private int mID = 0;
	private PriceData mData = null;

	//	0單機 1On_line 2.Off_line
	int of_line=Utilis.toInt(Utilis.getIni(AddPricing.this, "SYS", "IMPORT", 3));
	String mUid=Utilis.getIni(AddPricing.this, "SYS", "IMPORT", 2);  //ex:3g001
	
	private HashMap<Integer,Integer> mCountryIdList = new HashMap<Integer,Integer>();
	private ArrayList<Integer> mCountryId = new ArrayList<Integer>();
	private ArrayList<String> mCountryList = new ArrayList<String>();
	private ArrayList<String> mCountryIcon = new ArrayList<String>();
	private ArrayList<Double> mCountryRate = new ArrayList<Double>();
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == COUNTRY_CODE) {
			if (resultCode == RESULT_OK) {
				String pid = data.getStringExtra("country_pic");
				int id = data.getIntExtra("country_id", 1);
				double dRate = data.getDoubleExtra("country_rate", 1);
				mData.rate = dRate;
				try {
					mData.nCountry = id;
					((ImageView) findViewById(R.id.img_country))
							.setImageDrawable(Utilis.getResourceImage(
									AddPricing.this, pid));
					refreshCost();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_pricing);
		setTitle("訂價策略編輯");
		
		mID = getIntent().getIntExtra("id", 0);
		mMode = getIntent().getIntExtra("mode", 0);

		getCountryData(this);
		if(mMode == EMode.EDIT){
			if(mID != 0){
				getData(this);
			}
		}else{
			
			DefaultData defaultData = DBUtil.Default.getDefaultData(this);
			
			mData = new PriceData();
			
			if(defaultData != null){
				mData.nCountry = defaultData.nCountry;
				mData.country = defaultData.country; 
				int index = mCountryId.indexOf(mData.nCountry);
				if(index >= 0){
					((ImageView)findViewById(R.id.img_country)).setImageDrawable(Utilis.getResourceImage(this, mCountryIcon.get(index)));
				}
				mData.rate = defaultData.dBillRate;
//				((EditText)findViewById(R.id.edit_p5)).setText(""+mData.p5);
			}else{
				((ImageView)findViewById(R.id.img_country)).setImageDrawable(Utilis.getResourceImage(this, mCountryIcon.get(0)));
				mData.country = mCountryList.get(0);
				mData.nCountry = mCountryId.get(0);
			}
		}

		if(mData != null && mMode == EMode.EDIT){
			// 設定國家
			int index = mCountryIdList.get(mData.nCountry);
			String icon;
			icon = mCountryIcon.get(index);
			((ImageView)findViewById(R.id.img_country)).setImageDrawable(Utilis.getResourceImage(this, icon));
			((EditText)findViewById(R.id.edit_p0)).setText(""+mData.p0);
			((EditText)findViewById(R.id.edit_p1)).setText(""+mData.p1);
			((EditText)findViewById(R.id.edit_p2)).setText(""+mData.p2);
			((EditText)findViewById(R.id.edit_p3)).setText(""+mData.p3);
			((EditText)findViewById(R.id.edit_p4)).setText(""+mData.p4);
			((EditText)findViewById(R.id.edit_p5)).setText(""+mData.p5);
		}
		
		((EditText)findViewById(R.id.edit_p0)).addTextChangedListener(watcherPrice);
		
//		((EditText)findViewById(R.id.edit_p0)).setOnClickListener(mNumberListener);
//		((EditText)findViewById(R.id.edit_p1)).setOnClickListener(mNumberListener);
//		((EditText)findViewById(R.id.edit_p2)).setOnClickListener(mNumberListener);
//		((EditText)findViewById(R.id.edit_p3)).setOnClickListener(mNumberListener);
//		((EditText)findViewById(R.id.edit_p4)).setOnClickListener(mNumberListener);
//		((EditText)findViewById(R.id.edit_p5)).setOnClickListener(mNumberListener);
		((Button)findViewById(R.id.btn_next)).setOnClickListener(new MenuClick());
		((Button)findViewById(R.id.btn_save)).setOnClickListener(new MenuClick());
		((Button)findViewById(R.id.btn_exit)).setOnClickListener(new MenuClick());
		((ImageView)findViewById(R.id.img_country)).setOnClickListener(new MenuClick());
	}
	
	class MenuClick implements OnClickListener{
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			int id = v.getId();
			Utilis.runVibrate(AddPricing.this);
			switch(id){
				case R.id.btn_next:
				{
					if(saveData() == true){
						mMode = EMode.ADD;
						Toast.makeText(AddPricing.this, "下一筆資料記錄開始", Toast.LENGTH_SHORT).show();
					}
					break;
				}
				case R.id.btn_save:
					if(saveData() == true){
						finish();
					}
					break;
				case R.id.btn_exit:
					finish();
					break;
				case R.id.img_country:
				{
					Intent intent = new Intent();
					intent.setClass(AddPricing.this, CodeList.class);
					intent.putExtra("code_mode", CodeMode.COUNTRY);
					intent.putExtra("edit_mode", 1);
					AddPricing.this.startActivityForResult(intent, COUNTRY_CODE);
					break;
				}
			}
		}
	}
	public void getData(Context context){
		SQLiteDatabase db = Utilis.getDB(context);
		Cursor cursor = db.rawQuery("select * from qc_defpri where _id=" + mID, null);
		if(cursor != null){
			try{
				if(cursor.getCount() > 0){
					cursor.moveToFirst();
					mData = new PriceData();
					mData.id = cursor.getInt(cursor.getColumnIndex("_ID"));
					mData.nCountry = cursor.getInt(cursor.getColumnIndex("COUNTRY"));
					int index = mCountryIdList.get(mData.nCountry);
					if(index < 0){
						mData.country = "NO";
						mData.rate = 1;
					}else{
						mData.country = mCountryList.get(index);
						mData.rate = mCountryRate.get(index);
					}
					mData.p0 = cursor.getInt(cursor.getColumnIndex("P0"));
					mData.p1 = cursor.getInt(cursor.getColumnIndex("P1"));
					mData.p2 = cursor.getInt(cursor.getColumnIndex("P2"));
					mData.p3 = cursor.getInt(cursor.getColumnIndex("P3"));
					mData.p4 = cursor.getInt(cursor.getColumnIndex("P4"));
					mData.p5 = cursor.getInt(cursor.getColumnIndex("P5"));
				}
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				cursor.close();
				cursor = null;
			}
		}
		db.close();
		db = null;
	}
	
	// 取得國家資料
	public void getCountryData(Context context){
		if(mCountryIcon != null){
			mCountryIcon.clear();
		}
		if(mCountryList != null){
			mCountryList.clear();
		}
		SQLiteDatabase db = Utilis.getDB(context);
		Cursor cursor = db.rawQuery("select _ID,NAME,PIC,RATE from qc_country order by _ID", null);
		if(cursor != null){
			try{
				if(cursor.getCount() > 0){
					cursor.moveToFirst();
					for(int i = 0; i < cursor.getCount(); i++){
						int id = cursor.getInt(cursor.getColumnIndex("_ID"));
						mCountryIdList.put(id, i);
						mCountryId.add(id);
						String pic = cursor.getString(cursor.getColumnIndex("PIC"));
						String name = cursor.getString(cursor.getColumnIndex("NAME"));
						Double rate = cursor.getDouble(cursor.getColumnIndex("RATE"));
						mCountryIcon.add(pic);
						mCountryList.add(name);
						mCountryRate.add(rate);
						cursor.moveToNext();
					}
				}
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				cursor.close();
				cursor = null;
			}
		}
		db.close();
		db = null;
	}
	
	@SuppressWarnings("unused")
	private NumberClick mNumberListener = new NumberClick();
	class NumberClick implements OnClickListener{
		@Override
		public void onClick(View v) {
			int id = v.getId();
			Utilis.runVibrate(AddPricing.this);
//			DialogUtilis.showComputer(AddPricing.this,id);
			showComputer(id);
		}
	}
	
	
	private void showComputer(final int vid){
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		final View root = this.getLayoutInflater().inflate(R.layout.dlg_computer, null);
		final Calculator calu = new Calculator(AddPricing.this, root);
		final TextView print = (TextView)root.findViewById(R.id.text_print);
		String strValue = ((EditText)AddPricing.this.findViewById(vid)).getText().toString();
		if(strValue != null && strValue.length() > 0){
			print.setText(strValue);
//			calu.setBuffer(strValue);
		}
		
		dialog.setView(root);
		dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
	          public void onClick(DialogInterface dialog, int which) {
	        	  calu.resultNumber();
	        	  EditText edit = (EditText)AddPricing.this.findViewById(vid);
	        	  try{
	        		  String result = print.getText().toString();
	        		  if(result == null || result.length() <=0){
	        			  print.setText("0");
	        		  }else if(result.indexOf("+") > 0){
	        			  print.setText("0");
	        		  }else if(result.indexOf("-") > 0){
	        			  print.setText("0");
	        		  }else if(result.indexOf("×") > 0){
	        			  print.setText("0");
	        		  }else if(result.indexOf("÷") > 0){
	        			  print.setText("0");
	        		  }
	        		  edit.setText(print.getText().toString());
	        		  
	        		  if(vid == R.id.edit_p0){
	        			  // 重新計算成本
	        			  refreshCost();
	        		  }
	        	  }catch(Exception e){
	        		  e.printStackTrace();
	        	  }
	        	  calu.clear();
	          }
		});
		dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	          public void onClick(DialogInterface dialog, int which) {
	          }
			});
		dialog.show();
	}
	
	// 重新計算成本
	private void refreshCost(){
		double d0 = Utilis.toDouble(((EditText)findViewById(R.id.edit_p0)).getText().toString());
		double rate = mData.rate;
		int d1 = (int)(d0 * rate);
		((EditText)findViewById(R.id.edit_p1)).setText("" + d1);
	}
	
	private boolean saveData(){
		boolean succed=true;
		
		double p0 = Utilis.toDouble(((EditText)findViewById(R.id.edit_p0)).getText().toString());
		double p1 = Utilis.toDouble(((EditText)findViewById(R.id.edit_p1)).getText().toString());
		double p2 = Utilis.toDouble(((EditText)findViewById(R.id.edit_p2)).getText().toString());
		double p3 = Utilis.toDouble(((EditText)findViewById(R.id.edit_p3)).getText().toString());
		double p4 = Utilis.toDouble(((EditText)findViewById(R.id.edit_p4)).getText().toString());
		double p5 = Utilis.toDouble(((EditText)findViewById(R.id.edit_p5)).getText().toString());

		ContentValues value = new ContentValues();
		value.put("DEFPRI",p0);
		value.put("COUNTRY", mData.nCountry);
    	value.put("P0", p0);
    	value.put("P1", p1);
    	value.put("P2", p2);
    	value.put("P3", p3);
    	value.put("P4", p4);
    	value.put("P5", p5);
    	
		if (Utilis.haveInternet(this) && of_line!=0){  //有網路的狀態且非單機,優先雲端運算,再行Hander維護Client端
			StringBuffer bfstr = new StringBuffer();
			StringBuffer bfstrF = new StringBuffer();
					bfstr.append(mUid).append(";");
					bfstrF.append("UID").append(";");
					bfstr.append(mID).append(";");
					bfstrF.append("_ID").append(";");
					bfstr.append(p0).append(";");
					bfstrF.append("DEFPRI").append(";");
					bfstr.append(mData.nCountry).append(";");
					bfstrF.append("COUNTRY").append(";");
					bfstr.append(p0).append(";");
					bfstrF.append("P0").append(";");
					bfstr.append(p1).append(";");
					bfstrF.append("P1").append(";");
					bfstr.append(p2).append(";");
					bfstrF.append("P2").append(";");
					bfstr.append(p3).append(";");
					bfstrF.append("P3").append(";");
					bfstr.append(p4).append(";");
					bfstrF.append("P4").append(";");
					bfstr.append(p5);
					bfstrF.append("P5");
				Toast.makeText(this, "正前往雲端編輯_商品類別中,請稍候....", Toast.LENGTH_SHORT).show();
				Thread t = new Thread(new DBCloud.sendPostRunnableQC(this,bfstr.toString(),bfstrF.toString(),5));
				t.start();
    	}else if(mMode == EMode.ADD){
    		SQLiteDatabase db = Utilis.getDB(this);
	    	long result = db.insert(TbName.QC_DEFPRI, null, value);
	    	if(result > 0){
	    		Toast.makeText(this, "存取資料成功", Toast.LENGTH_SHORT).show();
	    	}else{
	    		Toast.makeText(this, "存取資料失敗", Toast.LENGTH_SHORT).show();
	    		succed =false;
	    	}
	    	db.close();
    	}else{  // EDIT
    		SQLiteDatabase db = Utilis.getDB(this);
    		String[] args = {String.valueOf(mID)};
			int success = db.update(com.cwbuyer.lib.TbName.QC_DEFPRI, value,
					"_ID=?", args);
			if(success > 0){
				Toast.makeText(this, "修改資料成功", Toast.LENGTH_SHORT).show();
			}else{
				Toast.makeText(this, "修改資料失敗", Toast.LENGTH_SHORT).show();
	    		succed =false;
			}
			db.close();
    	}
		value.clear();
		return succed;

	}
	
	private TextWatcher watcherPrice = new TextWatcher(){  
        @Override  
        public void afterTextChanged(Editable s) {  
        }  
        @Override  
        public void beforeTextChanged(CharSequence s, int start, int count,  
                int after) {  
        }  
        @Override  
        public void onTextChanged(CharSequence s, int start, int before,  
                int count) {
        	refreshCost();
        }  
    };
}
