package com.danding.yang800;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
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.danding.yang800.Entity.GoodsInfo;
import com.danding.yang800.Entity.ThumbViewInfo;
import com.danding.yang800.Presenter.GoodsInfoActivityPresenter;
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.ToastUtil;
import com.danding.yang800.View.BannerView;
import com.danding.yang800.View.GoTopScrollView;
import com.danding.yang800.View.PreviewLayout;
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.util.ArrayList;
import java.util.HashMap;
import java.util.List;

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

public class GoodsInfoActivity extends BaseActivity {
    @BindView(R.id.goodsInfo_goodsIntroduceTV)
    TextView goodsInfo_goodsIntroduceTV;
    @BindView(R.id.goodsInfo_goodsIntroduceLineIV)
    TextView goodsInfo_goodsIntroduceLineIV;
    @BindView(R.id.goodsInfo_goodsparameterLineIV)
    TextView goodsInfo_goodsparameterLineIV;
    @BindView(R.id.goodsInfo_goodsIntroduceLayout)
    RelativeLayout goodsInfo_goodsIntroduceLayout;
    @BindView(R.id.goodsInfo_goodsparameterLayout)
    RelativeLayout goodsInfo_goodsparameterLayout;
    @BindView(R.id.goodsInfo_goodsInfoScollView)
    GoTopScrollView goodsInfo_goodsInfoScollView;
    //    @BindView(R.id.goodsInfo_goodsparameterInfoLayout)
//    LinearLayout goodsInfo_goodsparameterInfoLayout;
    @BindView(R.id.goodsInfo_goodsInfoReturnTopIv)
    ImageView goodsInfo_goodsInfoReturnTopIv;
    @BindView(R.id.goodsInfo_backTv)
    TextView goodsInfo_backTv;
    @BindView(R.id.goodsInfo_priceTv)
    TextView goodsInfo_priceTv;

    private Rect mRVBounds = new Rect();
    private int mStatusBarHeight;
    @BindView(R.id.document_View)
    RelativeLayout document_View;
    private List<ThumbViewInfo> mThumbViewInfoList = new ArrayList<>();
    FrameLayout container;
    //    @BindView(R.id.banner1)
//    BannerView banner1;
    @BindView(R.id.goodsInfo_goodsIv)
    ImageView goodsInfo_goodsIv;
    @BindView(R.id.goodsInfo_goodsShareTv)
    TextView goodsInfo_goodsShareTv;
    @BindView(R.id.goodsInfo_goodsShareIv)
    ImageView goodsInfo_goodsShareIv;
    PreviewLayout mPreviewLayout;
    UMWeb web;
    GoodsInfoActivityPresenter presenter;
    SharedPreferences sp;
    @BindView(R.id.goodsInfo_goodsNameTv)
    TextView goodsInfo_goodsNameTv;
    @BindView(R.id.goodsInfo_webview)
    WebView goodsInfo_webview;
    @BindView(R.id.goodsInfo_priceIntTv)
    TextView goodsInfo_priceIntTv;
    @BindView(R.id.goodsInfo_profitIntTv)
    TextView goodsInfo_profitIntTv;
    @BindView(R.id.goodsInfo_profitTv)
    TextView goodsInfo_profitTv;
    @BindView(R.id.goodsTaxTv)
    TextView goodsTaxTv;
    @BindView(R.id.goodsInfo_countryNameTv)
    TextView goodsInfo_countryNameTv;
    @BindView(R.id.goodsInfo_depotNameTv)
    TextView goodsInfo_depotNameTv;
    @BindView(R.id.goodsWeightTv)
    TextView goodsWeightTv;
    @BindView(R.id.goodsInfo_lineLayout)
    RelativeLayout goodsInfo_lineLayout;
    @BindView(R.id.goodsInfo_typeLayout)
    LinearLayout goodsInfo_typeLayout;
    @BindView(R.id.goodsInfo_skuMarketInventoryTv)
    TextView goodsInfo_skuMarketInventoryTv;
    @BindView(R.id.goodsInfo_changePriceIv)
    ImageView goodsInfo_changePriceIv;
    @BindView(R.id.goodsInfo_hideTv)
    TextView goodsInfo_hideTv;
    @BindView(R.id.goodsInfo_expFreeTv)
    TextView goodsInfo_expFreeTv;
    @BindView(R.id.goodsInfo_taxFreeTv)
    TextView goodsInfo_taxFreeTv;
    String shareUrl = "";
    String title = "";
    String storeName = "";
    String imageUrl = "";
    String goodsSubtitle = "";
    String goodsinfo = "";
    String goodsNotice = "";

