package com.gh.gamecenter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.Animatable;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.controller.ControllerListener;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.image.ImageInfo;
import com.gh.gamecenter.common.base.activity.ToolBarActivity;
import com.gh.gamecenter.common.constant.EntranceConsts;
import com.gh.gamecenter.common.utils.ImageUtils;
import com.gh.common.util.MessageShareUtils;
import com.gh.common.util.QRCodeUtils;
import com.gh.gamecenter.core.utils.StringUtils;
import com.gh.gamecenter.entity.ConcernEntity;
import com.gh.gamecenter.common.retrofit.ObservableUtil;

import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.CountDownLatch;

import io.reactivex.functions.Consumer;

/**
 * Created by khy on 2016/11/7.
 */
public class ShareCardPicActivity extends ToolBarActivity {

    TextView mShareContentTv;
    TextView mShareGameNameTv;
    SimpleDraweeView mShareGameIconDv;
    ImageView mShareQrCodeDv;
    SimpleDraweeView mShareContentImgRv;
    ScrollView mShareScreenshotRl;
    View mActionbar;
    RelativeLayout mShareChangImageRl;
    RelativeLayout mShareShareRl;
    ImageView mShareChangImageIcon;
    TextView mShareChangImageTv;

    public static final String KEY_SHARE_ARRIMG = "shareArrImg";

    private String gameName;
    private String gameIconUrl;
    private String shareContent;
    private String picName;

    private int currentImgPosition;

    private List<String> shareArrImg;

    private Bitmap shareBm;

    private CountDownLatch latch;

    private String newsId;

    public static void startShareCardPicActivity(Context context, ConcernEntity concernEntity, String entrance) {

        final String shareContent;
        if (concernEntity.getBrief() != null) {
            shareContent = concernEntity.getBrief();
        } else {
            shareContent = concernEntity.getContent();
        }

        Intent intent = new Intent(context, ShareCardPicActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString(EntranceConsts.KEY_GAMENAME, concernEntity.getGameName());
        bundle.putString(EntranceConsts.KEY_GAME_ICON_URL, concernEntity.getGameIcon());
        bundle.putString(EntranceConsts.KEY_SHARECONTENT, shareContent);
        if (concernEntity.getLink() == null) {
            bundle.putString(EntranceConsts.KEY_NEWSID, concernEntity.getId());
        }
        if (concernEntity.getImg() != null && concernEntity.getImg().size() > 0) {
            bundle.putStringArrayList(KEY_SHARE_ARRIMG, (ArrayList<String>) concernEntity.getImg());
        }
        intent.putExtras(bundle);
        intent.putExtra(EntranceConsts.KEY_ENTRANCE, StringUtils.buildString(entrance, "+(消息详情[", concernEntity.getGameName(), "])"));
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_sharecard_pic;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initView();

        Bundle extras = getIntent().getExtras();
        gameName = extras.getString(EntranceConsts.KEY_GAMENAME);
        gameIconUrl = extras.getString(EntranceConsts.KEY_GAME_ICON_URL);
        shareContent = extras.getString(EntranceConsts.KEY_SHARECONTENT);
        newsId = extras.getString(EntranceConsts.KEY_NEWSID);
        List<String> arrImg = extras.getStringArrayList(KEY_SHARE_ARRIMG);

        picName = "shareImgPic.jpg";
        currentImgPosition = 0;

        setNavigationTitle(getString(R.string.title_share_card_pic));

        shareArrImg = new Vector<>();
        if (arrImg != null) shareArrImg.addAll(arrImg);

        mActionbar.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), android.R.color.black));

        latch = ObservableUtil.latch(shareArrImg.size(), new Consumer<Object>() {
            @Override
            public void accept(Object o) {
                ShareCardPicActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        setContentImage(shareArrImg.get(0));
                        currentImgPosition++;
                    }
                });
            }
        }, new Object());

        for (int i = 0; i < shareArrImg.size(); i++) {
            checkUrl(shareArrImg.get(i), shareArrImg.size(), i);
        }

        mShareGameNameTv.setText(gameName);
        mShareContentTv.setText(Html.fromHtml(shareContent));
