package com.danding.yang800;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.danding.yang800.Adapter.SelectGoodsAdapter;
import com.danding.yang800.Adapter.SelectgoodAdapter;
import com.danding.yang800.Entity.DetailsInfo;
import com.danding.yang800.Entity.GoodsSortInfo;
import com.danding.yang800.Entity.SortListInfo;
import com.danding.yang800.General.SpaceItemDecoration;
import com.danding.yang800.Presenter.SelectGoodsActivityPresenter;
import com.danding.yang800.Util.GeneralUtil;
import com.danding.yang800.Util.LogUtil;
import com.danding.yang800.Util.ShareUtil;
import com.danding.yang800.Util.StatusColorUtil;
import com.danding.yang800.Util.StringUtil;
import com.danding.yang800.Util.ToastUtil;
import com.danding.yang800.View.NetworkProgressDialog;
import com.danding.yang800.View.XScrollView;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.umeng.socialize.shareboard.ShareBoardConfig;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.ShareBoardlistener;
import com.yanzhenjie.sofia.Sofia;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SelectGoodsActivity extends BaseActivity implements XScrollView.IXScrollViewListener, View.OnClickListener {
    SelectGoodsAdapter goodsadapter;
    @BindView(R.id.selectGoods_backTv)
    TextView selectGoods_backTv;
    @BindView(R.id.select_recyclerview)
    RecyclerView select_recyclerview;
    ListView selectgoods_list;
    @BindView(R.id.selectgoods_scrollView)
    XScrollView selectgoods_scrollView;
    @BindView(R.id.select_sortIv)
    ImageView select_sortIv;
    @BindView(R.id.selectgoods_serchEdit)
    EditText selectgoods_serchEdit;
    @BindView(R.id.selectGoods_titleLayout)
    RelativeLayout selectGoods_titleLayout;
    int pos = 0;
    private PopupWindow popupWindow;
    private PopupWindow popupWindowstate;
    private PopupWindow pullpopupWindow;
    TextView selectgoods_allGoodsUpTv;
    SelectGoodsActivityPresenter presenter;
    int Count = 0;
    int page = 1;
    private NetworkProgressDialog pd = null;
    String keyword = "";
    String sort = "storeProfit";
    String storeId = "";
    SharedPreferences sp;
    public String storeUrl = "";
    public String goodsUrl = "";
    public String storeName = "";
    ClipboardManager cm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        int type = StatusColorUtil.StatusBarLightMode(this);
//        if (type > 0) {
//            StatusColorUtil.setStatusBarColor(this, R.color.white);
//            StatusColorUtil.StatusBarLightMode(this, type);
//        }
        setContentView(R.layout.activity_select_goods);
        Sofia.with(this).statusBarDarkFont().statusBarBackground(ContextCompat.getColor(this, R.color.white));
        sp = getSharedPreferences("variable", Context.MODE_PRIVATE);
        ButterKnife.bind(this);
//        sp.edit().putString("storeId", "29").commit();
        cm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        page = 1;
        storeId = sp.getString("storeId", "");
        LogUtil.d(storeId);
        //  ToastUtil.show(this,storeId);
        goodsadapter = new SelectGoodsAdapter(this);
        presenter = new SelectGoodsActivityPresenter(this, goodsadapter);
        presenter.getShareUrl();
        presenter.getStoreName(storeId);
        findView();
        initHorizaontal();
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);

    }

    SelectgoodAdapter adapter;

    @OnClick({R.id.selectGoods_backTv, R.id.select_sortIv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.selectGoods_backTv:
                finish();
                break;
            case R.id.select_sortIv:
                showpullWindow();
                break;
        }
    }

    private void findView() {
        selectgoods_scrollView.setPullRefreshEnable(true);
        selectgoods_scrollView.setPullLoadEnable(false);
        selectgoods_scrollView.setAutoLoadEnable(true);
        selectgoods_scrollView.setIXScrollViewListener(this);
        selectgoods_scrollView.setRefreshTime(getTime());
        View content = LayoutInflater.from(this).inflate(R.layout.select_contents_layout, null);
        selectgoods_allGoodsUpTv = (TextView) content.findViewById(R.id.selectgoods_allGoodsUpTv);
        selectgoods_allGoodsUpTv.setOnClickListener(this);
        selectgoods_list = (ListView) content.findViewById(R.id.selectgoods_list);
        selectgoods_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(SelectGoodsActivity.this, GoodsInfoActivity.class);
                intent.putExtra("ifUp", goodsadapter.getItem(position).getIfup());
                intent.putExtra("goodsSn", goodsadapter.getItem(position).getGoodsSn());
                intent.putExtra("skuSn", goodsadapter.getItem(position).getSkuSn());
                intent.putExtra("shareUrl", goodsUrl + "?skuSn=" + goodsadapter.getItem(position).getStoreSkuSn());
                intent.putExtra("title", goodsadapter.getItem(position).getName());
                intent.putExtra("storeName", storeName);
                intent.putExtra("imageUrl", goodsadapter.getItem(position).getUrl());
                intent.putExtra("goodsSubtitle", goodsadapter.getItem(position).getGoodsSubtitle());
                startActivity(intent);
            }
        });
        selectgoods_serchEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    keyword = selectgoods_serchEdit.getText().toString().trim();
                    page = 1;
                    pos = 1;
                    onLoad();
                    if (goodsadapter != null) {
                        goodsadapter.clear();
                    }
                    initDialog();
