package com.qiyou.mb.android.ui.fragments;

import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.qiyou.mb.android.R;
import com.qiyou.mb.android.beans.basic.Note;
import com.qiyou.mb.android.beans.basic.NoteMessage;
import com.qiyou.mb.android.utils.Utils;
import com.qiyou.mb.android.utils.enums.BBSCate;
import com.qiyou.mb.android.utils.log.QLog;
import com.qiyou.mb.android.utils.server.RestMethods;

import org.json.JSONException;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

public class NoteNew extends NoteList {

	@Override
	public void setFTag() {
		TAG = "com.qiyou.NoteNew";
	}

	public static String getFTag() {
		return "com.qiyou.NoteNew";
	}

	@Override
	public String getCurrentTag() {
		return "com.qiyou.NoteNew";
	}

	private CheckBox chkMainTop, chkCateTop, chkTop, chkNoReply; // bbs_chk_main_top
	boolean isEdit;

	public static NoteNew newInstance(Note note) {
		NoteNew f = new NoteNew();
		f.currentNote = note;
		f.isEdit = false;
		return f;
	}

	public static NoteNew newInstance(Note note, NoteMessage currentMsg) {
		NoteNew f = new NoteNew();
		f.currentNote = note;
		f.currentMsg = currentMsg;
		f.isEdit = true;
		return f;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

	}

	boolean isReply;

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		if (isEdit) {
			if (currentMsg != null) {
				editTitle.setVisibility(View.GONE);
				editBody.setText(currentMsg.getBody());

			} else if (currentNote != null) {
				editTitle.setVisibility(View.VISIBLE);
				editTitle.setText(currentNote.getTitle());
				editBody.setText(currentNote.getBody());

			}
		} else {

			editTitle.setVisibility(isReply ? View.GONE : View.VISIBLE);
		}

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		// if(vContainer==null)
		// vContainer = inflater.inflate(R.layout.trackingbasic_fragment,
		// container, false);
		activity.updateActionBarTitle(isEdit ? R.string.frg_noteEdit
				: R.string.frg_noteNew);
		vContainer = inflater.inflate(R.layout.notes_new, container, false);
		initialViews();

