package com.wasu.cs.ui;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.wasu.authsdk.AuthListener;
import com.wasu.authsdk.AuthSDK;
import com.wasu.authsdk.entity.OrderPlanList;
import com.wasu.comp.userlogin.DialogLogin;
import com.wasu.compfactory.WasuCompFactory;
import com.wasu.cs.adapter.FeiHuImageAdapter;
import com.wasu.cs.adapter.FeiHuRecyclerAdapter;
import com.wasu.cs.model.FeiHuData;
import com.wasu.cs.model.Model;
import com.wasu.cs.protocol.CatProtocol;
import com.wasu.cs.utils.JsonUtil;
import com.wasu.cs.widget.BlockLinearLayout;
import com.wasu.cs.widget.ListScrollView;
import com.wasu.cs.widget.RowRecyclerView;
import com.wasu.cs.widget.ViewFlow;
import com.wasu.cs.widget.mediacontrol.DialogCommonPlanBuy;
import com.wasu.frescoimagefetchermodule.FrescoImageFetcherModule;
import com.wasu.module.datafetch.DataFetchListener;
import com.wasu.module.datafetch.DataFetchModule;
import com.wasu.module.log.WLog;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import basic.BuilderTypeManager.BuildType;
import cn.com.wasu.main.Common;
import cn.com.wasu.main.IntentConstant;
import cn.com.wasu.main.IntentMap;
import cn.com.wasu.main.R;


/**
 * 飞狐 CS模板
 */
public class ActivityFeiHuCs extends ActivityBase implements View.OnClickListener, View.OnKeyListener {
    private static final String TAG = "ActivityFeiHuCs";
    private String csJsonUrl = Common.HOME_URL;
    private FeiHuData mData = new FeiHuData();//cs模板栏目数据
    private CatProtocol catProtocol;
    private ListScrollView listScrollView;
    private MyAdapter mAdapter;
    private ViewFlow viewFlow;
    private BlockLinearLayout focusSearchLayout;
    private LinearLayout headerFocusLayout;//头部焦点控件
    private FrameLayout yb_layout, jibao_layout, nb_layout;
    private View yb, jibao, nb;
    private List<FeiHuData.DataBean.BannerBean.ListBean> headerData = new ArrayList<>();
    private SparseArray<RowData> rowDatas = new SparseArray<>();//所有行数据
    private RowRecyclerView firstRowRecyclerView;

    public static final int YB = 1;//月包
    public static final int JIBAO = 2;//季包
    public static final int NB = 3;//年包
    public static final String CATEGORYBIZID = "40814652052210000001988";

    private String mYbId = "40414579811740000003902";
    private String mJibaoId = "40414579811380000002589";
    private String mNbId = "40414579811070000001366";

    @Override
    protected void doCreate(Bundle savedInstanceState) {
        WLog.i(TAG,"doCreate()");

        setContentView(R.layout.activity_feihu_cs);
        csJsonUrl = getIntent().getStringExtra(IntentConstant.DATAURI.value());
        initView();
        initData();
    }


    private void initView() {
        listScrollView = (ListScrollView) findViewById(R.id.listScrollView);
        listScrollView.setmItemHeight((int) getResources().getDimension(R.dimen.d_336dp));
        focusSearchLayout = (BlockLinearLayout) findViewById(R.id.layoutBody);
        focusSearchLayout.setOnFocusSearchListener(focusSearchListener);
        headerFocusLayout = (LinearLayout) findViewById(R.id.headerFocusLayout);
        headerFocusLayout.setOnClickListener(this);
        headerFocusLayout.setOnKeyListener(this);
        yb_layout = (FrameLayout) findViewById(R.id.yb_layout);
        jibao_layout = (FrameLayout) findViewById(R.id.jibao_layout);
        nb_layout = (FrameLayout) findViewById(R.id.nb_layout);
        yb = findViewById(R.id.feihu_yb);
        yb.setOnClickListener(this);
        yb.setOnClickListener(this);
        jibao = findViewById(R.id.feihu_jibao);
        jibao.setOnClickListener(this);
        jibao.setOnClickListener(this);
        nb = findViewById(R.id.feihu_nb);
        nb.setOnClickListener(this);
        nb.setOnClickListener(this);
    }

