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

import android.app.Dialog;
import android.content.Intent;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.chmo.R;
import com.android.chmo.app.ChmoApplication;
import com.android.chmo.app.VChatManager;
import com.android.chmo.base.BaseActivity;
import com.android.chmo.http.RequestCallback;
import com.android.chmo.http.response.ModelDetailRes;
import com.android.chmo.http.response.ModelListRes;
import com.android.chmo.http.response.Res;
import com.android.chmo.http.response.VideoPriceRes;
import com.android.chmo.http.service.ModelService;
import com.android.chmo.http.service.PayService;
import com.android.chmo.http.service.UserService;
import com.android.chmo.model.LoginUser;
import com.android.chmo.model.ModelInfo;
import com.android.chmo.model.ModelLabel;
import com.android.chmo.model.ModelPhoto;
import com.android.chmo.model.ModelSkill;
import com.android.chmo.ui.adpater.ImagePagerAdapter;
import com.android.chmo.ui.dialog.CallRewardDialog;
import com.android.chmo.ui.dialog.ConfirmDialog;
import com.android.chmo.ui.view.PageIndexView;
import com.android.chmo.ui.view.StarView;
import com.android.chmo.utils.LoginUtils;
import com.android.chmo.utils.PixelUtils;
import com.google.gson.Gson;
import com.netease.nim.uikit.api.NimUIKit;

import org.greenrobot.eventbus.EventBus;

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

import butterknife.BindView;
import butterknife.OnClick;


public class ModelDetailActivity extends BaseActivity {
    private ModelInfo model;
    private String modelPk;

    private List<ModelSkill> skillList = new ArrayList<>();
    private List<String> honorList = new ArrayList<>();
    public List<ModelLabel> labelList = new ArrayList<>();

    @BindView(R.id.images)
    ViewPager imagePager;
    @BindView(R.id.imgIndex)
    PageIndexView imgIndexView;
    @BindView(R.id.status)
    ImageView statusView;
    @BindView(R.id.name)
    TextView nameView;
    @BindView(R.id.star)
    StarView starView;
    @BindView(R.id.fansCount)
    TextView fansCountView;
    @BindView(R.id.follow_btn)
    Button followBtn;
    @BindView(R.id.works)
    TextView worksView;
    @BindView(R.id.video_price)
    TextView videoPice;
    @BindView(R.id.sign)
    TextView signView;
    @BindView(R.id.height)
    TextView heightView;
    @BindView(R.id.weight)
    TextView weightView;
    @BindView(R.id.three)
    TextView threeView;
    @BindView(R.id.skill_container)
    LinearLayout skillContainer;
    @BindView(R.id.honor_container)
    LinearLayout honorContainer;
    @BindView(R.id.label_container)
    LinearLayout labelContainer;


    @OnClick(R.id.back)
    public void back() {
        close();
    }

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

    @Override
    public void initView() {
        if(getIntent().hasExtra("model")) {
            model = (ModelInfo)getIntent().getSerializableExtra("model");
            modelPk = model.modelpk;
        }else if(getIntent().hasExtra("modelPk")) {
            modelPk = getIntent().getStringExtra("modelPk");
        }
        int width = PixelUtils.getWindowWidth();
        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams)imagePager.getLayoutParams();
        lp.width = width;
        lp.height = width;
        imagePager.setLayoutParams(lp);

        getModelInfo(modelPk);

        fillModelInfo();