    @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_goods_info);
        Sofia.with(this).statusBarDarkFont().statusBarBackground(ContextCompat.getColor(this, R.color.white));
        ButterKnife.bind(this);
        sp = getSharedPreferences("variable", Context.MODE_PRIVATE);
        Intent intent = getIntent();
        String ifUp = intent.getStringExtra("ifUp");
        String goodsSn = intent.getStringExtra("goodsSn");
        String skuSn = intent.getStringExtra("skuSn");
        shareUrl = intent.getStringExtra("shareUrl");
        title = intent.getStringExtra("title");
        storeName = intent.getStringExtra("storeName");
        imageUrl = intent.getStringExtra("imageUrl");
        goodsSubtitle = intent.getStringExtra("goodsSubtitle");
        if (ifUp.equals("上架")) {
            goodsInfo_goodsShareTv.setVisibility(View.INVISIBLE);
            goodsInfo_goodsShareIv.setVisibility(View.INVISIBLE);
        }
        initWeb();
        View view;
        presenter = new GoodsInfoActivityPresenter(this);
        presenter.getGoodsInfo(sp.getString("storeId", ""), goodsSn, skuSn);
//        int resId = getResources().getIdentifier("status_bar_height", "dimen", "android");
//        mStatusBarHeight = getResources().getDimensionPixelSize(resId);
        goodsInfo_goodsInfoScollView.setImgeViewOnClickGoToFirst(goodsInfo_goodsInfoReturnTopIv);
//        container = (FrameLayout) findViewById(android.R.id.content);
//        List<BannerItem> list = new ArrayList<>();
//        for (int i = 0; i < urls.length; i++) {
//            BannerItem item = new BannerItem();
//            item.image = urls[i];
////            item.title = titles[i];
//            mThumbViewInfoList.add(new ThumbViewInfo(urls[i], i));
//            list.add(item);
//        }
//        banner1.setViewFactory(new BannerViewFactory(this));
//        banner1.setDataList(list);
//        banner1.start();
//        banner1.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                ToastUtil.show(GoodsInfoActivity.this, "444");
//            }
//        });


    }

    private void initWeb() {
        WebSettings wSet = goodsInfo_webview.getSettings();
        wSet.setJavaScriptEnabled(true);
        goodsInfo_webview.clearCache(true);
        goodsInfo_webview.setWebChromeClient(new WebChromeClient() {
        });
        goodsInfo_webview.getSettings().setAllowFileAccess(true);
        goodsInfo_webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        goodsInfo_webview.getSettings().setJavaScriptEnabled(true);
        goodsInfo_webview.getSettings().setUseWideViewPort(true);
        goodsInfo_webview.getSettings().setLoadWithOverviewMode(true);

    }


    @OnClick({R.id.goodsInfo_goodsIntroduceLayout, R.id.goodsInfo_goodsparameterLayout
            , R.id.goodsInfo_backTv, R.id.goodsInfo_goodsShareTv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.goodsInfo_backTv:
                finish();
                break;
            case R.id.goodsInfo_goodsShareTv:
                ShareUtil.share(GoodsInfoActivity.this, shareUrl, title,goodsSubtitle, imageUrl,0);
                break;
            case R.id.goodsInfo_goodsIntroduceLayout:
                goodsInfo_webview.clearCache(true);
                goodsInfo_goodsIntroduceLineIV.setVisibility(View.VISIBLE);
                goodsInfo_goodsparameterLineIV.setVisibility(View.INVISIBLE);
//                goodsInfo_webview.setVisibility(View.VISIBLE);
//                goodsInfo_goodsparameterInfoLayout.setVisibility(View.GONE);
                LogUtil.d(goodsinfo + "goodsinfo");
                goodsInfo_webview.loadDataWithBaseURL(null, goodsinfo, "text/html", "utf-8",
                        null);
                break;
            case R.id.goodsInfo_goodsparameterLayout:
                goodsInfo_webview.clearCache(true);
                goodsInfo_goodsIntroduceLineIV.setVisibility(View.INVISIBLE);
                goodsInfo_goodsparameterLineIV.setVisibility(View.VISIBLE);
//                goodsInfo_webview.setVisibility(View.GONE);
//                goodsInfo_goodsparameterInfoLayout.setVisibility(View.VISIBLE);
                goodsInfo_webview.loadDataWithBaseURL(null, goodsNotice, "text/html", "utf-8",
                        null);
                break;

        }
    }

    //    public static String[] titles = new String[]{
