package com.cwbuyer.main;

import java.util.ArrayList;
import java.util.LinkedList;
import android.annotation.SuppressLint;
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.InputFilter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.cwbuyer.code.CodeList;
import com.cwbuyer.code.CodeMode;
import com.cwbuyer.format.DefaultData;
import com.cwbuyer.format.EMode;
import com.cwbuyer.lib.AccountUtil;
import com.cwbuyer.lib.Calculator;
import com.cwbuyer.lib.DBUtil;
import com.cwbuyer.lib.DateUtil;
import com.cwbuyer.lib.Utilis;
import com.cwbuyer.main.ManageAccount.AccountData;
import com.pwbuyer.main.R;

// 預設參數
@SuppressLint("InflateParams")
public class AParam  extends Activity {
	
	private int COUNTRY_CODE = 1001;
    
	private ArrayList<String> mCountryList = new ArrayList<String>();
	private ArrayList<String> mCountryIcon = new ArrayList<String>();
	private ArrayList<Integer> mCountryId = new ArrayList<Integer>();
	private LinkedList<AccountData> mAccountList = null;
	private DefaultData mData = null;
	
	private String[] mProductStrs = new String[]{"自訂_空白", "來源編號 + 流水號", "廠商編號 + 來源編號", "廠商編號 + 流水號", "批號  + 流水號", "與來源編號同", "廠商編號 + 批號 + 流水號","年度季別+流水號"};
	private String[] mFirstStrs = new String[]{"拍照","廠商編號","來源編號","商品編號","商品類別","進價"};
	private String[] mSeason = new String[]{"春天","夏天","秋天","冬天","四季"};
	private String[] mYear = new String[]{"2012","2013","秋天","冬天"};
	private String[] mAccount;
	