        loadDetail();
    }

    private void fillModelInfo() {
        if(null == model) {
            return;
        }
        modelPk = model.modelpk;

        nameView.setText(model.name);
        signView.setText(model.lname);
        worksView.setText(model.occupation);

        videoPice.setText(model.vprice + "币/分钟");
        heightView.setText(model.hei+"cm");
        weightView.setText(model.wei+"kg");
        threeView.setText(model.bust + "/" + model.wai + "/" + model.hip);
        starView.setStar(model.star);
        if(model.is_a == 0) {
            statusView.setImageResource(R.mipmap.status_outline);
        }else if (model.is_a == 1) {
            statusView.setImageResource(R.mipmap.status_online);
        }else {
            statusView.setImageResource(R.mipmap.status_calling);
        }
        fillFollowBtn();
        fillModelPic(model.modelphoto);
    }

    private void fillFollowBtn() {
        fansCountView.setText(model.fcount + "粉丝");
        followBtn.setBackgroundResource(model.isattention == 1 ? R.mipmap.cancel_follow : R.mipmap.add_follow);
    }

    private void fillModelPic(List<ModelPhoto> photos) {
        List<String> pics = new ArrayList<>();
        for (ModelPhoto p : photos) {
            pics.add(p.photo);
        }
        imagePager.setAdapter(new ImagePagerAdapter(this, getSupportFragmentManager(), pics));
        imgIndexView.setDefDrawable(R.mipmap.page_indicator);
        imgIndexView.setSelectedIndexDrawable(R.mipmap.page_indicator_focused);
        imgIndexView.setCount(pics.size());
        imgIndexView.setVisibility(pics.size() > 1 ? View.VISIBLE : View.GONE);
        imgIndexView.setCurIndex(0);
        imagePager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }
            @Override
            public void onPageSelected(int position) {
                imgIndexView.setCurIndex(position);
            }
            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    private void fillModelSkill() {
        skillContainer.removeAllViews();
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lp.topMargin = 2;
        for (ModelSkill skill : skillList) {
            View view = LayoutInflater.from(this).inflate(R.layout.item_model_skill,null);
            TextView skillText = (TextView) view.findViewById(R.id.skill);
            TextView priceText = (TextView) view.findViewById(R.id.price);
            skillText.setText(skill.name);
            priceText.setText(skill.price + "元/小时");

            skillContainer.addView(view, lp);
        }
    }

    private void fillModelHonor() {
        honorContainer.removeAllViews();
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lp.topMargin = 2;
        for (String honor : honorList) {
            View view = LayoutInflater.from(this).inflate(R.layout.item_model_skill,null);
            TextView skillText = (TextView) view.findViewById(R.id.skill);
            skillText.setText(honor);
            honorContainer.addView(view, lp);
        }
    }

    private void fillModelLabel() {
        labelContainer.removeAllViews();
        int[] labelBgs = new int[]{R.drawable.label1, R.drawable.label2,R.drawable.label3};
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 60);
        lp.rightMargin =15;
        for (int i=0; i < labelList.size(); i++) {
            TextView view = (TextView)LayoutInflater.from(this).inflate(R.layout.label_item,null);
            view.setText(labelList.get(i).name);
            view.setBackgroundResource(labelBgs[i]);
            labelContainer.addView(view,lp);
        }

    }

    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);
                    fillModelInfo();
                    loadVideoPrice();
                }else {
                    showToast("模特信息获取失败");
                    finish();
                }
            }
            @Override
            public void onFailure(String error) {
                showToast("模特信息获取失败");
                finish();
            }
        });
    }

    private void loadDetail() {
        ModelService.getModelDetailInfo(modelPk, new RequestCallback() {
            @Override
            public void onSuccess(String result) {
                ModelDetailRes res = new Gson().fromJson(result, ModelDetailRes.class);
                if(res.dogetprice != null) {
                    skillList = res.dogetprice;
                    fillModelSkill();
                }
                if (res.dogethonorname != null) {
                    honorList = res.dogethonorname;
                    fillModelHonor();
                }
                if (res.dogetmodelfigure != null && res.dogetmodelfigure.selffigure != null) {
                    labelList = res.dogetmodelfigure.selffigure;
                    fillModelLabel();
                }
            }
            @Override
            public void onFailure(String error) {
            }
        });

    }

    private void loadVideoPrice() {
        ModelService.getModelVideoPrice(model.memberpk, new RequestCallback() {
            @Override
            public void onSuccess(String result) {
                VideoPriceRes res = new Gson().fromJson(result,VideoPriceRes.class);
                if(res.msg.equals("success")) {
                    model.vprice = res.vprice;
                    videoPice.setText(model.vprice + "币/分钟");
                }
            }
            @Override
            public void onFailure(String error) {
            }
        });
    }


    @OnClick(R.id.privateZone)
    public void privateZone() {
        Intent intent = new Intent(this,ModelZoneActivity.class);
        intent.putExtra("model", model);
        openPage(intent);
    }

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

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

    @OnClick(R.id.talk)
    public void talk() {
        NimUIKit.startP2PSession(this, model.memberpk);
    }


    // 直呼
    @OnClick(R.id.call)
    public void call() {
        new CallRewardDialog(this).setSelectListener(new CallRewardDialog.RewardSelectListener() {
            @Override
            public void onSelect(int value, Dialog dialog) {
                LoginUser user = ChmoApplication.getApp().getLoginUser();
                if (Float.parseFloat(user.coin_a) < value) {
                    showToast("余额不足，请充值");
                    return;
                }
                dialog.dismiss();

                reward(value);

            }
        }).show();

    }

    // 视频
    @OnClick(R.id.sendVideo)
    public void sendVideo() {
        VChatManager.getInstance().startVChat(this,model.memberpk, model.name, model.vprice);
    }

    // 预约
    @OnClick(R.id.reserve)
    public void reserve() {
        Intent intent = new Intent(this,ModelReserveActivty.class);
        intent.putExtra("model", model);
        openPage(intent);
    }


    private void reward(final int value) {
        new ConfirmDialog(this)
                .setMsg("确定要打赏"+ value+"元？")
                .setDialogListener(new ConfirmDialog.DialogListener() {
                    @Override
                    public void onOk(Dialog dialog) {
                        dialog.dismiss();
                        showLoading();
                        PayService.sendRedPkg(model.modelpk, String.valueOf(value), new RequestCallback() {
                            @Override
                            public void onSuccess(String result) {
                                hideLoading();
                                Res res = new Gson().fromJson(result,Res.class);
                                if (res.msg.equals("success")) {
                                    showToast("打赏成功");
                                    LoginUtils.refreshUser();
                                }else {
                                    showToast("打赏失败");
                                }
                            }

                            @Override
                            public void onFailure(String error) {
                                hideLoading();
                                showToast("打赏失败");
                            }
                        });
                    }
                    @Override
                    public void onCancel(Dialog dialog) {
                        dialog.dismiss();
                    }
                }).show();
    }


    @OnClick(R.id.report)
    public void report() {
        Intent intent = new Intent(this,ModelReportActivity.class);
        intent.putExtra("modelPk", model.modelpk);
        openPage(intent);
    }

    @OnClick(R.id.shield)
    public void shield() {
        new ConfirmDialog(this).setMsg("是否确定屏蔽该模特？")
                .setDialogListener(new ConfirmDialog.DialogListener() {
            @Override
            public void onOk(Dialog dialog) {
                dialog.dismiss();
                showLoading();
                UserService.shieldModel(model.modelpk, new RequestCallback() {
                    @Override
                    public void onSuccess(String result) {
                        hideLoading();
                        Res res = new Gson().fromJson(result,Res.class);
                        if (res.msg.equals("success")) {
                            showToast("屏蔽成功");
                            EventBus.getDefault().post("modelChange");
                            finish();
                        }else {
                            showToast("屏蔽失败");
                        }
                    }

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

            @Override
            public void onCancel(Dialog dialog) {
                dialog.dismiss();
            }
        }).show();
    }

}
