package com.danding.yang800;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.util.Util;
import com.danding.yang800.Adapter.MyShopAdapter;
import com.danding.yang800.Config.ConfigUtil;
import com.danding.yang800.Entity.SortListInfo;
import com.danding.yang800.General.Yang800App;
import com.danding.yang800.Presenter.MyshopActivityPresenter;
import com.danding.yang800.Util.BitmapUtil;
import com.danding.yang800.Util.GeneralUtil;
import com.danding.yang800.Util.LogUtil;
import com.danding.yang800.Util.ShareUtil;
import com.danding.yang800.Util.StringUtil;
import com.danding.yang800.Util.ToastUtil;
import com.danding.yang800.View.NetworkProgressDialog;
import com.danding.yang800.View.XListView;
import com.tencent.mm.opensdk.modelmsg.GetMessageFromWX;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
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 butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MyShopActivity extends BaseActivity implements XListView.IXListViewListener {
    @BindView(R.id.shop_designIv)
    ImageView shop_designIv;
    @BindView(R.id.shop_seeIv)
    ImageView shop_seeIv;
    XListView myshop_list;
    MyShopAdapter adapter;
    @BindView(R.id.myShop_backImage)
    ImageView myShop_backImage;
    private PopupWindow popupWindow;
    @BindView(R.id.myshop_Iv)
    ImageView myshop_Iv;
    @BindView(R.id.myshop_shareIv)
    ImageView myshop_shareIv;
    @BindView(R.id.myshop_shopIv)
    ImageView myshop_shopIv;
    @BindView(R.id.myshop_HeadIv)
    ImageView myshop_HeadIv;
    @BindView(R.id.myshop_shopNameTv)
    TextView myshop_shopNameTv;
    @BindView(R.id.myshop_shopDesTv)
    TextView myshop_shopDesTv;
    @BindView(R.id.myshop_emptyLayout)
    RelativeLayout myshop_emptyLayout;
    private PopupWindow popupshareWindow;
    MyshopActivityPresenter presenter;
    private NetworkProgressDialog pd;
    private int Count = 0;
    int page = 1;
    String storeId = "";
    SharedPreferences sp;
    String headUrl = "";
    String backUrl = "";
    private IWXAPI api;
    Bundle bundle;
    public String storeUrl = "";
    public String goodsUrl = "";
    ClipboardManager cm;
    boolean success = false;
    public String storeName = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        setContentView(R.layout.activity_my_shop);
        sp = getSharedPreferences("variable", Context.MODE_PRIVATE);
//        sp.edit().putString("storeId", "300619").commit();
        cm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        api = Yang800App.getApi(this);
        bundle = getIntent().getExtras();
        storeId = sp.getString("storeId", "");
        ButterKnife.bind(this);
        findView();
    }

    private void findView() {
        myshop_list = (XListView) findViewById(R.id.myshop_list);
        myshop_list.setPullRefreshEnable(true);
        myshop_list.setPullLoadEnable(true);
        myshop_list.setAutoLoadEnable(true);
        myshop_list.setXListViewListener(this);
        adapter = new MyShopAdapter(this);
        myshop_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(MyShopActivity.this, GoodsInfoActivity.class);
                if (position > 0) {
                    intent.putExtra("ifUp", adapter.getItem(position - 1).getIfup());
                    intent.putExtra("goodsSn", adapter.getItem(position - 1).getGoodsSn());
                    intent.putExtra("skuSn", adapter.getItem(position - 1).getSkuSn());
                    intent.putExtra("shareUrl", goodsUrl + "?skuSn=" + adapter.getItem(position - 1).getStoreSkuSn());
                    intent.putExtra("title", adapter.getItem(position - 1).getName());
                    intent.putExtra("storeName", storeName);
                    intent.putExtra("imageUrl", adapter.getItem(position - 1).getUrl());
                    intent.putExtra("goodsSubtitle", adapter.getItem(position - 1).getGoodsSubtitle());
                    startActivity(intent);
                }
            }
        });
        presenter = new MyshopActivityPresenter(this, adapter);
        initDialog();
        presenter.getShareUrl();
        presenter.getSortShopInfo(storeId, "", page + "", false, false);
    }


    @OnClick({R.id.myShop_backImage, R.id.myshop_Iv, R.id.shop_designIv, R.id.shop_seeIv, R.id.myshop_shareIv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.myShop_backImage:
                finish();
                break;
            case R.id.myshop_Iv:
                Intent intent = new Intent(MyShopActivity.this, ShopDesignActivity.class);
                startActivityForResult(intent, 1);
                break;
            case R.id.shop_designIv:
                startActivity(GoodsSortActivity.class);
                break;
            case R.id.shop_seeIv:
                startActivity(SeeActivity.class);
                break;
            case R.id.myshop_shareIv:
                sp.edit().putBoolean("WXlogin", false).commit();
                if (!StringUtil.getString(storeUrl) || !StringUtil.getString(goodsUrl)) {
                    presenter.getShareUrl();
                }
                if (success) {
                    showshareWindow();
                }
                break;
        }
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        bundle = intent.getExtras();
    }


    public void showshareWindow() {
        View contentView = LayoutInflater.from(this).inflate(
                R.layout.layout_popupwindows_myshopshare, null);
        popupshareWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT, true);
        ImageView popupshareWindow_cancelIv = (ImageView) contentView.findViewById(R.id.popupshareWindow_cancelIv);
        RelativeLayout popupshareWindow_shareshop = (RelativeLayout) contentView.findViewById(R.id.popupshareWindow_shareshop);
        RelativeLayout popupshareWindow_copyLink = (RelativeLayout) contentView.findViewById(R.id.popupshareWindow_copyLink);
        RelativeLayout popupshareWindow_zxing = (RelativeLayout) contentView.findViewById(R.id.popupshareWindow_zxing);
        popupshareWindow_cancelIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupshareWindow.dismiss();
            }
        });
        popupshareWindow_shareshop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO 跳转微信
                popupshareWindow.dismiss();
                if (headUrl.equals("")) {
                    ShareUtil.share(MyShopActivity.this, storeUrl + "?storeId=" + storeId,
                            myshop_shopNameTv.getText().toString().trim(), "全球直采，正品保障，资深买手精选的好货，我自己用觉得很好，推荐给你看看~",
                            "", R.drawable.main_myhead);
                } else {
                    ShareUtil.share(MyShopActivity.this, storeUrl + "?storeId=" + storeId,
                            myshop_shopNameTv.getText().toString().trim(), "全球直采，正品保障，资深买手精选的好货，我自己用觉得很好，推荐给你看看~",
                            headUrl, 0);
                }

            }
        });
        popupshareWindow_copyLink.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO 复制链接
                if (StringUtil.getString(storeUrl)) {
                    cm.setText(storeUrl + "?storeId=" + storeId);
                    ToastUtil.show(MyShopActivity.this, "复制完成");
                    popupshareWindow.dismiss();
                }


            }
        });
        popupshareWindow_zxing.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (StringUtil.getString(storeUrl)) {
                    Intent intent = new Intent(MyShopActivity.this, ShopShareActivity.class);
                    intent.putExtra("url", storeUrl + "?storeId=" + storeId);
                    intent.putExtra("headUrl", headUrl);
                    intent.putExtra("backUrl", backUrl);
                    intent.putExtra("storeName", myshop_shopNameTv.getText().toString().trim());
                    startActivity(intent);
                    overridePendingTransition(0, 0);
                    popupshareWindow.dismiss();
                }
            }
        });
        popupshareWindow.setFocusable(true);
        popupshareWindow.setOutsideTouchable(true);
        popupshareWindow.setBackgroundDrawable(new BitmapDrawable());
        popupshareWindow.showAtLocation(contentView, Gravity.BOTTOM, 0, 0);
    }

    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("赚￥" + adapter.getItem(position).getSkuProfit());
        select_popup_profit2Tv.setText("只要你的好友通过你的链接购买该商品，你就能获得" + adapter.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) {
                // TODO 跳转微信
                popupWindow.dismiss();
                ShareUtil.share(MyShopActivity.this, goodsUrl + "?skuSn=" + adapter.getItem(position).getStoreSkuSn(),
                        adapter.getItem(position).getName(), adapter.getItem(position).getGoodsSubtitle(),
                        adapter.getItem(position).getUrl(), 0);
            }
        });
        popupWindow_copyLink.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO 复制链接
                cm.setText(goodsUrl + "?skuSn=" + adapter.getItem(position).getStoreSkuSn());
                ToastUtil.show(MyShopActivity.this, "复制完成");
                popupWindow.dismiss();
            }
        });
        popupWindow_zxing.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MyShopActivity.this, ShopInfoActivity.class);
                intent.putExtra("url", goodsUrl + "?skuSn=" + adapter.getItem(position).getStoreSkuSn());
                intent.putExtra("goodsUrl", adapter.getItem(position).getUrl());
                intent.putExtra("goodsPrice", adapter.getItem(position).getSkuMarketPrice());
                intent.putExtra("goodsName", adapter.getItem(position).getName());
                startActivity(intent);
                overridePendingTransition(0, 0);
                popupWindow.dismiss();
            }
        });
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.showAtLocation(contentView, Gravity.BOTTOM, 0, 0);
    }


    /**
     * 获得类目数据数据更新操作
     */
    public void upadateAdapter(int totalCount, String name, String des, String avatar, String img, boolean load) {
        LogUtil.d(avatar);
        dismissDialog();
        success = true;
        if (!load) {
            myshop_shopNameTv.setText(name);
            myshop_shopDesTv.setText(des);
            if (avatar.equals("")) {
                myshop_HeadIv.setImageResource(R.drawable.main_myhead);
            } else {
                if (headUrl.equals("")) {
                    headUrl = avatar;
                    Glide.with(this).load(headUrl).error(R.drawable.huisebeijing).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(myshop_HeadIv);
                }
            }
            if (img.equals("")) {
                myshop_shopIv.setImageResource(R.drawable.main_back);
            } else {
                if (backUrl.equals("")) {
                    backUrl = img;
                    Glide.with(this).load(backUrl).error(R.drawable.huisebeijing).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(myshop_shopIv);
                }

            }
        }
        Count = totalCount;
        if (Count == 0) {
            myshop_emptyLayout.setVisibility(View.VISIBLE);
            myshop_list.setVisibility(View.GONE);
        } else {
            myshop_emptyLayout.setVisibility(View.GONE);
            myshop_list.setVisibility(View.VISIBLE);
        }
        if (adapter.getLists().size() > 0 && adapter.getLists().size() != totalCount) {
            myshop_list.setPullLoadEnable(true);
        } else {
            myshop_list.setPullLoadEnable(false);
        }
        if (page == 1) {
            myshop_list.setAdapter(adapter);
        }
        adapter.notifyDataSetChanged();
        onLoad();
    }

    @Override
    public void onRefresh() {
        page = 1;
        presenter.getSortShopInfo(storeId, "", page + "", false, false);
    }

    @Override
    public void onLoadMore() {
        if (adapter.getLists().size() < Count && adapter.getLists().size() > 2) {
            page++;
            presenter.getSortShopInfo(storeId, "", page + "", false, true);
        } else {
            onLoad();
        }
    }

    public void onLoad() {
        myshop_list.stopRefresh();
        myshop_list.stopLoadMore();
    }

    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 setShouye(int position, boolean shouyexian) {
        adapter.getItem(position).setShouyexian(shouyexian);
        adapter.notifyDataSetChanged();
    }

    public void setifUp(int position, String ifUp) {
        ToastUtil.show(this, "下架成功");
        adapter.getLists().remove(position);
        // adapter.getItem(position).setIfup(ifUp);
        myshop_list.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        if (adapter.getLists().size() == 0) {
            myshop_emptyLayout.setVisibility(View.VISIBLE);
            myshop_list.setVisibility(View.GONE);
        }
    }

    public void toChangePriceActivity(int position, String goodsSn, String skuSn) {
        Intent intent = new Intent(MyShopActivity.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(adapter.getItem(position).getSkuSupplyPrice());
//                Double profit = GeneralUtil.sub(skuPrice, supplyPrice);
//                adapter.getItem(position).setSkuMarketPrice(price);
//                adapter.getItem(position).setSkuProfit(profit + "");
//                adapter.getItem(position).setStorePriceChange(true);
//                adapter.notifyDataSetChanged();
                presenter.getGoodsInfo(storeId, adapter.getItem(position).getGoodsSn(), adapter.getItem(position).getSkuSn(), position);
            }
        }
        if (requestCode == 1) {
            presenter.getSortShopInfo(storeId, "", 1 + "", true, false);
        }
    }

    public void upadateShop(String name, String des, String avatar, String img) {
        success = true;
        dismissDialog();
        myshop_shopNameTv.setText(name);
        storeName = name;
        myshop_shopDesTv.setText(des);
        if (avatar.equals("")) {
            myshop_HeadIv.setImageResource(R.drawable.main_myhead);
        } else {
            headUrl = avatar;
            Glide.with(this).load(avatar).error(R.drawable.huisebeijing).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(myshop_HeadIv);

        }
        if (img.equals("")) {
            myshop_shopIv.setImageResource(R.drawable.main_back);
        } else {
            backUrl = img;
            Glide.with(this).load(img).error(R.drawable.huisebeijing).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(myshop_shopIv);

        }
    }

//    public void upadateAdapter(SortListInfo info, int position) {
//        if (info != null) {
//            adapter.getLists().set(position, info);
//            adapter.notifyDataSetChanged();
//        }
//    }
}