//                    if (pos == 0) {
//                        presenter.gethotSale("300500", keyword, page + "", "storeProfit");
//                    } else {
                    for (int i = 0; i < adapter.infos.size(); i++) {
                        if (i == 1) {
                            adapter.isClicks.set(i, true);
                        } else {
                            adapter.isClicks.set(i, false);
                        }
                    }
                    select_recyclerview.setAdapter(adapter);
                    // adapter.notifyDataSetChanged();
                    presenter.getSortShopInfo(storeId, keyword, 0 + "", page + "", sort, false);
//                    }

                    return true;
                }
                return false;
            }
        });
        selectgoods_scrollView.setView(content);
        selectgoods_list.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (goodsadapter.getLists().size() <= 3) {
                    selectgoods_scrollView.onTouchEvent(event);
                }
                return false;
            }
        });
    }

    private void initHorizaontal() {
        // 创建一个线性布局管理器
        setLayout();
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        int screenWidth = display.getWidth();
        int space = 30 * screenWidth / 750;
        select_recyclerview.addItemDecoration(new SpaceItemDecoration(space));
        initDialog();
        presenter.getcategory();
        // 设置Adapter

    }

    private void setLayout() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        // 设置布局管理器
        select_recyclerview.setLayoutManager(layoutManager);
    }

    private String getTime() {
        return new SimpleDateFormat("MM-dd HH:mm", Locale.CHINA).format(new Date());
    }

    @Override
    public void onRefresh() {
        page = 1;
        // onLoad();
        //initDialog();
        if (pos == 0) {
            presenter.gethotSale(storeId, keyword, page + "", sort, false);
        } else {
            presenter.getSortShopInfo(storeId, keyword, adapter.infos.get(pos).getId() + "", page + "", sort, false);
        }
    }

    public void onLoad() {
        selectgoods_scrollView.stopRefresh();
        selectgoods_scrollView.stopLoadMore();
        selectgoods_scrollView.setRefreshTime(getTime());
    }

    @Override
    public void onLoadMore() {
        if (goodsadapter.getLists().size() < Count && goodsadapter.getLists().size() > 3) {
            page++;
            // initDialog();
            if (pos == 0) {
                presenter.gethotSale(storeId, keyword, page + "", sort, true);
            } else {
                presenter.getSortShopInfo(storeId, keyword, adapter.infos.get(pos).getId() + "", page + "", sort, true);
            }
//            presenter.getSortShopInfo(storeId, keyword, pos + "", page + "", sort, true);
        } else {
//            measureHeight();
            onLoad();
        }
    }

    public int measureHeight() {
        // get ListView adapter
        ListAdapter adapter = selectgoods_list.getAdapter();
        if (null == adapter) {
            return 0;
        }

        int totalHeight = 0;

        for (int i = 0, len = adapter.getCount(); i < len; i++) {
            View item = adapter.getView(i, null, selectgoods_list);
            if (null == item) continue;
            // measure each item width and height
            item.measure(0, 0);
            // calculate all height
            totalHeight += item.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = selectgoods_list.getLayoutParams();

        if (null == params) {
            params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
        }

        // calculate ListView height
        params.height = totalHeight + (selectgoods_list.getDividerHeight() * (adapter.getCount() - 1));

        selectgoods_list.setLayoutParams(params);

        return params.height;
    }


    public void showWindow(final int position) {
        View contentView = LayoutInflater.from(this).inflate(
                R.layout.layout_popupwindows_state, null);
        popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT, true);
        ImageView popupWindow_cancelIv = (ImageView) contentView.findViewById(R.id.popupWindow_cancelIv);
        TextView select_popup_profitTv = (TextView) contentView.findViewById(R.id.select_popup_profitTv);
        TextView select_popup_profit2Tv = (TextView) contentView.findViewById(R.id.select_popup_profit2Tv);
        select_popup_profitTv.setText("赚￥" + goodsadapter.getItem(position).getSkuProfit());
        select_popup_profit2Tv.setText("只要你的好友通过你的链接购买该商品，你就能获得" + goodsadapter.getItem(position).getSkuProfit()
                + "元的利润哦~");
        RelativeLayout popupWindow_shareshop = (RelativeLayout) contentView.findViewById(R.id.popupWindow_shareshop);
        RelativeLayout popupWindow_copyLink = (RelativeLayout) contentView.findViewById(R.id.popupWindow_copyLink);
        RelativeLayout popupWindow_zxing = (RelativeLayout) contentView.findViewById(R.id.popupWindow_zxing);
        popupWindow_cancelIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        popupWindow_shareshop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                ShareUtil.share(SelectGoodsActivity.this, goodsUrl + "?skuSn=" + goodsadapter.getItem(position).getStoreSkuSn(),
                        goodsadapter.getItem(position).getName(), goodsadapter.getItem(position).getGoodsSubtitle(),
                        goodsadapter.getItem(position).getUrl(), 0);
            }
        });
        popupWindow_copyLink.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO 复制链接
                cm.setText(goodsUrl + "?skuSn=" + goodsadapter.getItem(position).getStoreSkuSn());
                ToastUtil.show(SelectGoodsActivity.this, "复制完成");
                popupWindow.dismiss();
            }
        });
        popupWindow_zxing.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(SelectGoodsActivity.this, ShopInfoActivity.class);
                intent.putExtra("goodsUrl", goodsadapter.getItem(position).getUrl());
                intent.putExtra("goodsPrice", goodsadapter.getItem(position).getSkuMarketPrice());
                intent.putExtra("goodsName", goodsadapter.getItem(position).getName());
                intent.putExtra("url", goodsUrl + "?skuSn=" + goodsadapter.getItem(position).getStoreSkuSn());
                startActivity(intent);
                overridePendingTransition(0, 0);
                popupWindow.dismiss();
            }
        });
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.showAtLocation(contentView, Gravity.BOTTOM, 0, 0);
    }


    private void showpullWindow() {
        View contentView = LayoutInflater.from(this).inflate(
                R.layout.layout_popupwindows_pull, null);
        pullpopupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
        TextView selectgood_popup_Profit_reduceTv = (TextView) contentView.findViewById(R.id.selectgood_popup_Profit_reduceTv);
        selectgood_popup_Profit_reduceTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pullpopupWindow.dismiss();
                sort = "storeProfit";
                page = 1;
                onLoad();
                if (goodsadapter != null) {
                    goodsadapter.clear();
                }
                if (pos == 0) {
                    presenter.gethotSale(storeId, keyword, page + "", sort, false);
                } else {
                    presenter.getSortShopInfo(storeId, keyword, adapter.infos.get(pos).getId() + "", page + "", sort, false);
                }
            }
        });
        TextView selectgood_popup_sell_reduceLayout = (TextView) contentView.findViewById(R.id.selectgood_popup_sell_reduceLayout);
        selectgood_popup_sell_reduceLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pullpopupWindow.dismiss();
                page = 1;
                sort = "storePrice";
                onLoad();
                if (goodsadapter != null) {
                    goodsadapter.clear();
                }
                if (pos == 0) {
                    presenter.gethotSale(storeId, keyword, page + "", sort, false);
                } else {
                    presenter.getSortShopInfo(storeId, keyword, adapter.infos.get(pos).getId() + "", page + "", sort, false);
                }
            }
        });
        pullpopupWindow.setFocusable(true);
        pullpopupWindow.setOutsideTouchable(true);
        pullpopupWindow.setBackgroundDrawable(new BitmapDrawable());
        pullpopupWindow.showAsDropDown(select_sortIv);

    }

    public void setShouye(int position, boolean shouyexian) {
        goodsadapter.getItem(position).setShouyexian(shouyexian);
        selectgoods_list.setAdapter(goodsadapter);
        goodsadapter.notifyDataSetChanged();
    }

    public void setifUp(int position, String ifUp) {
//        if (ifUp.equals("已上架")) {
//            for (int i = 0; i <goodsadapter.getLists().size() ; i++) {
//                if (i==position){
//                    SortListInfo info=goodsadapter.getLists().get(i);
//                    info.setIfup(ifUp);
//                }
//            }
//            for (SortListInfo info :
//                    goodsadapter.getLists()) {
//                info.setIfup("已上架");
//            }
//            goodsadapter.getItem(position).setIfup(ifUp);
//            goodsadapter.notifyDataSetChanged();
//        } else {
        presenter.getGoodsInfo(storeId, goodsadapter.getItem(position).getGoodsSn(), goodsadapter.getItem(position).getSkuSn(), position);
//        }

    }

    /**
     * 一键上架点击事件
     */
    @Override
    public void onClick(View v) {
        if (selectgoods_allGoodsUpTv.getText().toString().equals("一键上架该类目所有商品")) {
            //上架posi位置的类目所有商品
            onLoad();
            initDialog();
            if (pos == 0) {
                presenter.rockingByHotSale(storeId, keyword);
            } else {
                presenter.rockingByCategory(storeId, adapter.infos.get(pos).getId() + "", keyword);
            }
//            selectgoods_list.setAdapter(goodsadapter);
//            goodsadapter.notifyDataSetChanged();
            // selectgoods_allGoodsUpTv.setText("已上架该类目所有商品");
        }
    }

    /**
     * 获得类目数据数据更新操作
     */
    public void upadateAdapter(int totalCount) {
        if (pos == 1) {
            selectgoods_allGoodsUpTv.setVisibility(View.GONE);
        } else {
            selectgoods_allGoodsUpTv.setVisibility(View.VISIBLE);
        }
        dismissDialog();
        Count = totalCount;
        if (Count == 0) {
            selectgoods_allGoodsUpTv.setVisibility(View.GONE);
            goodsadapter.notifyDataSetChanged();
            selectgoods_scrollView.setPullLoadEnable(false);
            //selectgoods_scrollView.removeFootView();
        } else if (goodsadapter.getLists().size() > 0 && goodsadapter.getLists().size() != totalCount) {
            selectgoods_scrollView.setPullLoadEnable(true);
            goodsadapter.notifyDataSetChanged();
        } else if (goodsadapter.getLists().size() == totalCount) {
            selectgoods_scrollView.setPullLoadEnable(false);
            goodsadapter.notifyDataSetChanged();
        } else {
            selectgoods_scrollView.setPullLoadEnable(false);
            // selectgoods_scrollView.removeFootView();
            goodsadapter.notifyDataSetChanged();
        }
        if (page == 1) {
            selectgoods_list.setAdapter(goodsadapter);
        } else {
            goodsadapter.notifyDataSetChanged();
        }
//        if (page == 1) {
        measureHeight();
//        }
        onLoad();

    }

    public void errData() {
        selectgoods_allGoodsUpTv.setVisibility(View.GONE);
        goodsadapter.notifyDataSetChanged();
        // selectgoods_scrollView.removeFootView();
        selectgoods_scrollView.setPullLoadEnable(false);
    }

    /*
    * 第一次进入该页面请求热卖单品数据返回更新操作
    * */
    public void upadateAdapter(final ArrayList<GoodsSortInfo> infos) {
        adapter = new SelectgoodAdapter(this, infos);
        // 设置Adapter
        select_recyclerview.setAdapter(adapter);
        presenter.gethotSale(storeId, keyword, page + "", sort, false);
        adapter.setOnItemClickListener(new SelectgoodAdapter.OnItemClickListener() {
            @Override
            public void setOnItemClick(View v, int position) {
                keyword = "";
                page = 1;
                onLoad();
                selectgoods_scrollView.post(new Runnable() {
                    @Override
                    public void run() {
                        selectgoods_scrollView.fullScroll(ScrollView.FOCUS_UP);
                    }
                });
                pos = position;
                adapter.notifyDataSetChanged();
                initDialog();
                sort = "storeProfit";
                if (pos == 0) {
                    presenter.gethotSale(storeId, keyword, page + "", "storeProfit", false);
                } else {
                    presenter.getSortShopInfo(storeId, keyword, adapter.infos.get(pos).getId() + "", page + "", "storeProfit", false);
                }
            }
        });
    }

    public void initDialog() {
        if (pd == null) {
            pd = NetworkProgressDialog.createDialog(this);
            if (!pd.isShowing()) {
                pd.show();
            }
        }
    }

    public void dismissDialog() {
        if (pd != null) {
            pd.dismiss();
            pd = null;
            NetworkProgressDialog.clear();
        }
    }

    public void toChangePriceActivity(int position, String goodsSn, String skuSn) {
        Intent intent = new Intent(SelectGoodsActivity.this, ChangePriceActivity.class);
        intent.putExtra("goodsSn", goodsSn);
        intent.putExtra("skuSn", skuSn);
        intent.putExtra("position", position);
        startActivityForResult(intent, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0) {
            if (data != null) {
                Bundle bundle = data.getExtras();
//                String price = bundle.getString("price");
                int position = bundle.getInt("position");
//                Double skuPrice = Double.parseDouble(price);
//                Double supplyPrice = Double.parseDouble(goodsadapter.getItem(position).getSkuSupplyPrice());
//                Double profit = GeneralUtil.sub(skuPrice, supplyPrice);
//                goodsadapter.getItem(position).setSkuMarketPrice(price);
//                goodsadapter.getItem(position).setSkuProfit(profit + "");
//                goodsadapter.getItem(position).setStorePriceChange(true);
//                goodsadapter.notifyDataSetChanged();
                presenter.getGoodsInfo(storeId, goodsadapter.getItem(position).getGoodsSn(), goodsadapter.getItem(position).getSkuSn(), position);
            }
        }
    }

}