    @Override
    protected void setDefaultBg(Drawable drawable) {
        getWindow().setBackgroundDrawableResource(R.color.black_alpha_08);
    }

    private void initData() {
        DataFetchModule.getInstance().fetchJsonGet(csJsonUrl, new DataFetchListener.JsonListener() {

            @Override
            public void onJsonGet(int i, String s, JSONObject jsonObject) {
                if (jsonObject != null) {
                    mData = JsonUtil.fromJson(jsonObject.toString(), FeiHuData.class);
                    if (mData != null) {
                        if (mData.getData() != null) {
                            if (mData.getData().getBanner() != null) {
                                headerData = mData.getData().getBanner().getList();
                                initPg();
                                initHeaderView();
                            }
                            if (mData.getData().getBody() != null) {
                                initBodyView();
                            }
                        } else {
                            showErrorExitDlg("数据获取失败，请重试！");
                        }
                    } else {
                        showErrorExitDlg("数据获取失败，请重试！");
                    }
                }
            }
        });

    }


    /**
     * 获取body的所有行数据
     **/

    private void fetchRowData() {
        int size = rowDatas.size();
        /**循环获取每一行的数据**/
        for (int i = 0; i < size; i++) {
            final int pos = i;

            DataFetchModule.getInstance().fetchJsonGet(rowDatas.get(i).getJsonUrl(), new DataFetchListener.JsonListener() {
                @Override
                public void onJsonGet(int retcode, String extraMsg, JSONObject jsondata) {
                    if (retcode != 0) {
                        return;
                    }
                    CatData data = new CatData();
                    data.from(jsondata);
                    if (data.getAssets().size() > 0) {
                        notifyRowDataChange(data, pos);
                    }
                }
            });
        }
    }

    private void notifyRowDataChange(CatData data, int pos) {
        List<AssetElement> list = rowDatas.get(pos).getList();
        if (list.size() >= 1) {
            list.addAll(1, data.getAssets());
        } else {
            list.addAll(data.getAssets());
        }
        mAdapter.notifyDataChange(pos, list);
    }


    /**
     * 显示header轮播海报图
     */
    private void initHeaderView() {
        viewFlow = (ViewFlow) findViewById(R.id.viewFlow);
        viewFlow.setAdapter(new FeiHuImageAdapter(ActivityFeiHuCs.this, headerData));
        viewFlow.setmSideBuffer(headerData.size()); // 设置图片5张
        viewFlow.setTimeSpan(5000);
        viewFlow.setSelection(0);           // 设置初始位置
        if (mData.getData().getBanner().getList().size() > 1) {
            viewFlow.startAutoFlowTimer(); // 启动自动播放
        }

    }

    //初始化飞狐包信息
    private void initPg() {
        List<FeiHuData.DataBean.BannerBean.PackageImagesBean> packageImages = mData.getData().getBanner().getPackageImages();
        if (packageImages == null || packageImages.size() <= 0) {
            yb_layout.setVisibility(View.VISIBLE);
            nb_layout.setVisibility(View.VISIBLE);
        } else {
            for (FeiHuData.DataBean.BannerBean.PackageImagesBean packageImage : packageImages) {
                switch (packageImage.getPgType()) {
                    case YB:
                        mYbId = packageImage.getPgId();
                        yb_layout.setVisibility(View.VISIBLE);
                        ImageView yb = (ImageView) findViewById(R.id.feihu_yb_bg);
                        FrescoImageFetcherModule.getInstance().attachImage(packageImage.getPicUrl(), yb);
                        break;
                    case JIBAO:
                        mJibaoId = packageImage.getPgId();
                        jibao_layout.setVisibility(View.VISIBLE);
                        ImageView jibao = (ImageView) findViewById(R.id.feihu_jibao_bg);
                        FrescoImageFetcherModule.getInstance().attachImage(packageImage.getPicUrl(), jibao);
                        break;
                    case NB:
                        mNbId = packageImage.getPgId();
                        nb_layout.setVisibility(View.VISIBLE);
                        ImageView nb = (ImageView) findViewById(R.id.feihu_nb_bg);
                        FrescoImageFetcherModule.getInstance().attachImage(packageImage.getPicUrl(), nb);
                        break;
                    default:
                        break;
                }
            }
        }
    }

