package BWP.MobileSale.ChinaPay;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

import org.forks.jsonrpc.DFDataTable;
import org.forks.jsonrpc.JsonRpcException;
import org.forks.jsonrpc.NamedValue;
import org.forks.jsonrpc.RpcFacade;
import org.forks.jsonrpc.RpcObject;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import BWP.MobileSale.LoginedActivity;
import BWP.MobileSale.R;
import BWP.MobileSale.Util.ActivityUtil;
import BWP.MobileSale.Util.CallableTask;
import BWP.MobileSale.Util.DialogUtil;

public class PayActivity extends LoginedActivity {
	private RpcObject mDmo, mPayDmo;
	Spinner spAccountUnit, spHeadOffice,spCardNo;
	TextView UsrName, CertId, moneyInput,feeInput,accMoneyInput ;
	DFDataTable tablePayInfo;
	ArrayAdapter<String> adapter1;
	ArrayAdapter<String> cardNoAdapter;	
	DFDataTable tableHeadOffice;
	DFDataTable tableOpenBankId;	
	DFDataTable tableCertType;
	List<String> listCardNo = new ArrayList<String>();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.chinapay_pay);
		loadTask.execute();
	}

	CallableTask loadTask = new CallableTask(PayActivity.this, "读取中...") {

		@Override
		public Object call() throws Exception {

			String method = "/Sale/SaleExportBase/ChinaPayRpc/LoadUserProfile";
			mDmo = RpcFacade.rpcCall(method);

			mPayDmo = RpcObject
					.create("/Sale/BWP/SaleExportBase/ChinaPay/PayObj");
			return null;
		}

		@Override
		protected void successUI() {
			initControls();
			/*
			 * try {
			 * 
			 * } catch (JsonRpcException e) { DialogUtil.Alert(PayActivity.this,
			 * e.getDetailMessage()); e.printStackTrace(); }
			 */
		}

	};

	private void initControls() throws JsonRpcException {
		if (mDmo.getLong("ID") == 0) {
			DialogUtil.AutoHiddenAlert(PayActivity.this, "请先进行个性设置，完善付款相关信息！");
			finish();
			return;
		}
 
		initAccountUnit();
		initHeadOffice();
		initcardNo();
		initUsrName();
		initCertId();
		initmoneyInput();
		initButton();
		
		String method = "/Sale/SaleExportBase/ChinaPayRpc/GetCertType";
		tableCertType = RpcFacade.rpcCall(method);
		method = "/Sale/SaleExportBase/ChinaPayRpc/GetBankType";
		tableOpenBankId = RpcFacade.rpcCall(method);
		
		method = "/Sale/SaleExportBase/ChinaPayRpc/GetPayInfo";
		tablePayInfo = RpcFacade.rpcCall(method, mDmo.getLong("HeadOffice_ID"));
		listCardNo.clear();
		List<RpcObject> rows1 = tablePayInfo.getRows();
		for (RpcObject b : rows1) {
			listCardNo.add(b.getString("CardNo"));
		}
		String card = mDmo.getString("CardNo");
		if (!listCardNo.contains(card)) {
			listCardNo.add(0, card);
		}
		cardNoAdapter = new ArrayAdapter<String>(PayActivity.this,
				android.R.layout.simple_spinner_item, listCardNo);
		spCardNo.setAdapter(cardNoAdapter);
		spCardNo.setSelection(listCardNo.indexOf(card));
		spCardNo.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				List<RpcObject> rows = tablePayInfo.getRows();
				Boolean h = false;
				String cardNo = arg0.getItemAtPosition(arg2).toString();
				for (RpcObject b : rows) {
					if (cardNo == b.getString("CardNo")) {
						UsrName.setText(b.getString("UsrName"));
						CertId.setText(b.getString("CertId"));
 
						mDmo.setNamedValue("OpenBankId", b.getNamedValue("OpenBankId")); 
						mDmo.setNamedValue("CertType", b.getNamedValue("CertType"));
						mDmo.setNamedValue("CardType", b.getNamedValue("CardType"));  
						h = true;
						break;
					}
				}
				if (!h) {
					UsrName.setText("");
					CertId.setText(""); 
				}
			}

			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
	}

	private void initAccountUnit() throws JsonRpcException {
		spAccountUnit = (Spinner) findViewById(R.id.order_setuser_setaccountunit);
		List<String> list = new ArrayList<String>();
		list.add("");
		String method = "/Sale/Sale/Rpcs/MobileLoadRpc/LoadAccountingUnit";
		DFDataTable table = RpcFacade.rpcCall(method);
		List<RpcObject> rows = table.getRows();
		for (RpcObject rpcObject : rows) {
			list.add(rpcObject.getString("Name"));
		}
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(
				PayActivity.this, android.R.layout.simple_spinner_item, list);
		spAccountUnit.setAdapter(adapter);
		spAccountUnit.setSelection(list.indexOf(mDmo
				.getString("AccountingUnit_Name")));

	}

	private void initHeadOffice() throws JsonRpcException {
		spHeadOffice = (Spinner) findViewById(R.id.order_setuser_sethheadoffice);
		List<String> list = new ArrayList<String>();
		list.add("");
		String method = "/Sale/SaleExportBase/ChinaPayRpc/LoadHeadOffice";
		tableHeadOffice = RpcFacade.rpcCall(method);
		List<RpcObject> rows = tableHeadOffice.getRows();
		for (RpcObject rpcObject : rows) {
			list.add(rpcObject.getString("Name"));
		}
		adapter1 = new ArrayAdapter<String>(PayActivity.this,
				android.R.layout.simple_spinner_item, list);
		spHeadOffice.setAdapter(adapter1);
		spHeadOffice.setSelection(list.indexOf(mDmo
				.getString("HeadOffice_Name")));

		spHeadOffice
		.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				List<RpcObject> rows = tableHeadOffice.getRows();
				Long id = 0L;
				for (RpcObject b : rows) {
					if (adapter1.getItem(arg2) == b.getString("Name")) {
						id = b.getLong("ID");
						break;
					}
				}
				String method = "/Sale/SaleExportBase/ChinaPayRpc/GetPayInfo";
				tablePayInfo = RpcFacade.rpcCall(method, id);
				List<RpcObject> rows1 = tablePayInfo.getRows();
				listCardNo.clear();
				listCardNo.add("");
				for (RpcObject b : rows1) {
					listCardNo.add(b.getString("CardNo"));
				}
				ArrayAdapter<String> cardNoAdapter = new ArrayAdapter<String>(PayActivity.this,
						android.R.layout.simple_spinner_item, listCardNo);
				spCardNo.setAdapter(cardNoAdapter);
				String card = mDmo.getString("CardNo");
				if (listCardNo.contains(card)) {
					spCardNo.setSelection(listCardNo.indexOf(card)); 
				} 
			}

			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
		
		
	}

	private void initcardNo() {
		spCardNo = (Spinner) findViewById(R.id.order_setuser_setCarNo); 
	}

	private void initUsrName() {
		UsrName = ActivityUtil.Find(this, R.id.order_setuser_setPayUserName);
		UsrName.setText(mDmo.getString("UsrName"));
	}

	private void initCertId() {
		CertId = ActivityUtil.Find(this, R.id.order_setuser_setCerID);
		CertId.setText(mDmo.getString("CertId"));
	}

	private void initmoneyInput() {		
		feeInput = ActivityUtil.Find(this, R.id.chinapay_fee);
		feeInput.setText(String.valueOf(mDmo.getDecimal("Fee")));
		accMoneyInput = ActivityUtil.Find(this, R.id.chinapay_accmoney);
		moneyInput = ActivityUtil.Find(this, R.id.chinapay_money);
		moneyInput.setKeyListener(new DigitsKeyListener(false, true));

		moneyInput.addTextChangedListener(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) {
				try{
					Double fee = Double.parseDouble(feeInput.getText().toString());
					Double money = Double.parseDouble(moneyInput.getText() .toString());
					 NumberFormat nbf=NumberFormat.getInstance();   
					 nbf.setMinimumFractionDigits(2);
					accMoneyInput.setText(nbf.format( money - fee) ) ;	
				}catch(Exception e){} 
				
			}
		});

	}

	private void initButton() {
		Button btnReturn = (Button) findViewById(R.id.Order_SetUser_Ruturn);
		btnReturn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});

		Button pay = (Button) findViewById(R.id.ChinaPay_DoPay);
		pay.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				saveTask.execute();

			}
		});
	}

	RpcObject result;

	CallableTask saveTask = new CallableTask(PayActivity.this, "付款中...") {
		@Override
		public Object call() throws Exception {

			// UpdateUserProfile
			String acc = (String) spAccountUnit.getSelectedItem();
			String ho = (String) spHeadOffice.getSelectedItem();

			mDmo.setString("AccountingUnit_Name", acc);
			mDmo.setString("HeadOffice_Name", ho);
			mDmo.setString("CardNo", (String)spCardNo.getSelectedItem());
			mDmo.setString("UsrName", UsrName.getText().toString());
			mDmo.setString("CertId", CertId.getText().toString());
		 
 
			mPayDmo.setString("AccountingUnit_Name", acc);
			mPayDmo.setString("HeadOffice_Name", ho);
			mPayDmo.setString("CardNo", (String)spCardNo.getSelectedItem());
			mPayDmo.setString("UsrName", UsrName.getText().toString());
			mPayDmo.setString("CertId", CertId.getText().toString()); 
			mPayDmo.setString("TransAmt", moneyInput.getText().toString()); 
			mPayDmo.setNamedValue("OpenBankIdNv", mDmo.getNamedValue("OpenBankId"));
			mPayDmo.setNamedValue("CardTypeNv", mDmo.getNamedValue("CardType"));
			mPayDmo.setNamedValue("CertTypeNv", mDmo.getNamedValue("CertType"));

			String method = "/Sale/SaleExportBase/ChinaPayRpc/DoPay";
			result = RpcFacade.rpcCall(method, mPayDmo);

			method = "/Sale/SaleExportBase/ChinaPayRpc/UpdateUserProfile";
			RpcFacade.rpcCall(method, mDmo);

			return null;
		}

		@Override
		protected void successUI() {
			if (result.getBoolean("Success")) {
				DialogUtil.AutoHiddenAlert(PayActivity.this, "付款成功");
				finish();
			} else {
				DialogUtil.Alert(PayActivity.this,
						"付款失败" + result.getString("Msg"));
			}

		}

	};

}