//    };
    public static String[] urls = new String[]{//750x500
            "https://img20.360buyimg.com/da/jfs/t9466/201/1546408582/116954/173761ac/59c36194N9a1387f1.jpg",
            "https://img14.360buyimg.com/babel/jfs/t9316/174/1567985127/155298/d1d2dc7d/59c3977cN202624dc.jpg",
            "https://img10.360buyimg.com/babel/jfs/t9469/106/2105789592/71916/a62391c/59c4cae0N03a5a8d9.jpg",
    };

    public void updateData(String goodsName, String skuImageUrl, String profitInt, String profit, String priceInt,
                           String price, String goodsContent, String goodsTax, String skuMarketInventory
            , boolean storePriceChange, String countryName, String depotName, String goodsType, String weight, String stats
            , String buyNoticeImg, boolean taxFree, boolean expFree) {
        goodsInfo_goodsNameTv.setText(goodsName);
        goodsInfo_priceIntTv.setText(priceInt);
        goodsInfo_priceTv.setText(price);
        goodsInfo_profitIntTv.setText(profitInt);
        goodsInfo_profitTv.setText(profit);
        goodsTaxTv.setText("税率：" + goodsTax + "%");

        if (stats.equals("3")) {
            goodsInfo_skuMarketInventoryTv.setText("库存：" + 0);
        } else {
            goodsInfo_skuMarketInventoryTv.setText("库存：" + skuMarketInventory);
        }

        goodsWeightTv.setText("商品计重：" + weight + "kg");
        if (goodsType.equals("2")) {
            goodsTaxTv.setVisibility(View.INVISIBLE);
            goodsInfo_lineLayout.setVisibility(View.GONE);
            goodsInfo_typeLayout.setVisibility(View.GONE);
            goodsInfo_hideTv.setVisibility(View.VISIBLE);
        } else {
            goodsInfo_lineLayout.setVisibility(View.VISIBLE);
            goodsInfo_typeLayout.setVisibility(View.VISIBLE);
            goodsInfo_hideTv.setVisibility(View.GONE);
            goodsInfo_countryNameTv.setText(countryName + "品牌");
            goodsInfo_depotNameTv.setText(depotName);
        }
        if (expFree) {
            goodsInfo_expFreeTv.setVisibility(View.VISIBLE);
        } else {
            goodsInfo_expFreeTv.setVisibility(View.GONE);
        }
        if (taxFree) {
            goodsTaxTv.setVisibility(View.INVISIBLE);
            goodsInfo_taxFreeTv.setVisibility(View.VISIBLE);
        } else {
            goodsInfo_taxFreeTv.setVisibility(View.GONE);
        }
        if (storePriceChange) {
            goodsInfo_changePriceIv.setVisibility(View.VISIBLE);
        } else {
            goodsInfo_changePriceIv.setVisibility(View.GONE);
        }
        Glide.with(this).load(skuImageUrl).error(R.drawable.huisebeijing).diskCacheStrategy(DiskCacheStrategy.ALL).into(goodsInfo_goodsIv);
//        LinearLayout lineLayout = new LinearLayout(this);
//        lineLayout.setOrientation(LinearLayout.VERTICAL);
//        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
//                LinearLayout.LayoutParams.MATCH_PARENT,
//                LinearLayout.LayoutParams.WRAP_CONTENT);
//        lineLayout.setLayoutParams(layoutParams);
//        View view;
//        for (int i = 0; i < goodsContent.length; i++) {
//            view = LayoutInflater.from(this).inflate(
//                    R.layout.goodsinfo_iv_layout, null);
//            ImageView goodsInfo_iv = (ImageView) view.findViewById(R.id.goodsInfo_iv);
//            Glide.with(this).load(goodsContent[i]).dontAnimate().
//                    error(R.drawable.huisebeijing).diskCacheStrategy(DiskCacheStrategy.ALL)
//                    .into(goodsInfo_iv);
//            lineLayout.addView(view);
//        }
//        goodsInfo_infoLayout.addView(lineLayout);
        StringBuilder sb = new StringBuilder();
        sb.append("<style>");
        sb.append("img { width:100%;}");
        sb.append("p { -webkit-margin-before:0em; -webkit-margin-after:0em }");
        sb.append("</style>");
        sb.append(goodsContent);
        goodsinfo = sb.toString();
        StringBuilder sbNotice = new StringBuilder();
        sbNotice.append("<style>");
        sb.append("img { width:100%;}");
        sbNotice.append("</style>");
        sbNotice.append(buyNoticeImg);
        goodsNotice = sbNotice.toString();
        goodsInfo_webview.loadDataWithBaseURL(null, goodsinfo, "text/html", "utf-8",
                null);
    }

    public static class BannerItem {
        public String image;
        public String title;

        @Override
        public String toString() {
            return title;
        }
    }

    public class BannerViewFactory implements BannerView.ViewFactory<BannerItem> {
        GoodsInfoActivity context;

        public BannerViewFactory(GoodsInfoActivity context) {
            this.context = context;
        }

        @Override
        public View create(BannerItem item, final int position, final ViewGroup container) {
            ImageView iv = new ImageView(context);
            iv.setScaleType(ImageView.ScaleType.FIT_XY);
            Glide.with(context).load(item.image).
                    diskCacheStrategy(DiskCacheStrategy.SOURCE).into(iv);
//            iv.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    Message message = new Message();
//                    message.what = position;
//                    handler.sendMessage(message);
////                   ToastUtil.show(GoodsInfoActivity.this,"114");
//                }
//            });
            return iv;
        }
    }

    int position;