//        mShareGameIconDv.setImageURI(gameIconUrl);
        ImageUtils.display(mShareGameIconDv, gameIconUrl);
        mShareQrCodeDv.setImageResource(R.drawable.test_qrcode);

        if (shareArrImg.size() > 1) {
            mShareChangImageIcon.setImageResource(R.drawable.sharecard_chang_img);
            mShareChangImageTv.setTextColor(Color.WHITE);
        } else {
            mShareChangImageIcon.setImageResource(R.drawable.sharecard_unchang_img);
            mShareChangImageTv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.hint));
        }

        String qrBody;
        if (!TextUtils.isEmpty(newsId)) {
            qrBody = "http://www.ghzs666.com/article/" + newsId + ".html?source=appshare200";
        } else {
            qrBody = "https://www.ghzs.com/?source=appshare200";
        }
        QRCodeUtils.setQRCode(this, qrBody, mShareQrCodeDv);


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
            builder.detectFileUriExposure();
        }
    }

    private void initView() {
        mShareContentTv = findViewById(R.id.sharecard_content);
        mShareGameNameTv = findViewById(R.id.sharecard_game_name);
        mShareGameIconDv = findViewById(R.id.sharecard_game_icon);
        mShareQrCodeDv = findViewById(R.id.sharecard_qrcode);
        mShareContentImgRv = findViewById(R.id.sharecard_game_content_img);
        mShareScreenshotRl = findViewById(R.id.sharecard_screenshot);
        mActionbar = findViewById(R.id.normal_toolbar_container);
        mShareChangImageRl = findViewById(R.id.sharecard_chang_img);
        mShareShareRl = findViewById(R.id.sharecard_share_btn);
        mShareChangImageIcon = findViewById(R.id.sharecard_chang_img_icon);
        mShareChangImageTv = findViewById(R.id.sharecard_chang_img_tv);

        mShareShareRl.setOnClickListener(v -> {
            if (shareBm != null && shareBm.isRecycled()) {
                shareBm.isRecycled();
            }

            shareBm = getBitmapByView(mShareScreenshotRl);
            saveBitmap(shareBm);
            MessageShareUtils.getInstance(ShareCardPicActivity.this).showShareWindows(ShareCardPicActivity.this, getWindow().getDecorView(), shareBm, picName, 1);
        });

        mShareChangImageRl.setOnClickListener(v -> {
            if (currentImgPosition > shareArrImg.size() - 1) {
                currentImgPosition = 0;
            }

            setContentImage(shareArrImg.get(currentImgPosition));
            currentImgPosition++;
        });
    }

    private void setContentImage(String url) {
        ControllerListener<ImageInfo> listener = new BaseControllerListener<ImageInfo>() {
            @Override
            public void onFinalImageSet(String id, ImageInfo imageInfo, Animatable animatable) {
                super.onFinalImageSet(id, imageInfo, animatable);
                if (imageInfo == null) {
                    return;
                }
                int height = imageInfo.getHeight();
                int width = imageInfo.getWidth();
                float index = (float) height / (float) width;
                ViewGroup.LayoutParams layoutParams = mShareContentImgRv.getLayoutParams();
                int widthPixels = getResources().getDisplayMetrics().widthPixels;
                if (index > 1) {
                    layoutParams.height = widthPixels;

                } else {
                    layoutParams.height = (int) (index * widthPixels);
                }
                mShareContentImgRv.setLayoutParams(layoutParams);
            }
        };

        DraweeController controller = Fresco.newDraweeControllerBuilder()
                .setUri(url)
                .setControllerListener(listener)
                .build();

        mShareContentImgRv.setController(controller);
    }

//    private void createQrCode() {
//        Observable
//                .create(new Observable.OnSubscribe<String>() {
//                    @Override
//                    public void call(Subscriber<? super String> subscriber) {
//                        String filePath = getExternalCacheDir().getPath() + "/ShareImg/ShareQRCode.jpg";
//                        boolean success = QRCodeUtils.createQRImage("http://www.ghzs666.com/article/" + newsId + ".html?source=appshare200"
//                                , 200, 200, filePath, ShareCardPicActivity.this);
//                        if (success) {
//                            subscriber.onNext(filePath);
//                        }
//                        subscriber.onCompleted();
//                    }
//                })
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Response<String>(){
//                    @Override
//                    public void onResponse(String response) {
//                        super.onResponse(response);
//                        mShareQrCodeDv.setImageBitmap(BitmapFactory.decodeFile(response));
//                    }
//                });
//    }

    private void checkUrl(final String url, final int size, final int position) {
        new Thread() {
            @Override
            public void run() {
                try {
                    String newUrl = "http://image.ghzs666.com/pic/hq" + url.substring(url.lastIndexOf("/"));
                    HttpURLConnection connection = (HttpURLConnection) new URL(newUrl).openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(5 * 1000);
                    connection.setReadTimeout(5 * 1000);
                    connection.connect();
                    int code = connection.getResponseCode();
                    if (code == 200) {
                        shareArrImg.remove(position);
                        shareArrImg.add(position, newUrl);

                        latch.countDown();
                    } else {
                        latch.countDown();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    public static Bitmap getBitmapByView(ScrollView scrollView) {
        int h = 0;
        Bitmap bitmap;

        // 获取scrollview实际高度
        for (int i = 0; i < scrollView.getChildCount(); i++) {
            h += scrollView.getChildAt(i).getHeight();
            scrollView.getChildAt(i).setBackgroundColor(Color.WHITE);
        }

        // 创建对应大小的bitmap
        bitmap = Bitmap.createBitmap(scrollView.getWidth(), h,
                Bitmap.Config.ARGB_8888);
        final Canvas canvas = new Canvas(bitmap);
        scrollView.draw(canvas);

        return bitmap;
    }

    public void saveBitmap(Bitmap bm) {
        File file = new File(MessageShareUtils.getSaveBitmapBasePath(this));
        if (!file.isDirectory()) {
            file.delete();
            file.mkdirs();
        }
        if (!file.exists()) {
            file.mkdirs();
        }
        MessageShareUtils.getInstance(ShareCardPicActivity.this).writeBitmap(file.getPath(), picName, bm, false);
    }
}
