package com.mjsheng.myappstore.fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.mjsheng.myappstore.R;
import com.mjsheng.myappstore.adapter.CommentsListAdapter;
import com.mjsheng.myappstore.bean.CommentInfo;
import com.mjsheng.myappstore.bean.JsonCallback;
import com.mjsheng.myappstore.bean.LzyResponse;
import com.mjsheng.myappstore.comm.CommonDatas;
import com.mjsheng.myappstore.utils.Configure;
import com.mjsheng.myappstore.utils.MySQLData;
import com.mjsheng.myappstore.utils.Utils;
import com.mjsheng.myappstore.view.StarRatingBar;
import com.mjsheng.myappstore.widget.Sound;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;
import okhttp3.internal.Util;

public class CommentsPageFragment extends Fragment implements View.OnClickListener {

    private ListView mCommentsListView;
    private Button mGiveCommentBtn;
    private CommentsListAdapter mCommentsListAdapter;
    private EditText mCommentsEditText;
    private Button mCommentBtn;
    private CheckBox mAnonymityCheckBox;
    private StarRatingBar mCommentsRatingBar;
    private View mEditCommentLL;
    private ArrayList<CommentInfo> mCommentsDatas;
    private View mParentView = null;
    private boolean isAnonymous = false;
    private Sound sound;
    private String packageName = null;

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


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.comments_page_layout, container,
                false);
        sound = new Sound(getContext());
        initView(view);
        return view;
    }

    private void initView(View view) {
        mCommentsListView = (ListView) view.findViewById(R.id.comments_listview);
        mGiveCommentBtn = (Button) view.findViewById(R.id.give_comment_btn);

        mGiveCommentBtn.setOnClickListener(this);
        mCommentsListAdapter = new CommentsListAdapter(getActivity());
        mCommentsListView.setAdapter(mCommentsListAdapter);

        mEditCommentLL = view.findViewById(R.id.edit_comment_ll);
        mCommentsRatingBar = (StarRatingBar) view.findViewById(R.id.comment_ratingbar);
        mCommentsRatingBar.setmClickable(true);
        mAnonymityCheckBox = (CheckBox) view.findViewById(R.id.anonymity_checkbox);
        mAnonymityCheckBox.setOnClickListener(this);

        mCommentBtn = (Button) view.findViewById(R.id.comment_btn);
        mCommentBtn.setOnClickListener(this);
        mCommentsEditText = (EditText) view.findViewById(R.id.comment_edit);
        view.findViewById(R.id.comments_page_layout).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) {
                sound.playSoundEffect();
                if (mCommentsEditText != null) {
                    mCommentsEditText.clearFocus();
                    Utils.hideKeyboard(getActivity(), mCommentsEditText);
                }
                return false;
            }
        });

    }

    public void initDatas(String appPkg) {
        packageName = appPkg;
        OkGo.post(Configure.HTTP_TAG_GET_APP_COMMENTS_REQ)
                .tag(this)
                .params("key",Configure.HTTP_KEY)
                .params("sn",Utils.getSerial())
                .params("package",java.net.URLEncoder.encode(appPkg))
                .cacheKey(Configure.HTTP_TAG_GET_APP_COMMENTS_REQ + java.net.URLEncoder.encode(appPkg))
                .cacheMode(CacheMode.REQUEST_FAILED_READ_CACHE)
                .execute(new JsonCallback<LzyResponse<List<CommentInfo>>>() {
                    @Override
                    public void onSuccess(LzyResponse<List<CommentInfo>> listLzyResponse, Call call, Response response) {
                        if (mCommentsDatas == null) {
                            mCommentsDatas = new ArrayList<>();
                        }
                        mCommentsDatas = (ArrayList<CommentInfo>) listLzyResponse.data;
                        mCommentsListAdapter.setData(mCommentsDatas);
                        mCommentsListAdapter.notifyDataSetChanged();
                    }
                    @Override
                    public void onCacheError(Call call, Exception e) {
                        super.onCacheError(call, e);
                        Utils.showToast(getContext(), "网络连接不稳定，请稍后重试！"+e.getMessage());
                    }
                });
    }


    private void updateCommentsTab(int commentsCount) {
        if (mParentView != null) {
            RadioButton commentBtn = (RadioButton) mParentView.findViewById(R.id.comments_btn);
            if (commentBtn != null && isAdded()) {
                commentBtn.setText(getResources().getString(
                        R.string.app_detail_comments_text_format,
                        commentsCount > 0 ? "(" + commentsCount + ")" : ""));
            }
        }
    }

    @Override
    public void onClick(View v) {
        sound.playSoundEffect();
        switch (v.getId()) {
            case R.id.give_comment_btn:
                showCommentsEdit(true);
                break;
            case R.id.comment_btn:
                commitComment();
                break;
            case R.id.anonymity_checkbox:
                if (isAnonymous) {
                    isAnonymous = false;
                } else {
                    isAnonymous = true;
                }
                break;
            default:
                break;
        }
    }

    private void showCommentsEdit(boolean isShow) {
        if (isShow) {
            mGiveCommentBtn.setVisibility(View.GONE);
            mEditCommentLL.setVisibility(View.VISIBLE);
        } else {
            mGiveCommentBtn.setVisibility(View.VISIBLE);
            mEditCommentLL.setVisibility(View.GONE);
        }
    }

    public void setParentView(View parentView) {
        mParentView = parentView;
        if (mParentView != null) {
            mParentView.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View arg0, MotionEvent arg1) {
                    if (mCommentsEditText != null) {
                        mCommentsEditText.clearFocus();
                        Utils.hideKeyboard(getActivity(),
                                mCommentsEditText);
                    }
                    return false;
                }
            });
        }
    }


    private void commitComment() {
        if (mCommentsEditText != null) {
            mCommentsEditText.clearFocus();
            Utils.hideKeyboard(getActivity(), mCommentsEditText);
        }

        final String commentText = mCommentsEditText.getText().toString();
        if (TextUtils.isEmpty(commentText.trim())) {
            Utils.showToast(getActivity(), getString(R.string.comment_content_empty));
            return;
        }

        final int rating =  mCommentsRatingBar.getStarNumber();
        if (rating == 0) {
            Utils.showToast(getActivity(), getString(R.string.comment_star_empty));
            return;
        }
//
//        final String userName = MySQLData.GetData(getActivity(), CommonDatas.SP_BABY_NAME);
//        if (userName.equals("")) {
//            Utils.showToast(getActivity(), "请先登录再进行评论！");
//            return;
//        }

        SimpleDateFormat mDateFormat = new SimpleDateFormat(getString(R.string.app_comment_time_format));
        Date endDate = new Date();
        final String commentDate = mDateFormat.format(endDate);
        OkGo.post(Configure.HTTP_TAG_POST_APP_COMMENTS_REQ)
                .tag(this)
                .params("package",java.net.URLEncoder.encode(packageName))
                .params("score", String.valueOf(rating))
                .params("content", commentText)
                .params("sn", Utils.getSerial())
                .params("key", Configure.HTTP_KEY)
                .cacheKey(Configure.HTTP_TAG_POST_APP_COMMENTS_REQ + java.net.URLEncoder.encode(packageName))
                .cacheMode(CacheMode.NO_CACHE)
                .execute(new StringCallback() {

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        CommentInfo commentInfo = new CommentInfo();
                        commentInfo.setApp_baoming(packageName);
//                        commentInfo.setUser_name(userName);
                        commentInfo.setNiming(String.valueOf(isAnonymous));
                        commentInfo.setPingfen(String.valueOf(rating));
                        commentInfo.setPinglun_time(commentDate);
                        commentInfo.setPinglun_content(commentText);

                        if (mCommentsDatas == null) {
                            mCommentsDatas = new ArrayList<>();
                            mCommentsListAdapter.setData(mCommentsDatas);
                        }
                        mCommentsDatas.add(0, commentInfo);
                        mCommentsListAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onCacheError(Call call, Exception e) {
                        super.onCacheError(call, e);
                        if(!Utils.isIntent(getContext())){
                            Utils.showToast(getContext(),"网络连接不稳定，请稍后重试！");
                        }
                    }
                });

        showCommentsEdit(false);
        resetDatas();
    }

    private void resetDatas() {
        mCommentsRatingBar.setStar(0);
        mCommentsEditText.setText("");
        mAnonymityCheckBox.setChecked(false);
    }
}