    private void setBodyData() {
        List<FeiHuData.DataBean.BodyBean.ListBeanX> list = mData.getData().getBody().getList();
        int size = list.size();
        for (int i = 0; i < size; i++) {
            RowData rowData = new RowData();
            rowData.setJsonUrl(list.get(i).getJsonUrl());
            rowData.setPicUrl(list.get(i).getPicUrl());
            rowData.setTitle(list.get(i).getTitle());
            rowData.setTotal(list.get(i).getTotal());
            AssetElement asset = null;
            FeiHuData.DataBean.BodyBean.ListBeanX.AllBean all = list.get(i).getAll();
            if (all != null && all.getJsonUrl() != null && all.getLayout() != null && all.getPicUrl() != null) {
                asset = new AssetElement();
                asset.setJsonUrl(all.getJsonUrl());
                asset.setLayout(all.getLayout());
                asset.setPicUrl(all.getPicUrl());
                rowData.getList().add(asset);
            }
            FeiHuData.DataBean.BodyBean.ListBeanX.MoreBean more = list.get(i).getMore();
            if (more != null && more.getJsonUrl() != null && more.getLayout() != null && more.getPicUrl() != null) {
                asset = new AssetElement();
                asset.setJsonUrl(more.getJsonUrl());
                asset.setLayout(more.getLayout());
                asset.setPicUrl(more.getPicUrl());
                rowData.getList().add(asset);
            }
            rowDatas.put(i, rowData);
        }
    }

    /**
     * 数据请求完了后显示body UI
     */
    private void initBodyView() {

        setBodyData();
        /**需要先创建适配器后才能设置适配器，因为一设置适配器就会去显示数据**/
        mAdapter = new MyAdapter(rowDatas);
        /**设置适配器**/
        listScrollView.setAdapter(mAdapter);
        fetchRowData();
    }

    /**
     * 焦点分发拦截控制
     */
    private final BlockLinearLayout.OnFocusSearchListener focusSearchListener = new BlockLinearLayout.OnFocusSearchListener() {
        @Override
        public View onFocusSearch(View focused, int direction) {
            if (direction == View.FOCUS_LEFT || direction == View.FOCUS_RIGHT) {
                return focused;
            }
            return null;
        }
    };

