package BWP.MobileSale.Order;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import org.forks.jsonrpc.RpcFacade;
import org.forks.jsonrpc.RpcObject;

import BWP.MobileSale.LoginedActivity;
import BWP.MobileSale.R;
import BWP.MobileSale.SelectBatchNoActivity;
import BWP.MobileSale.Util.ActivityUtil;
import BWP.MobileSale.Util.CallableTask;
import BWP.MobileSale.Util.StringUtil;
import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.media.ThumbnailUtils;
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.LinearLayout;
import android.widget.TextView;

public class OrderDetailEditActivity extends LoginedActivity{

	private TextView textViewGoodsName;
	private EditText editTextNumber,editTextSecondNumber;
	private EditText editTextPrice,remarkText;
	private int position;
	private boolean isOrNotShowSecond;
	private boolean isEditSecond;
	private boolean isEditMain;
	private boolean showRemark;	
	private long buyer_ID;
	private BigDecimal policyPrice;
	private HashMap<String,Object> detail;
	private TextView batchNo_ID;
	private TextView batchNo_Name;
	final int RequestCode_SelectBatchNo = 1;
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != Activity.RESULT_OK) {
			return;
		}
		if(requestCode == RequestCode_SelectBatchNo){
			HashMap<String, Object> map = (HashMap<String, Object>) data
					.getSerializableExtra("Result");
			Object id = (Object) map.get("ID");
			batchNo_ID.setText(id.toString());
			batchNo_Name.setText((String)map.get("Name"));

		}
	}
	
	Date date;
	long accountingUnit_ID;
	static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	@SuppressWarnings("unchecked")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.order_detail_edit);
		Intent intent = getIntent();
		position = intent.getIntExtra("Position", -1);
		isOrNotShowSecond = intent.getBooleanExtra("IsOrNotShowSecond", false);
		isEditSecond = intent.getBooleanExtra("IsEditSecond", true);
		isEditMain = intent.getBooleanExtra("IsEditMain", true);
		showRemark = intent.getBooleanExtra("ShowRemark", false);		
		buyer_ID = intent.getLongExtra("Buyer_ID",0);
		String dateStr = intent.getStringExtra("Date");
		try {
			date = dateFormat.parse(dateStr);
		} catch (Exception e) {
			
		}
		if(intent.getSerializableExtra("AccountingUnit_ID") == null){
			accountingUnit_ID = 0;
		}else{
			accountingUnit_ID = Long.parseLong(intent.getSerializableExtra("AccountingUnit_ID").toString());
		}
		

		detail = (HashMap<String, Object>) intent.getSerializableExtra("Detail");
		
		String method = "/Sale/Sale/Rpcs/MobileOrderRpc/CheckIsOrNotShowPolicyPrice";
		Boolean result = RpcFacade.rpcCall(method);
		if(!result){
			LinearLayout policyPriceLayout = (LinearLayout)this.findViewById(R.id.policyPriceLayout);
			policyPriceLayout.setVisibility(View.GONE);
		}
		String method2 = "/Sale/Sale/Rpcs/MobileOrderRpc/CheckEditPriceRole";
		boolean hasEditPriceRole = RpcFacade.rpcCall(method2);
		editTextPrice = ActivityUtil.Find(this, R.id.EditText_Price);
		if(!hasEditPriceRole){
			LinearLayout priceLayout = (LinearLayout)this.findViewById(R.id.priceLayout);
			priceLayout.setVisibility(View.GONE);
		}else{
			editTextPrice.setText(StringUtil.ToString(detail.get("Price")));
		}
		remarkText= ActivityUtil.Find(this, R.id.EditText_Remark);
		if (showRemark) {
			remarkText.setText(StringUtil.ToString(detail.get("Remark")));
		} else {
			LinearLayout priceLayout = (LinearLayout) this .findViewById(R.id.remarkLayout);
			priceLayout.setVisibility(View.GONE);
		}
		
		textViewGoodsName = ActivityUtil.Find(this, R.id.TextView_Goods_Name);
		editTextNumber = ActivityUtil.Find(this, R.id.EditText_Number);
		editTextNumber.setEnabled(isEditMain);
		editTextSecondNumber = ActivityUtil.Find(this, R.id.EditText_SecondNumber);
		editTextSecondNumber.setEnabled(isEditSecond);				
		textViewGoodsName.setText(StringUtil.ToString(detail.get("Goods_Name")));
		editTextNumber.setText(StringUtil.ToString(detail.get("Number")));
		
		String method3 = "/Sale/Sale/Rpcs/MobileOrderRpc/CheckIsOrNotShowBatchNo";
		final boolean isOrNotShowBatchNo = RpcFacade.rpcCall(method3);
		if(isOrNotShowBatchNo){
		
		batchNo_ID = ActivityUtil.Find(this, R.id.BatchNo_ID);
		batchNo_Name = ActivityUtil.Find(this, R.id.BatchNo);
		batchNo_ID.setText(StringUtil.ToString(detail.get("BatchNo_ID")));
		batchNo_Name.setText(StringUtil.ToString(detail.get("BatchNo_Name")));
		Button btn = (Button)findViewById(R.id.SelectBatchNo);
		btn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), SelectBatchNoActivity.class);
				startActivityForResult(intent, RequestCode_SelectBatchNo);
				
			}
		});
		}else{
			LinearLayout batchNoLayout = (LinearLayout)findViewById(R.id.batchNoLayout);
			batchNoLayout.setVisibility(View.GONE);
		}
		if(!isOrNotShowSecond){
			editTextSecondNumber.setVisibility(View.GONE);
			TextView secondTextView = (TextView)ActivityUtil.Find(this, R.id.TextView_SecondNumber);
			secondTextView.setVisibility(View.GONE);
		}else{
			editTextSecondNumber.setText(StringUtil.ToString(detail.get("SecondNumber")));	
		}
		Button buttonOK = ActivityUtil.Find(this, R.id.Button_OK);
		Button buttonCancel = ActivityUtil.Find(this, R.id.Button_Cancel);
		buttonOK.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				detail.put("Number", StringUtil.ParseMoney(editTextNumber.getText().toString()));
				detail.put("Remark", remarkText.getText().toString() );				
				if(isOrNotShowSecond){
					detail.put("SecondNumber", StringUtil.ParseMoney(editTextSecondNumber.getText().toString()));
				}
				if(isOrNotShowSecond){
					detail.put("Price", StringUtil.ParseMoney(editTextPrice.getText().toString()));
				}
				if(isOrNotShowBatchNo){
					if(batchNo_ID.getText()!=null && batchNo_ID.getText()!=""){
					detail.put("BatchNo_ID", Long.parseLong(batchNo_ID.getText().toString()));
					detail.put("BatchNo_Name", batchNo_Name.getText().toString());
					}
				}
				detail.put("PolicyPrice", policyPrice);
				Intent intent =new Intent();
				intent.putExtra("Detail", detail);
				intent.putExtra("Position", position);
				ActivityUtil.Finish(OrderDetailEditActivity.this, intent);				
			}
		});
		
		buttonCancel.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				finish();				
			}
		});
		if(isOrNotShowSecond){
		editTextNumber.addTextChangedListener(
				new TextWatcher() {
					
					@Override
					public void onTextChanged(CharSequence s, int start, int before, int count) {
						if(editTextNumber.hasFocus()){
						BigDecimal number =  StringUtil.ParseMoney(s.toString());
						Object goods_SecondaryUnit1RelativeRatio =  detail.get("Goods_SecondaryUnit1RelativeRatio");
						Object goods_SecondaryUnit1Ratio =  detail.get("Goods_SecondaryUnit1Ratio");
						if(number!=null&&goods_SecondaryUnit1Ratio!=null&&goods_SecondaryUnit1RelativeRatio!=null){
							BigDecimal mainUnitNum = ((number).divide(((BigDecimal)detail.get("LeftRatio")),6,BigDecimal.ROUND_HALF_EVEN)).multiply(((BigDecimal)detail.get("RightRatio")));
							BigDecimal secondNumber = (mainUnitNum.multiply((BigDecimal)goods_SecondaryUnit1RelativeRatio)).divide((BigDecimal)goods_SecondaryUnit1Ratio,6,BigDecimal.ROUND_HALF_EVEN);
							editTextSecondNumber.setText(secondNumber.toString());
							
						}
						}
						
					}
					
					@Override
					public void beforeTextChanged(CharSequence s, int start, int count,
							int after) {
						// TODO Auto-generated method stub
						
					}
					
					@Override
					public void afterTextChanged(Editable s) {
						
						
					}
				}
				);
		
		editTextSecondNumber.addTextChangedListener(
				new TextWatcher() {
					
					@Override
					public void onTextChanged(CharSequence s, int start, int before, int count) {
						if(editTextSecondNumber.hasFocus()){
						BigDecimal secondNumber =  StringUtil.ParseMoney(s.toString());
						Object goods_SecondaryUnit1RelativeRatio =  detail.get("Goods_SecondaryUnit1RelativeRatio");
						Object goods_SecondaryUnit1Ratio =  detail.get("Goods_SecondaryUnit1Ratio");
						if(secondNumber!=null&&goods_SecondaryUnit1Ratio!=null&&goods_SecondaryUnit1RelativeRatio!=null){
							BigDecimal mainUnitNum = (((BigDecimal)secondNumber).multiply(((BigDecimal)goods_SecondaryUnit1Ratio))).divide(((BigDecimal)goods_SecondaryUnit1RelativeRatio));
							BigDecimal number = (mainUnitNum.divide((BigDecimal)detail.get("RightRatio"))).multiply((BigDecimal)detail.get("LeftRatio"));
							editTextNumber.setText(number.toString());
							
						}
						}
					}
					
					@Override
					public void beforeTextChanged(CharSequence s, int start, int count,
							int after) {
						// TODO Auto-generated method stub
						
					}
					
					@Override
					public void afterTextChanged(Editable s) {
						
						
					}
				}
				);
		}
		if(result){
		initBillTask.execute();
		}
	}
	
	CallableTask initBillTask = new CallableTask(this, "读取价格中...") {
		public Object call() throws Exception {
			if (buyer_ID > 0) {
				String method = "/Sale/Sale/Rpcs/MobileOrderRpc/GetPolicyPrice";
				BigDecimal result;
				if(accountingUnit_ID > 0){
					result = RpcFacade.rpcCall(method, (Long)detail.get("Goods_ID"),buyer_ID,date,accountingUnit_ID);
				}else{
				  result = RpcFacade.rpcCall(method, (Long)detail.get("Goods_ID"),buyer_ID,date,null);
				}
				if(result!= new BigDecimal(0)){
					policyPrice = result;
				}
			} 
			return null;
		}

		@Override
		protected void successUI() {
			if(policyPrice!= new BigDecimal(0)){
				SetPolicyPriceText();
			}
		}
	};
	
	private void SetPolicyPriceText() {
		TextView textViewPolicyPrice = ActivityUtil.Find(this, R.id.TextView_PolicyPrice);
		textViewPolicyPrice.setText(policyPrice.toString());
	}
	
}