//    @Override
//    public void onWindowFocusChanged(boolean hasFocus) {
//        super.onWindowFocusChanged(hasFocus);
//        if (hasFocus) {
//            //if (mThumbViewInfoList != null && mThumbViewInfoList.size() > 0) {
//            banner1.getGlobalVisibleRect(mRVBounds);
//            assembleDataList();
////            }
//        }
//    }

//    private void assembleDataList() {
//        computeBoundsForward(0);
//        computeBoundsBackward(0);
//    }
//
//    /**
//     * 从第一个完整可见item顺序遍历
//     */
//    private void computeBoundsForward(final int firstCompletelyVisiblePos) {
//        document_View.post(new Runnable() {
//            @Override
//            public void run() {
////        document_View.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
////            @Override
////            public void onGlobalLayout() {
//                for (int i = firstCompletelyVisiblePos; i < mThumbViewInfoList.size(); i++) {
//                    Rect bounds = new Rect();
//                    if (banner1 != null) {
//                        banner1.getGlobalVisibleRect(bounds);
//                        if (mSolidWidth * mSolidHeight == 0) {
//                            mPadding[0] = banner1.getPaddingLeft();
//                            mPadding[1] = banner1.getPaddingTop();
//                            mPadding[2] = banner1.getPaddingRight();
//                            mPadding[3] = banner1.getPaddingBottom();
//                            mSolidWidth = bounds.width();
//                            mSolidHeight = bounds.height();
//                        }
//                        bounds.left = bounds.left + mPadding[0];
//                        bounds.top = bounds.top + mPadding[1];
//                        bounds.right = bounds.left + mSolidWidth - mPadding[2];
//                        bounds.bottom = bounds.top + mSolidHeight - mPadding[3];
//                    } else {
//                        bounds.left = i % 3 * mSolidWidth + mPadding[0];
//                        bounds.top = mRVBounds.bottom + mPadding[1];
//                        bounds.right = bounds.left + mSolidWidth - mPadding[2];
//                        bounds.bottom = bounds.top + mSolidHeight - mPadding[3];
//                    }
//                    bounds.offset(0, -mStatusBarHeight);
//                    mThumbViewInfoList.get(i).setBounds(bounds);
////                    if (Build.VERSION.SDK_INT >= 16) {
////                        document_View.getViewTreeObserver().removeOnGlobalLayoutListener(this);
////                    } else {
////                        document_View.getViewTreeObserver().removeGlobalOnLayoutListener(this);
////                    }
//                }
//            }
//        });
//    }
//
//    private int mSolidWidth = 0;
//    private int mSolidHeight = 0;
//    private int[] mPadding = new int[4];
//
//    /**
//     * 从第一个完整可见item逆序遍历，如果初始位置为0，则不执行方法内循环
//     */
//    private void computeBoundsBackward(int firstCompletelyVisiblePos) {
//        for (int i = firstCompletelyVisiblePos - 1; i >= 0; i--) {
//            Rect bounds = new Rect();
//            if (banner1 != null) {
//
//                banner1.getGlobalVisibleRect(bounds);
//
//                bounds.left = bounds.left + mPadding[0];
//                bounds.bottom = bounds.bottom - mPadding[3];
//                bounds.right = bounds.left + mSolidWidth - mPadding[2];
//                bounds.top = bounds.bottom - mSolidHeight + mPadding[1];
//            } else {
//                bounds.left = i % 3 * mSolidWidth + mPadding[0];
//                bounds.bottom = mRVBounds.top - mPadding[3];
//                bounds.right = bounds.left + mSolidWidth - mPadding[2];
//                bounds.top = bounds.bottom - mSolidHeight + mPadding[1];
//            }
//            bounds.offset(0, -mStatusBarHeight);
//
//            mThumbViewInfoList.get(i).setBounds(bounds);
//
//        }
//    }
//
//    @Override
//    public void onBackPressed() {
//        if (container.getChildAt(container.getChildCount() - 1) instanceof PreviewLayout) {
//            mPreviewLayout.startScaleDownAnimation();
//            banner1.setCurrentPosition(mPreviewLayout.pos);
//            banner1.mIsResumed = true;
//            banner1.update();
//            return;
//        }
//        super.onBackPressed();
//    }

}