    /**
     * header控件跳转事件监听
     * author chenming
     * time 2016/06/30
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.headerFocusLayout:
                int adapterindex = -1;

                //加入判断，避免除数为0导致异常
                if (headerData != null && headerData.size() > 0 && viewFlow.getSelectedItemPosition() > 0) {
                    adapterindex = viewFlow.getSelectedItemPosition() % headerData.size();
                } else {
                    return;
                }

                String adcsjsonurl = headerData.get(adapterindex).getJsonUrl();
                String adcslayout = headerData.get(adapterindex).getLayout();
                IntentMap.startIntent(this, null, adcslayout, adcsjsonurl, null);
                break;
            case R.id.feihu_yb:
                String userKey = AuthSDK.getInstance().getValue(AuthSDK.KEY_USERKEY);
                if (TextUtils.isEmpty(userKey)) {//用户未登录，引导登录
                    DialogLogin dialogLogin = new WasuCompFactory().createUniLogin(this, BuildType.loginurl);
                    dialogLogin.setLoginStatusListener(new DialogLogin.LoginStatusListener() {
                        @Override
                        public void onLogStatus(boolean b) {
                            if (b) {//登录成功，二次询价,需要引导用户订包
                                queryPirceAndShowPayDialog(mYbId, "3260");
                            } else {//登录失败
                                Toast.makeText(ActivityFeiHuCs.this, "用户登录失败!", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                    dialogLogin.show();
                } else {//已经登录，弹出支付
                    queryPirceAndShowPayDialog(mYbId, "3260");
                }
                break;
            case R.id.feihu_jibao:
                String userKey1 = AuthSDK.getInstance().getValue(AuthSDK.KEY_USERKEY);
                if (TextUtils.isEmpty(userKey1)) {//用户未登录，引导登录
                    DialogLogin dialogLogin = new WasuCompFactory().createUniLogin(this, BuildType.loginurl);
                    dialogLogin.setLoginStatusListener(new DialogLogin.LoginStatusListener() {
                        @Override
                        public void onLogStatus(boolean b) {
                            if (b) {//登录成功，二次询价,需要引导用户订包
                                queryPirceAndShowPayDialog(mJibaoId, "3260");
                            } else {//登录失败
                                Toast.makeText(ActivityFeiHuCs.this, "用户登录失败!", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                    dialogLogin.show();
                } else {//已经登录，弹出支付
                    queryPirceAndShowPayDialog(mJibaoId, "3260");
                }
                break;
            case R.id.feihu_nb:
                String userKey2 = AuthSDK.getInstance().getValue(AuthSDK.KEY_USERKEY);
                if (TextUtils.isEmpty(userKey2)) {//用户未登录，引导登录
                    DialogLogin dialogLogin = new WasuCompFactory().createUniLogin(this, BuildType.loginurl);
                    dialogLogin.setLoginStatusListener(new DialogLogin.LoginStatusListener() {
                        @Override
                        public void onLogStatus(boolean b) {
                            if (b) {//登录成功，二次询价,需要引导用户订包
                                queryPirceAndShowPayDialog(mNbId, "3262");
                            } else {//登录失败
                                Toast.makeText(ActivityFeiHuCs.this, "用户登录失败", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                    dialogLogin.show();
                } else {//已经登录，弹出支付
                    queryPirceAndShowPayDialog(mNbId, "3262");
                }
                break;
            default:
                break;
        }
    }

    private void queryPirceAndShowPayDialog(final String planBizId, final String thirdIndentId) {
        Map<String, Object> categoryBizId = new HashMap<String, Object>();
        categoryBizId.put("categoryBizId", CATEGORYBIZID);
        AuthSDK.getInstance().queryOrderPlanByCategoryBizId(categoryBizId, new AuthListener() {
            @Override
            public void result(int i, String s, Object o) {
                if (i == 0) {
                    List<OrderPlanList.OrderPlan> list = ((OrderPlanList) o).getList();
                    if (list == null || list.size() <= 0) {
                        return;
                    }
                    double price = 0;
                    String name = "";
                    for (int j = 0; j < list.size(); j++) {
                        if (list.get(j).planBizId.equals(planBizId)) {
                            price = list.get(j).price;
                            name = list.get(j).name;
                            break;
                        }
                    }
                    if (price == 0) return;
                    Map<String, Object> params = new HashMap<>();
                    params.put("planBizId", planBizId);
                    params.put("resourceName", name);
                    params.put("price", price);
                    params.put("thirdIndentId", thirdIndentId);
                    params.put("thirdChannel", "SOHU");

                    DialogCommonPlanBuy dialog = new DialogCommonPlanBuy(ActivityFeiHuCs.this, BuildType.payTypeUrl, params, new DialogCommonPlanBuy.PayStatusListener() {
                        @Override
                        public void onPay(int status, int code) {
                            if (status == 0) {
                                Toast.makeText(ActivityFeiHuCs.this, "支付成功!", Toast.LENGTH_LONG).show();
                            } else {
                                if (code == 12) {
                                    Toast.makeText(ActivityFeiHuCs.this, "支付失败，请重新登录后再支付！", Toast.LENGTH_LONG).show();
                                } else {
                                    Toast.makeText(ActivityFeiHuCs.this, "支付失败!", Toast.LENGTH_LONG).show();
                                }
                            }
                        }
                    });
                    dialog.show();
                } else {
                    Toast.makeText(ActivityFeiHuCs.this, "询价失败!", Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        switch (v.getId()) {
            case R.id.headerFocusLayout:
            case R.id.feihu_nb:
            case R.id.feihu_yb:
                if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (null != firstRowRecyclerView) {
                        if (firstRowRecyclerView.getChildAt(0) != null) {
                            firstRowRecyclerView.getChildAt(0).requestFocus();
                            return true;
                        }
                        return true;
                    } else {
                        return true;
                    }
                }
                return false;
        }
        return false;
    }

    /**
     * 实现自定义的适配器
     */
    class MyAdapter extends ListScrollView.Adapter {
        SparseArray<RowData> mData;
        SparseArray<FeiHuRecyclerAdapter> mAdapters = new SparseArray<>();

        public MyAdapter(SparseArray<RowData> data) {
            this.mData = data;
        }

