package com.android.chmo.ui.activity.find;

import android.content.Intent;
import android.graphics.Rect;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.chmo.R;
import com.android.chmo.base.BaseActivity;
import com.android.chmo.constant.Constants;
import com.android.chmo.http.HttpApi;
import com.android.chmo.http.RequestCallback;
import com.android.chmo.http.response.CommentListRes;
import com.android.chmo.http.response.ModelListRes;
import com.android.chmo.http.response.Res;
import com.android.chmo.http.service.FindService;
import com.android.chmo.http.service.ModelService;
import com.android.chmo.model.CommentInfo;
import com.android.chmo.model.FindInfo;
import com.android.chmo.model.ModelInfo;
import com.android.chmo.ui.activity.model.ModelDetailActivity;
import com.android.chmo.ui.adpater.CommentAdapter;
import com.android.chmo.ui.view.RefreshListView;
import com.android.chmo.utils.CommonUtils;
import com.android.chmo.utils.DateUtils;
import com.android.chmo.utils.PixelUtils;
import com.android.chmo.utils.TimeUtils;
import com.android.chmo.utils.XUtilsImage;
import com.google.gson.Gson;
import com.netease.nim.uikit.common.util.StatusBarUtil;

import org.greenrobot.eventbus.EventBus;

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

import butterknife.BindView;


public class FindDetailActivity extends BaseActivity implements RefreshListView.RefreshListener {

    @BindView(R.id.refreshList)
    RefreshListView refreshListView;
    @BindView(R.id.commentBottom)
    View commentBottom;
    @BindView(R.id.commentInput)
    EditText commentEdit;


    ImageView headView;
    ImageView bigImage;
    TextView nameView;
    TextView addrView;
    TextView timeView;

    TextView goodNum;
    ImageView goodIcon;
    TextView commentNum;
    TextView followText;
    ImageView followIcon;

    View emptyView;

    private CommentAdapter commentAdapter;

    private List<CommentInfo> mList = new ArrayList<>();

    private FindInfo info;

    private ModelInfo model;

    private int pageNo = 1;

    @Override
    protected int getContentResId() {
        return R.layout.activity_find_detail;
    }