		return vContainer;
	}

	EditText editTitle, editBody;
	Button btnSubmit;

	void initialViews() {
		isReply = !isEdit && currentNote.getId() > 0;
		editTitle = (EditText) vContainer.findViewById(R.id.edit_note_title);
		editBody = (EditText) vContainer.findViewById(R.id.edit_note_detail);
		btnSubmit = (Button) vContainer.findViewById(R.id.btn_submitNote);
		editTitle.setVisibility(currentNote == null ? View.VISIBLE
				: View.INVISIBLE);
		btnDel = (Button) vContainer.findViewById(R.id.btn_delNote);
		btnDel.setOnClickListener(ButtonOnClickListener);
		btnSubmit.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {

				try {
					Utils.hideSoftKeyboard(activity);

					if (isEdit) {
						if (currentNote == null) {
							submitNoteMsg();
						} else {
							submitNote();
						}

					} else if (currentNote == null || currentNote.getId() == 0) {
						submitNote();
					} else {
						submitNoteMsg();
					}

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});

		// chkMainTop,chkCateTop,chkTop;

		chkMainTop = (CheckBox) vContainer.findViewById(R.id.bbs_chk_main_top);
		chkCateTop = (CheckBox) vContainer.findViewById(R.id.bbs_chk_cate_top);
		chkTop = (CheckBox) vContainer.findViewById(R.id.bbs_chk_top);
		chkNoReply = (CheckBox) vContainer.findViewById(R.id.bbs_chk_noreply);

		// if ( isReply || currentNote == null ){

		btnDel.setVisibility(currentMsg != null? View.VISIBLE
				: View.GONE);
		chkMainTop.setVisibility(View.GONE);
		chkCateTop.setVisibility(View.GONE);
		chkTop.setVisibility(View.GONE);
		this.chkNoReply.setVisibility(View.GONE);

		// }

		if (currentMsg != null) {

			boolean enable = currentMsg.getUserId() == activity.app.user.getUserbean().getId() || isAdmin() ;
			editBody.setEnabled(enable);
			editTitle.setEnabled(enable);
			btnSubmit.setEnabled(enable);
			
		} else if (!isReply && currentNote != null) {

			vContainer.findViewById(R.id.txtbbsCate)
					.setVisibility(View.VISIBLE);
			spWebInputType = (Spinner) vContainer.findViewById(R.id.sp_bbsCate);
			spWebInputType.setVisibility(View.VISIBLE);
			initialSpCate();
			spWebInputType.setSelection(currentNote.getCategory());
			// spWebInputType.setEnabled(isEdit);

			// below is for check box
			chkMainTop.setChecked(currentNote.getMainPriority() > 0);
			chkCateTop.setChecked(currentNote.getCatePriority() > 0);
			chkTop.setChecked(currentNote.getPriority() > 0);
			chkNoReply.setChecked(currentNote.getStatus() > 0);

			if (!this.isAdmin() && currentNote.getStatus() > 1) { // than author
																	// can do
				this.chkNoReply.setVisibility(View.GONE);
			}

			if (isAdmin()) {
				chkMainTop.setVisibility(View.VISIBLE);
				chkCateTop.setVisibility(View.VISIBLE);
				chkTop.setVisibility(View.VISIBLE);
				this.chkNoReply.setVisibility(View.VISIBLE);
				return;
			}

			if (currentNote.getCateOwnerId() == activity.app.user.getUserbean()
					.getId()) { // its subcate owner
				// int visible = currentNote.getId() > 0 ? View.VISIBLE :
				// View.GONE;
				chkTop.setVisibility(View.VISIBLE);
				if (currentNote.getStatus() == 2
						|| currentNote.getStatus() == 0) {
					chkNoReply.setVisibility(View.VISIBLE);
				}

				spWebInputType.setVisibility(View.GONE);
				vContainer.findViewById(R.id.txtbbsCate).setVisibility(
						View.GONE);

			}

			if (currentNote.getUserId() == activity.app.user.getUserbean()
					.getId()) { // note owner

				spWebInputType.setVisibility(View.VISIBLE);
				vContainer.findViewById(R.id.txtbbsCate).setVisibility(
						View.VISIBLE);

				if (currentNote.getStatus() <= 1) {
					this.chkNoReply.setVisibility(View.VISIBLE);
				}
			} else { // subcate owner can't edit other's msg, but can del
				// vContainer.findViewById(
				// R.id.btn_delNote).setVisibility(View.GONE);
				// btnSubmit.setVisibility(View.GONE);
				editBody.setEnabled(false);
				editTitle.setEnabled(false);

			}

		}

	}

	public void submitNoteMsg() throws JSONException,
			UnsupportedEncodingException {
		NoteMessage msg;
		if (isEdit) {
			msg = currentMsg;


		} else {
			msg = new NoteMessage();
			msg.setUserId(activity.app.user.getUserbean().getId());
//			msg.setUserAlbum(activity.app.user.getUserbean().getAlbum());
			msg.setParentId(0);
			msg.setCateOwnerId(currentNote.getCateOwnerId());
			msg.setNoteId(currentNote.getId());
			msg.setTitle(currentNote.getTitle());

		}
		msg.setNoteOwnerId(currentNote.getUserId());
		msg.setLastEditBy(getAuditInfo());
		String s = editBody.getText().toString();
		if (!TextUtils.isEmpty(msg.getBody())
				&& msg.getBody().equalsIgnoreCase(s)) {
			this.showNotes("没有更改需要提交", true);
			return;
			// super.onBack();
		}
		msg.setBody(s);
		if (TextUtils.isEmpty(msg.getBody().trim())) {
			this.showNotes("请输入内容", true);
			editBody.requestFocus();
			editBody.setHintTextColor(Color.RED);
			return;
		}

		btnSubmit.setEnabled(false);
		postJsonWS(Utils.getGsonString(msg), RestMethods.NOTEMSG_P_IMPORT);

		QLog.getLogger().d(dTAG, "REPLY。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。");

		QLog.getLogger().d(dTAG, Utils.getGsonString(msg));

	}

	private String getAuditInfo() {
		return activity.app.user.getUserbean().getUserName() + "("
				+ activity.app.user.getUserbean().getId() + ")";
	}

	public void submitNote() throws JSONException, UnsupportedEncodingException {

		Note note;
		if (isEdit) {
			note = currentNote;
			note.setLastEditBy(getAuditInfo());
		} else {

			note = currentNote == null ? new Note() : currentNote;
			note.setUserId(activity.app.user.getUserbean().getId());
//			note.setUserAlbum(activity.app.user.getUserbean().getAlbum());
		}

		note.setBody(editBody.getText().toString());
		note.setTitle(editTitle.getText().toString());

		note.setPriority(this.chkTop.isChecked() ? 1 : 0);
		note.setCatePriority(this.chkCateTop.isChecked() ? 1 : 0);
		note.setMainPriority(this.chkMainTop.isChecked() ? 1 : 0);
		int noreply = activity.app.user.getUserbean().isPower() ? 3
				: isSubCateOwner() ? 2 : 1;
		note.setStatus(this.chkNoReply.isChecked() ? noreply : 0);

		int selectedItem = this.spWebInputType.getSelectedItemPosition();
		// int selctedCate =BBSCate.values()[ selectedItem].toInt();
		note.setCategory(selectedItem);

		if (TextUtils.isEmpty(note.getTitle().trim())) {
			this.showNotes("请输入标题", true);
			editTitle.requestFocus();
			editTitle.setHintTextColor(Color.RED);
			return;
		}
		if (TextUtils.isEmpty(note.getBody().trim())
				|| note.getBody().trim().length() < 5) {
			this.showNotes("请输入内容（5-500个字）", true);
			editBody.requestFocus();
			editBody.setHintTextColor(Color.RED);
			return;
		}

		btnSubmit.setEnabled(false);
		postJsonWS(Utils.getGsonString(note), RestMethods.NOTE_P_IMPORT);

		QLog.getLogger().d(dTAG, "发布。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。");

		QLog.getLogger().d(dTAG, Utils.getGsonString(note));

	}

	private boolean isSubCateOwner() {
		return currentNote != null
				&& currentNote.getCateOwnerId() == activity.app.user
						.getUserbean().getId();
	}

	@Override
	void updateUIOnRequestResonsed(String method) {
		btnSubmit.setEnabled(true);
	}

	private void initialSpCate() {
		// String BBSCity=
		// activity.app.user.getUserbean().getGeo().getCityName();
		// //.getGeo().getCityName();
		// if (BBSCity == null || TextUtils.isEmpty(BBSCity)){
		// BBSCity = "地方论坛";
		//
		// };

		// case 0:{return "聚义厅";}
		// case 1:{return "活动";}
		// case 2:return "队伍";
		// case 3:return "轨迹";
		// case 4:return "驴友";
		// case 5:return "地区";
		// case 6:return "软件使用";
		// case 7:return "运动装备";
		// case 8:return "问题反馈";
		// case 9:return "骑行天地";
		// case 10:return "跑友交流";
		// case 11:return "徒步户外";
		//
		// default: return "聚义厅";
		// }

		// String[] bbsCates = { "默认",
		// BBSCity,"我的","软件使用","骑行天地","跑友交流","徒步户外","活动相关","队伍相关",
		// "车辆装备","问题反馈"};
		List<String> cateList = new ArrayList<String>();

		for (BBSCate bbscate : BBSCate.values()) {
			cateList.add(bbscate.toCHString());
		}

		// List<String> cateList = Arrays.asList(bbsCates);

		spAdapterWeb = new ArrayAdapter<String>(activity, R.layout.myspinner,
				cateList) {
			@Override
			public View getDropDownView(int position, View convertView,
					ViewGroup parent) {
				TextView v = (TextView) super.getView(position, convertView,
						parent);
				// v.setMinimumHeight((int) (200*
				// getResources().getDisplayMetrics().density));

				v.setBackgroundResource(R.drawable.linearlayout_horizontal);

				// v.setTextAppearance(activity, R.style.ll_text_view_1);
				v.setPadding(5, 8, 5, 8);
				int selected = spWebInputType.getSelectedItemPosition();
				if (position == selected) {
					v.setTypeface(null, Typeface.BOLD);
					v.setBackgroundResource(R.drawable.head_linearlayout);
				}
				//
				// v.getPaint().setFlags(0);
				// v.setTypeface(null, Typeface.BOLD);
				// LayoutParams lp = new LayoutParams();

				v.setLayoutParams(new android.widget.AbsListView.LayoutParams(
						LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
				return v;
			}
		};// ArrayAdapter.createFromResource( activity,R.array.webInputType,
			// R.layout.thinspinner);

		// 设置下拉列表的风格
		spAdapterWeb.setDropDownViewResource(R.layout.spinner_item);

		// 将adapter2 添加到spinner中
		try {
			spWebInputType.setAdapter(spAdapterWeb);
		} catch (Exception e) {
			Utils.logStackTrace(e, "bbs");
		}
	}

	@Override
	public boolean isShowBottomTabs() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void setTabOnFiling() {
		// TODO Auto-generated method stub

	}

	@Override
	void initialNotesQuery() {

	}

}
