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

import android.content.Intent;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
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.Res;
import com.android.chmo.http.service.FindService;
import com.android.chmo.model.CommentInfo;
import com.android.chmo.model.ModelZone;
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.XUtilsImage;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;

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

import butterknife.BindView;

import static com.android.chmo.R.id.commentInput;

/**
 * Created by Administrator on 2018/8/7.
 */

public class ModelZoneDetailActivity extends BaseActivity implements RefreshListView.RefreshListener{

    @BindView(R.id.refreshList)
    RefreshListView refreshListView;

    @BindView(commentInput)
    EditText commentEdit;

    private TextView infoView;
    private ImageView imageView;
    private TextView timeView;
    private TextView goodNumView;
    private TextView commentNumView;

    private CommentAdapter commentAdapter;

    private ModelZone zone;

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

    private int pageNo = 1;

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

    @Override
    public void initView() {
        zone = (ModelZone) getIntent().getSerializableExtra("zone");

        refreshListView.setRefreshListener(this);
        refreshListView.getListView().setDividerHeight(2);
        refreshListView.getListView().addHeaderView(initHeaderView());
        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;
            }
        });

        fillView();
        refreshListView.autoRefresh();
    }

    private View initHeaderView() {
        View view = LayoutInflater.from(this).inflate(R.layout.zone_detail_header,null);
        infoView = (TextView) view.findViewById(R.id.info);
        imageView = (ImageView) view.findViewById(R.id.image);
        timeView = (TextView)view.findViewById(R.id.time);
        goodNumView = (TextView)view.findViewById(R.id.goodNum);
        commentNumView = (TextView)view.findViewById(R.id.commentNum);
        goodNumView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setGood();
            }
        });
        return view;
    }

    private void fillView() {
        infoView.setText(zone.intro);
        if(zone.iteminfo == null || zone.iteminfo.isEmpty()) {
            imageView.setVisibility(View.GONE);
        }else {
            imageView.setVisibility(View.VISIBLE);
            String url = zone.iteminfo.get(0).url;
            XUtilsImage.display(imageView, HttpApi.getImgUrl(url), R.mipmap.def_img2);
        }
        timeView.setText(zone.pdate);

        if(zone.likeCount == 0 && zone.privateinfo != null) {
            zone.likeCount = zone.privateinfo.size();
        }
        goodNumView.setText(zone.likeCount + "");
        goodNumView.setSelected(zone.islikes == 1);

        if(zone.commentCount == 0 && zone.recordinfo != null) {
            zone.commentCount = zone.recordinfo.size();
        }
        commentNumView.setText(zone.commentCount+"");

        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showImage();
            }
        });
    }


    private void showImage() {
        Intent intent = new Intent(this, ShowImageActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putStringArrayListExtra("images", getImgList(zone.iteminfo));
        intent.putExtra("zone", zone);
        openPageForResult(intent, 1);
    }


    public ArrayList<String> getImgList(List<ModelZone.ZoneItem> items) {
        ArrayList<String> list = new ArrayList<>();
        for(ModelZone.ZoneItem item : items) {
            list.add(HttpApi.getImgUrl(item.url));
        }
        return  list;
    }


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

    @Override
    public void onLoadMore() {
        refreshListView.postDelayed(new Runnable() {
            @Override
            public void run() {
                loadComment(pageNo + 1);
            }
        }, 500);
    }

    private void loadComment(final int page) {
        FindService.getCommentList(zone.privatepk, page, new RequestCallback() {
            @Override
            public void onSuccess(String result) {
                refreshListView.finishRefresh();
                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();
                    }
                }
            }

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

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

        showLoading();
        FindService.sendComment(zone.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();
                    zone.commentCount++;
                    commentNumView.setText("" + zone.commentCount);
                    commentEdit.setText("");

                    EventBus.getDefault().post("zoneRefresh");
                }else {
                    showToast("评论失败");
                }
            }

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

    private void setGood() {
        showLoading();
        final int type = zone.islikes == 1 ? 2: 1;
        FindService.setGood(zone.privatepk,type, new RequestCallback() {
            @Override
            public void onSuccess(String result) {
                hideLoading();
                Res res = new Gson().fromJson(result,Res.class);
                if(res.msg.equals("success")) {
                    zone.islikes = type;
                    if(type == 2) {
                        zone.likeCount--;
                    }else {
                        zone.likeCount++;
                    }
                    goodNumView.setText(zone.likeCount + "");
                    goodNumView.setSelected(zone.islikes == 1);
                    EventBus.getDefault().post("zoneRefresh");
                }else {
                    showToast("操作失败");
                }
            }

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


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK && requestCode == 1) {
            if(data.hasExtra("zone")) {
                this.zone = (ModelZone)data.getSerializableExtra("zone");
                fillView();
            }
        }
    }

    @Override
    public void finish() {
        Intent data = new Intent();
        data.putExtra("zone", zone);
        setResult(RESULT_OK, data);
        super.finish();
    }

}