        @Override
        public View getView(ListScrollView parent, final int pos) {
            View view = LayoutInflater.from(ActivityFeiHuCs.this).inflate(R.layout.item_feihu_row_layout, null);
            TextView tvName = (TextView) view.findViewById(R.id.rowName);
            ImageView columeLogo = (ImageView) view.findViewById(R.id.columnlogo);
            TextView total = (TextView) view.findViewById(R.id.total_text);

            tvName.setText(mData.get(pos).getTitle());
            total.setText("共 " + mData.get(pos).getTotal() + " ☆");
            FrescoImageFetcherModule.getInstance().attachImage(mData.get(pos).getPicUrl(), columeLogo);
            RowRecyclerView recyclerView = (RowRecyclerView) view.findViewById(R.id.rowList);
            FeiHuRecyclerAdapter adapter = new FeiHuRecyclerAdapter(ActivityFeiHuCs.this);
            adapter.setData(mData.get(pos).getList());
            mAdapters.put(pos, adapter);
            //设置布局管理器
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(ActivityFeiHuCs.this);
            linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
            recyclerView.setHasFixedSize(true);
            recyclerView.setLayoutManager(linearLayoutManager);
            recyclerView.setAdapter(adapter);
            if (0 == pos) {
                firstRowRecyclerView = recyclerView;
            }
            return view;
        }

        public void notifyDataChange(int i, List<AssetElement> list) {
            FeiHuRecyclerAdapter adapter = mAdapters.get(i);
            adapter.setData(list);
            adapter.notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return mData.size();
        }
    }

    @Override
    protected void onDestroy() {
        /**当退出时，停止广告轮播**/
        if (null != viewFlow) {
            viewFlow.stopAutoFlowTimer();
            viewFlow = null;
        }
        super.onDestroy();
        if (mData != null) {
            mData = null;
        }
        if (rowDatas != null) {
            rowDatas.clear();
            rowDatas = null;
        }
        if (catProtocol != null) {
            catProtocol.cleanData();
            catProtocol = null;
        }

    }


    //资产数据类
    public class AssetElement {

        private String layout;
        private String jsonUrl;
        private String picUrl;
        private String title;

        public String getLayout() {
            return layout;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public void setLayout(String layout) {
            this.layout = layout;
        }

        public String getJsonUrl() {
            return jsonUrl;
        }

        public void setJsonUrl(String jsonUrl) {
            this.jsonUrl = jsonUrl;
        }

        public String getPicUrl() {
            return picUrl;
        }

        public void setPicUrl(String picUrl) {
            this.picUrl = picUrl;
        }

    }

    class CatData extends Model implements Serializable {
        private List<AssetElement> assets = new ArrayList<>();


        public List<AssetElement> getAssets() {
            return assets;
        }

        public void setAssets(List<AssetElement> assets) {
            this.assets = assets;
        }

        @Override
        public boolean from(JSONObject json) {
            if (super.from(json)) {
                json = json.optJSONObject("data");
                if (json == null) {
                    return false;
                }
                JSONArray jsonArray = json.optJSONArray("assets");
                if (jsonArray == null) {
                    return false;
                }
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject o = jsonArray.optJSONObject(i);
                    AssetElement asset = new AssetElement();
                    asset.setJsonUrl(o.optString("jsonUrl"));
                    asset.setPicUrl(o.optString("picUrl"));
                    asset.setLayout(o.optString("layout"));
                    asset.setTitle(o.optString("title"));
                    assets.add(asset);
                }
                return true;
            }
            return false;
        }
    }

    //资产数据类
    class RowData {
        private String title;
        private String picUrl;
        private String jsonUrl;
        private int total;
        private List<AssetElement> list = new ArrayList<>();

        public String getJsonUrl() {
            return jsonUrl;
        }

        public void setJsonUrl(String jsonUrl) {
            this.jsonUrl = jsonUrl;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String tittle) {
            this.title = tittle;
        }

        public String getPicUrl() {
            return picUrl;
        }

        public void setPicUrl(String picUrl) {
            this.picUrl = picUrl;
        }

        public int getTotal() {
            return total;
        }

        public void setTotal(int total) {
            this.total = total;
        }

        public List<AssetElement> getList() {
            return list;
        }

        public void setList(List<AssetElement> list) {
            this.list = list;
        }
    }
}