    @Override
    public void initView() {
        info = (FindInfo) getIntent().getSerializableExtra("data");
        refreshListView.getListView().addHeaderView(initDetailView());
        refreshListView.setRefreshListener(this);
        commentAdapter = new CommentAdapter(this);
        refreshListView.setAdapter(commentAdapter);

        commentEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND) {
                    sendComment();
                    return true;
                }
                return false;
            }
        });
        listenerKeybroad();

        fillDetailView();

        refreshListView.autoRefresh();

        getModelInfo(info.modelpk);
    }

    private View initDetailView() {
        View view = LayoutInflater.from(this).inflate(R.layout.find_detail_header, null);
        headView = (ImageView) view.findViewById(R.id.head);
        bigImage = (ImageView) view.findViewById(R.id.bigImg);
        nameView = (TextView) view.findViewById(R.id.name);
        addrView = (TextView) view.findViewById(R.id.address);
        timeView = (TextView) view.findViewById(R.id.time);
        goodNum = (TextView) view.findViewById(R.id.goodText);
        commentNum = (TextView) view.findViewById(R.id.commentText);
        followText = (TextView) view.findViewById(R.id.followText);
        goodIcon = (ImageView) view.findViewById(R.id.goodIcon);
        followIcon = (ImageView) view.findViewById(R.id.followIcon);
        emptyView = view.findViewById(R.id.empty);

        int imgWidth = PixelUtils.getWindowWidth() - 20;
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) bigImage.getLayoutParams();
        lp.width = imgWidth;
        lp.height = imgWidth;
        bigImage.setLayoutParams(lp);

        view.findViewById(R.id.goodBtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setGood();
            }
        });
        view.findViewById(R.id.followBtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setFollow();
            }
        });
        view.findViewById(R.id.commentBtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CommonUtils.openKeybord(commentEdit, FindDetailActivity.this);
            }
        });


        return view;
    }

    private void fillDetailView() {
        nameView.setText(info.pet);
        addrView.setText(info.area);
        timeView.setText(getTimeStr(info.pdate));
        goodNum.setText("点赞" + info.likescount);
        commentNum.setText("评论" + info.commentcount);

        goodIcon.setImageResource(info.islikes == 1 ? R.mipmap.gooded : R.mipmap.good);

        XUtilsImage.display(bigImage, HttpApi.getImgUrl(info.img), R.mipmap.def_img2);
        XUtilsImage.displayCircluar(headView, HttpApi.getImgUrl(info.hphoto), R.mipmap.def_head);
        fillFollowBtn();
        headView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), ModelDetailActivity.class);
                intent.putExtra("model", model);
                intent.putExtra("modelPk", info.modelpk);
                openPage(intent);
            }
        });
    }

    private void fillFollowBtn() {
        if (info.isattention == 1) {
            followIcon.setImageResource(R.mipmap.liked);
            followText.setTextColor(getResources().getColor(R.color.pink));
            followText.setText("已关注");
        } else {
            followIcon.setImageResource(R.mipmap.like);
            followText.setTextColor(getResources().getColor(R.color.black));
            followText.setText("关注");
        }
    }

    private String getTimeStr(String time) {
        Date date = DateUtils.parseDate(time);
        return TimeUtils.friendlyTime(date.getTime() / 1000);
    }


    @Override
    public void onRefresh() {
        loadComment(1);
    }

    @Override
    public void onLoadMore() {
        loadComment(this.pageNo + 1);
    }


    private void getModelInfo(String modelPk) {
        ModelService.getModelInfo(modelPk, new RequestCallback() {
            @Override
            public void onSuccess(String result) {
                ModelListRes res = new Gson().fromJson(result, ModelListRes.class);
                if (res.data != null && res.data.size() > 0) {
                    model = res.data.get(0);
                } else {
                }
            }

            @Override
            public void onFailure(String error) {
            }
        });
    }


    private void loadComment(final int page) {
        FindService.getCommentList(info.privatepk, page, new RequestCallback() {
            @Override
            public void onSuccess(String result) {
                refreshListView.finishRefresh();
                final CommentListRes res = new Gson().fromJson(result, CommentListRes.class);
                if (res.data != null) {
                    pageNo = page;
                    if (page == 1) {
                        mList.clear();
                    }
                    mList.addAll(res.data);
                    commentAdapter.setList(mList);
                    if (res.data.size() == Constants.PAGE_SIZE) {
                        refreshListView.setEnableLoadMore(true);
                    } else {
                        refreshListView.setNoMoreData();
                    }
                }
                emptyView.setVisibility(mList.size() == 0 ? View.VISIBLE : View.GONE);
            }

            @Override
            public void onFailure(String error) {
                refreshListView.finishRefresh();
            }
        });
    }


    private void setGood() {
        showLoading();
        final int type = info.islikes == 1 ? 2 : 1;
        FindService.setGood(info.privatepk, type, new RequestCallback() {
            @Override
            public void onSuccess(String result) {
                hideLoading();
                Res res = new Gson().fromJson(result, Res.class);
                if (res.msg.equals("success")) {
                    info.islikes = type;
                    if (type == 2) {
                        info.likescount--;
                    } else {
                        info.likescount++;
                    }
                    goodNum.setText("点赞" + info.likescount);
                    goodIcon.setImageResource(info.islikes == 1 ? R.mipmap.gooded : R.mipmap.good);
                    EventBus.getDefault().post("findRefresh");
                } else {
                    showToast("操作失败");
                }
            }

            @Override
            public void onFailure(String error) {
                hideLoading();
                showToast("操作失败");
            }
        });
    }

    private void setFollow() {
        showLoading();
        int type = info.isattention == 1 ? 2 : 1;
        ModelService.setFollow(info.modelpk, type, new RequestCallback() {
            @Override
            public void onSuccess(String result) {
                hideLoading();
                Res res = new Gson().fromJson(result, Res.class);
                if (res.msg.equals("success")) {
                    info.isattention = info.isattention == 1 ? 0 : 1;
                    fillFollowBtn();
                    EventBus.getDefault().post("followChange");
                } else {
                    showToast(info.isattention == 1 ? "取消失败" : "关注失败");
                }
            }

            @Override
            public void onFailure(String error) {
                hideLoading();
                showToast(info.isattention == 1 ? "取消失败" : "关注失败");
            }
        });
    }

    private void sendComment() {
        CommonUtils.closeKeybord(commentEdit, this);
        String content = commentEdit.getText().toString();
        if (TextUtils.isEmpty(content)) {
            return;
        }

        showLoading();
        FindService.sendComment(info.privatepk, content, new RequestCallback() {
            @Override
            public void onSuccess(String result) {
                hideLoading();
                Res res = new Gson().fromJson(result, Res.class);
                if (res.msg.equals("success")) {
                    onRefresh();
                    info.commentcount++;
                    commentNum.setText("评论" + info.commentcount);
                    commentEdit.setText("");
                    EventBus.getDefault().post("findRefresh");
                } else {
                    showToast("评论失败");
                }
            }

            @Override
            public void onFailure(String error) {
                hideLoading();
                showToast("评论失败");
            }
        });
    }

    private void listenerKeybroad() {
        final View rootView = getWindow().getDecorView();
        rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            int rootViewVisibleHeight;

            @Override
            public void onGlobalLayout() {
                //获取当前根视图在屏幕上显示的大小
                Rect r = new Rect();
                rootView.getWindowVisibleDisplayFrame(r);

                int visibleHeight = r.height();
                if (rootViewVisibleHeight == 0) {
                    rootViewVisibleHeight = visibleHeight;
                    return;
                }
                //根视图显示高度没有变化，可以看作软键盘显示／隐藏状态没有改变
                if (rootViewVisibleHeight == visibleHeight) {
                    return;
                }

                //根视图显示高度变小超过200，可以看作软键盘显示了
                if (rootViewVisibleHeight - visibleHeight > 200) {
                    // 键盘显示
                    rootViewVisibleHeight = visibleHeight;
                    // 设置输入框位置
                    RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) commentBottom.getLayoutParams();
                    lp.bottomMargin = PixelUtils.getWindowHeight() - StatusBarUtil.getStatusBarHeight(getContext()) - rootViewVisibleHeight;
                    commentBottom.setLayoutParams(lp);
                    commentBottom.setVisibility(View.VISIBLE);
                    commentEdit.setFocusable(true);
                    commentEdit.setFocusableInTouchMode(true);
                    commentEdit.requestFocus();
                    return;
                }

                //根视图显示高度变大超过200，可以看作软键盘隐藏了
                if (visibleHeight - rootViewVisibleHeight > 200) {
                    // 键盘隐藏
                    commentBottom.setVisibility(View.GONE);
                    rootViewVisibleHeight = visibleHeight;
                    return;
                }

            }
        });
    }
}