	private int mSpinnerProduct = 0;
	private int mSpinnerAccount = 0;
	private int mSpinnerFirst = 0;
	int [] getYS={0,2017} ;	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
//		String OutPhotoURI;
		if (requestCode == COUNTRY_CODE) {
			if (resultCode == RESULT_OK) {
				int id = data.getIntExtra("country_id", 0);
				String pid = data.getStringExtra("country_pic");
				String name = data.getStringExtra("country_name");
				double rate = data.getDoubleExtra("country_rate", 0);
				try{
					if(mData.nCountry != id){ // 更換國家 就清除廠商資料
						((EditText)findViewById(R.id.edit_supply)).setText("");
					}
					
					mData.nCountry = id;
					((ImageView)findViewById(R.id.img_country)).setImageDrawable(Utilis.getResourceImage(AParam.this, pid));
					((EditText)findViewById(R.id.edit_country)).setText(name);
					((EditText)findViewById(R.id.edit_billrate)).setText("" + rate);
					
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}else if( requestCode == 1020){ // 廠商
			if(resultCode == RESULT_OK) {
				String factid = data.getStringExtra("fact_id");
				if(factid != null && factid.length() > 0){
					((EditText)findViewById(R.id.edit_supply)).setText(factid);
				}
			}
		}
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.param_layout);
        
        // 初始化 mYear   2002 ~ 2022
        mYear = new String[50];
        int addyear = 2012;
        for(int i = 0; i < 50; i ++){
        	mYear[i] = "" + (addyear + i);
        }
        
        
        // 一開始取出 DB 內 Default 的資料
        getCountryData(this);
        getData();
        if(mData == null){
        	mData = new DefaultData(); 
        }else{
        	((ImageView)findViewById(R.id.img_country)).setImageDrawable(Utilis.getResourceImage(this, mCountryIcon.get(mData.nCountry - 1)));
			((EditText)findViewById(R.id.edit_country)).setText(mData.country);
			((EditText)findViewById(R.id.edit_billrate)).setText("" + mData.dBillRate);
			((EditText)findViewById(R.id.edit_batch)).setText(mData.batch);
			((EditText)findViewById(R.id.edit_supply)).setText(mData.factno);
			InputFilter[] FilterArray = new InputFilter[1];
	    	FilterArray[0] = new InputFilter.LengthFilter(1);
	    	((EditText)findViewById(R.id.edit_hid)).setFilters(FilterArray);
	    	((EditText)findViewById(R.id.edit_hid)).setText(mData.nHid);
			
			// 設定正式/樣品
			if(mData.nItemState == 0){
				((RadioGroup)findViewById(R.id.group_state)).check(R.id.radio_state_1);
			}else if(mData.nItemState == 1){
				((RadioGroup)findViewById(R.id.group_state)).check(R.id.radio_state_2);
			}else {
				((RadioGroup)findViewById(R.id.group_state)).check(R.id.radio_state_3);
			}
			
			// 設定來源編碼預設
			if(mData.nSourceNumber == 0){
				((RadioGroup)findViewById(R.id.group_source)).check(R.id.radio_source_1);
			}else if(mData.nSourceNumber == 1){
				((RadioGroup)findViewById(R.id.group_source)).check(R.id.radio_source_2);
			}else if(mData.nSourceNumber == 2){
				((RadioGroup)findViewById(R.id.group_source)).check(R.id.radio_source_3);
			}
			
			// 設定年度季節
			((EditText)findViewById(R.id.edit_season)).setText("" + mYear[getYearSelect(mData.nYear)] + "," + mSeason[mData.nSeason]);
			((EditText)findViewById(R.id.edit_employ)).setText(mData.employ);
			
        }
		getYS[0]=mData.nYear; 
		getYS[1]=mData.nSeason; 

        // 帳戶 (重要)
        // 設定貨號產生方式
        mAccountList = DBUtil.CAccount.getAccountData(this);
        if(mAccountList.size() > 0){
        	mAccount = new String[mAccountList.size()];
        	for(int i = 0; i < mAccountList.size(); i++){
        		mAccount[i] = mAccountList.get(i).strShowInfo;
        	}
        }else{
        	mAccount = new String[]{"無"};
        }
        
        mSpinnerAccount = AccountUtil.getAccountIndex(mAccountList, mData.nAccountId);
		ArrayAdapter<CharSequence> adapterAccount = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, mAccount);
        adapterAccount.setDropDownViewResource(R.layout.sst_simple_dropdown_item);
		Spinner account = (Spinner)findViewById(R.id.spin_account);
		account.setAdapter(adapterAccount);
		account.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
			public void onItemSelected(@SuppressWarnings("rawtypes") AdapterView adapterView, View view,
					int position, long id) {
				mSpinnerAccount = position;
			}
			@SuppressWarnings("rawtypes")
			public void onNothingSelected(AdapterView arg0) {
			}
		});
		account.setSelection(mSpinnerAccount);
        
     // 設定貨號產生方式
		ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, mProductStrs);
		adapter.setDropDownViewResource(R.layout.sst_simple_dropdown_item);
		Spinner product = (Spinner)findViewById(R.id.spin_product);
		product.setAdapter(adapter);
		product.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
			public void onItemSelected(@SuppressWarnings("rawtypes") AdapterView adapterView, View view,
					int position, long id) {
				mSpinnerProduct = position;
			}
			@SuppressWarnings("rawtypes")
			public void onNothingSelected(AdapterView arg0) {
			}
		});
		product.setSelection(mData.nItemProduct);
		mSpinnerProduct = mData.nItemProduct;
		// 新增商品優先
		ArrayAdapter<CharSequence> adapterFirst = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, mFirstStrs);
		adapterFirst.setDropDownViewResource(R.layout.sst_simple_dropdown_item);
		Spinner itemSpinner = (Spinner)findViewById(R.id.spin_item_sort);
		itemSpinner.setAdapter(adapterFirst);
		itemSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
			public void onItemSelected(@SuppressWarnings("rawtypes") AdapterView adapterView, View view,
					int position, long id) {
				mSpinnerFirst = position;
			}
			@SuppressWarnings("rawtypes")
			public void onNothingSelected(AdapterView arg0) {
			}
		});
		itemSpinner.setSelection(mData.nItemFirst);
		mSpinnerFirst = mData.nItemFirst;
		((EditText)findViewById(R.id.edit_supply)).setOnClickListener(mClickListener);
		((EditText)findViewById(R.id.edit_country)).setOnClickListener(mClickListener);
		((EditText)findViewById(R.id.edit_billrate)).setOnClickListener(mClickListener);
		((EditText)findViewById(R.id.edit_season)).setOnClickListener(mClickListener);
		((Button)findViewById(R.id.btn_save)).setOnClickListener(mClickListener);
		((Button)findViewById(R.id.btn_exit)).setOnClickListener(mClickListener);
    }
    
    private MainClick mClickListener = new MainClick();
    class MainClick implements OnClickListener {
		@Override
		public void onClick(View v) {
			int id = v.getId();
			Utilis.runVibrate(AParam.this);
			switch (id) {
				case R.id.edit_country:
				{
					Intent intent = new Intent();
					intent.setClass(AParam.this, CodeList.class);
					intent.putExtra("code_mode", CodeMode.COUNTRY);
					intent.putExtra("edit_mode", 1);
					AParam.this.startActivityForResult(intent, COUNTRY_CODE);
					break;
				}
				case R.id.edit_supply:
				{
					Intent intent = new Intent();
					intent.setClass(AParam.this, AccountList.class);
					intent.putExtra("mode", EMode.GET);
					intent.putExtra("countryid", mData.nCountry);
					startActivityForResult(intent, 1020);
					break;
				}
				case R.id.edit_billrate:
				{
					showComputer(id);
					break;
				}
				case R.id.edit_season:
				{
					//showSeason(id);
					getYS = DateUtil.showSeason(AParam.this,id,"",getYS[0],getYS[1],0);
					break;
				}
				case R.id.btn_exit:
				{
					finish();
					break;
				}
				case R.id.btn_save:
				{
					if(saveData() == true){
						finish();
					}
					break;
				}
			}
		}
    }
    
    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(AParam.this, root);
		final TextView print = (TextView)root.findViewById(R.id.text_print);
		print.setText(((EditText)AParam.this.findViewById(vid)).getText().toString());
		dialog.setView(root);
		dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
	          public void onClick(DialogInterface dialog, int which) {
	        	  calu.resultNumber();
	        	  EditText edit = (EditText)AParam.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());
	        	  }catch(Exception e){
	        		  
	        	  }
	        	  calu.clear();
	          }
		});
		dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	          public void onClick(DialogInterface dialog, int which) {
	          }
			});
		dialog.show();
	}
    
    
    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 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++){
						String pic = cursor.getString(cursor.getColumnIndex("PIC"));
						String name = cursor.getString(cursor.getColumnIndex("NAME"));
						mCountryId.add(cursor.getInt(cursor.getColumnIndex("_ID")));
						mCountryIcon.add(pic);
						mCountryList.add(name);
						cursor.moveToNext();
					}
				}
			}catch(Exception e){
				
			}finally{
				cursor.close();
				cursor = null;
			}
		}
		db.close();
		db = null;
	}
    
    //取得年度對照表
    private int getYearSelect(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;
    }
    
    private void getData(){
    	SQLiteDatabase db = Utilis.getDB(this);
    	if(db != null){
			Cursor cursor = db.rawQuery("select * from qc_default", null);
			if(cursor != null){
				try{
					if(cursor.getCount() > 0){
						cursor.moveToFirst();
						mData = new DefaultData();
						mData.nCountry = cursor.getInt(cursor.getColumnIndex("COUNTRY"));
						mData.country = mCountryList.get(mData.nCountry - 1);
						mData.dBillRate = cursor.getDouble(cursor.getColumnIndex("BILLRATE"));
						mData.batch = cursor.getString(cursor.getColumnIndex("BATCH"));
						mData.factno = cursor.getString(cursor.getColumnIndex("FACTNO"));
						mData.nItemState = cursor.getInt(cursor.getColumnIndex("STATE"));
						mData.nSourceNumber = cursor.getInt(cursor.getColumnIndex("SOURCENO"));
						mData.nItemProduct = cursor.getInt(cursor.getColumnIndex("PRODUCT"));
						mData.nItemFirst = cursor.getInt(cursor.getColumnIndex("ITEMFIRST"));
						mData.nSeason = cursor.getInt(cursor.getColumnIndex("SEASON"));
						mData.nYear = cursor.getInt(cursor.getColumnIndex("YEAR"));
						mData.employ = cursor.getString(cursor.getColumnIndex("EMPLOY"));
						mData.nAccountId = cursor.getInt(cursor.getColumnIndex("ACCOUNT"));
						mData.nHid = cursor.getString(cursor.getColumnIndex("HID"));
						getYS[0]=mData.nYear;
						getYS[1]=mData.nSeason;
					}
				}catch(Exception e){
					e.printStackTrace();
				}finally{
					cursor.close();
				}
			}
			db.close();
    	}
    }
    
    @SuppressWarnings("unused")
	private boolean saveData(){
    	String factno = ((EditText)findViewById(R.id.edit_supply)).getText().toString();
    	Double billrate = Utilis.toDouble(((EditText)findViewById(R.id.edit_billrate)).getText().toString());
    	String batch = ((EditText)findViewById(R.id.edit_batch)).getText().toString();
    	String employ = ((EditText)findViewById(R.id.edit_employ)).getText().toString();
    	String hid = ((EditText)findViewById(R.id.edit_hid)).getText().toString();    	
    	
    	String strYearSeason = ((EditText)findViewById(R.id.edit_season)).getText().toString();
    	int checkStateId = ((RadioGroup)findViewById(R.id.group_state)).getCheckedRadioButtonId();
    	int nState = 0;
    	switch(checkStateId){
    	case R.id.radio_state_1:
    		nState = 0;
    		break;
    	case R.id.radio_state_2:
    		nState = 1;
    		break;
    	case R.id.radio_state_3:
    		nState = 2;
    		break;
    	}
    	
    	int checkSourceId = ((RadioGroup)findViewById(R.id.group_source)).getCheckedRadioButtonId();
    	int nSourceNo = 0;
    	switch(checkSourceId){
    	case R.id.radio_source_1:
    		nSourceNo = 0;
    		break;
    	case R.id.radio_source_2:
    		nSourceNo = 1;
    		break;
    	case R.id.radio_source_3:
    		nSourceNo = 2;
    		break;
    	}
    	
    	if(factno == null || factno.length() <= 0){
			Toast.makeText(this, "請輸入廠商編號", Toast.LENGTH_SHORT).show();
			return false;
		}
    	if(batch == null || batch.length() <= 0){
    		Toast.makeText(this, "請輸入批號", Toast.LENGTH_SHORT).show();
			return false;
    	}
    	
    	SQLiteDatabase db = Utilis.getDB(this);
		ContentValues value = new ContentValues();
		value.put("FACTNO", factno);
		value.put("COUNTRY", mData.nCountry);
		value.put("BATCH", batch);
		value.put("BILLRATE", billrate);
		
		value.put("STATE", nState);
		value.put("SOURCENO", nSourceNo);
		value.put("PRODUCT", mSpinnerProduct);
		value.put("ITEMFIRST", mSpinnerFirst);
		
		value.put("SEASON", getYS[1]);
		value.put("YEAR", getYS[0]);
		
		value.put("EMPLOY", employ);
		value.put("ACCOUNT", mAccountList.get(mSpinnerAccount).nID);
		value.put("HID", hid);		
    		try{
				int success = db.update(com.cwbuyer.lib.TbName.QC_DEFAULT, value,"", new String[]{});
				if(success > 0){
					Toast.makeText(this, "修改資料成功", Toast.LENGTH_SHORT).show();
				}else{
					Toast.makeText(this, "修改資料失敗", Toast.LENGTH_SHORT).show();
					return false;
				}
    		}catch(Exception e){
    			e.printStackTrace();
    		}
//    	}
    	db.close();
		return true;

    }
}
