package com.xxfc.discovery.other;

import android.Manifest;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.base.utils.ui.image.round.RoundImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.frame.base.url.Constance;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseStatusActivity;
import com.ruiwenliu.wrapper.base.presenter.PickerPresenter;
import com.ruiwenliu.wrapper.util.TransformationUtil;
import com.ruiwenliu.wrapper.util.ViewHolder;
import com.ruiwenliu.wrapper.util.glide.GlideManager;
import com.ruiwenliu.wrapper.util.glide.GlideOptions;
import com.ruiwenliu.wrapper.util.permission.RxPermission;
import com.ruiwenliu.wrapper.util.um.CustomShareListener;
import com.ruiwenliu.wrapper.util.um.ShareManager;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.rv.component.dialog.PickerDialog;
import com.rv.component.utils.DisplayUtil;
import com.rv.component.utils.IsAppInstall;
import com.rv.component.utils.ZxingUtils;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.ShareBoardlistener;
import com.xxfc.discovery.R;
import com.xxfc.discovery.R2;
import com.xxfc.discovery.presenter.DiscoveryPresenter;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;
import pub.devrel.easypermissions.AppSettingsDialog;

/**
 * 拍拍生成海报
 */
@Route(path = Constance.ACTIVITY_URL_PATGENERATEPOSTER)
public class PatGeneratePosterActivity extends BaseStatusActivity<PickerPresenter> {

    @BindView(R2.id.img_bill_top)
    ImageView imgBillTop;
    @BindView(R2.id.tv_content)
    TextView tvContent;
    @BindView(R2.id.ring_header)
    ImageView ringHeader;
    @BindView(R2.id.img_qrcode)
    ImageView imgQrcode;
    @BindView(R2.id.ll_bill_content)
    CardView llBillContent;
    @BindView(R2.id.tv_username)
    TextView tvUsername;

    @Autowired()
    String iconUrl;

    @Autowired()
    String content;

    @Autowired()
    String url;

    @Autowired()
    String userUrl;

    @Autowired()
    String userName;

    private ShareManager shareManager;

    @Override
    protected int setLayout() {
        return R.layout.activity_pat_generate_poster;
    }

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        titleView.setTitle("生成海报");

        if (!TextUtils.isEmpty(url)) {
            Bitmap bitmap = ZxingUtils.createQR(url, DisplayUtil.dip2px(this, 150), DisplayUtil.dip2px(this, 150));
            imgQrcode.setImageBitmap(bitmap);
        }

//        GlideOptions options = GlideOptions.placeholderOf(com.ruiwenliu.wrapper.R.drawable.glide_icon_placeholder).
//                error(com.ruiwenliu.wrapper.R.drawable.glide_icon_error);
//        TransformationUtil utils = new TransformationUtil(imgBillTop);
//        Glide.with(this)
//                .asBitmap()
//                .load(iconUrl)
//                .apply(options)
//                .apply(RequestOptions
//                        .bitmapTransform(new RoundedCorners(12)).override(imgBillTop.getWidth(), imgBillTop.getHeight())
//                        .disallowHardwareConfig())
//                .into(utils);


        GlideManager.getInstance(mActivity).loadRoundImage(iconUrl, imgBillTop, 8);
        tvContent.setText(content);
        if (!TextUtils.isEmpty(userUrl)) {
            GlideManager.getInstance(mActivity).loadCircleImage(userUrl, ringHeader);
        } else {
            ringHeader.setImageResource(R.drawable.icon_bill_defult);
        }
        tvUsername.setText(userName);
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {

    }


    @OnClick({R2.id.btn_replace_bill, R2.id.btn_share})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.btn_replace_bill) {
            changePoster();
        } else if (id == R.id.btn_share) {
            if (llBillContent != null && getViewBitmap(llBillContent) != null) {
                initShare(getViewBitmap(llBillContent));
            }
        }
    }

    /**
     * 更换海报
     */
    private void changePoster() {
        new PickerDialog(mActivity) {
            @Override
            public void helper(ViewHolder helper) {
                super.helper(helper);
                helper.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int i = v.getId();
                        if (i == R.id.btn_camera) {
                            processPicker(mPresenter.TYPE_CAMERA_CODE);
                            dismiss();

                        } else if (i == R.id.btn_album) {
                            processPicker(mPresenter.TYPE_ALBUM_CODE);
                            dismiss();

                        } else if (i == R.id.btn_cancel) {
                            dismiss();
                        }

                    }
                }, R.id.btn_camera, R.id.btn_album, R.id.btn_cancel);
            }
        }.show();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == mPresenter.TYPE_ALBUM_CODE) {
            if (data != null && data.getData() != null) {
                mPresenter.cropPhoto2(data.getData());
            }
        } else if (requestCode == mPresenter.TYPE_CAMERA_CODE && resultCode == RESULT_OK) {
            if (!TextUtils.isEmpty(mPresenter.gerCameraStoreUrl())) {
                mPresenter.cropPhoto2(Uri.fromFile(new File(mPresenter.gerCameraStoreUrl())));
            }
        } else if (requestCode == mPresenter.TYPE_CROP_CODE && resultCode == RESULT_OK) {
            String url = mPresenter.gerCameraStoreUrl();
//            GlideManager.getInstance(mActivity).loadRoundImage(url, imgBillTop, 8);

            GlideOptions options = GlideOptions.placeholderOf(com.ruiwenliu.wrapper.R.drawable.glide_icon_placeholder).
                    error(com.ruiwenliu.wrapper.R.drawable.glide_icon_error);
            TransformationUtil utils = new TransformationUtil(imgBillTop);
            Glide.with(this)
                    .asBitmap()
                    .load(url)
                    .apply(options)
                    .apply(RequestOptions
                            .bitmapTransform(new RoundedCorners(12)).override(imgBillTop.getWidth(), imgBillTop.getHeight())
                            .disallowHardwareConfig())
                    .into(utils);

        }
    }


    /**
     * 打开相机和相册
     *
     * @param type 1、相机2、相册
     */
    private void processPicker(final int type) {
        /**
         * 6.0以上手机做权限处理
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            new RxPermission(mActivity).request(
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA).subscribe(new Consumer<Boolean>() {
                @Override
                public void accept(Boolean aBoolean) throws Exception {
                    if (aBoolean == true) {
                        switch (type) {
                            case 1001:
                                mPresenter.openCamera(false);
                                break;
                            case 1002:
                                mPresenter.openAlbum(false);
                                break;
                        }
                    } else {
                        new AppSettingsDialog.Builder(PatGeneratePosterActivity.this).
                                setTitle("需要获取相机权限、存储权限")
                                .setRationale("如果没有此权限，此应用程序可能无法正常工作,是否打开设置修改该应用权限")
                                .build().show();
                    }
                }
            });
        } else {
            switch (type) {
                case 1001:
                    mPresenter.openCamera(false);
                    break;
                case 1002:
                    mPresenter.openAlbum(false);
                    break;
            }
        }
    }


    /**
     * 屏幕横竖屏切换时避免出现window leak的问题
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        shareManager.close();
    }


    /**
     * 获取scrollview的截屏
     */
    public Bitmap getViewBitmap(View v) {
        int w = v.getWidth();
        int h = v.getHeight();
        int startX = (int) v.getX();
        int startY = (int) v.getY();
        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_4444);
        Canvas c = new Canvas(bmp);
        c.drawColor(Color.WHITE);
        v.layout(startX, startY, w + startX, h + startY);
        v.draw(c);
        v.postInvalidate();
        return bmp;
    }

    /**
     * 初始化分享
     */
    private void initShare(final Bitmap bitmap) {

        if (shareManager == null) {
            shareManager = new ShareManager(this, new ShareBoardlistener() {
                @Override
                public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
                    if (snsPlatform.mShowWord.contains("微信")) {
                        if (!IsAppInstall.isWeixinAvilible(mActivity)) {
                            showToast("亲，您微信还没有安装呢");
                            return;
                        }
                    } else if (snsPlatform.mShowWord.contains("QQ")) {
                        if (!IsAppInstall.isQQClientAvailable(mActivity)) {
                            showToast("亲，您QQ还没有安装呢");
                            return;
                        }
                    }

                    shareManager.showShareImage(share_media, bitmap, new CustomShareListener(mActivity) {
                        @Override
                        public void onResult(SHARE_MEDIA platform) {
                            super.onResult(platform);

                            if (platform.name().equals("WEIXIN_FAVORITE")) {

                                showToast(platform + " 收藏成功啦");

                            } else {
                                if (platform != SHARE_MEDIA.MORE && platform != SHARE_MEDIA.SMS
                                        && platform != SHARE_MEDIA.EMAIL
                                        && platform != SHARE_MEDIA.FLICKR
                                        && platform != SHARE_MEDIA.FOURSQUARE
                                        && platform != SHARE_MEDIA.TUMBLR
                                        && platform != SHARE_MEDIA.POCKET
                                        && platform != SHARE_MEDIA.PINTEREST

                                        && platform != SHARE_MEDIA.INSTAGRAM
                                        && platform != SHARE_MEDIA.GOOGLEPLUS
                                        && platform != SHARE_MEDIA.YNOTE
                                        && platform != SHARE_MEDIA.EVERNOTE) {
                                    showToast(platform + "分享成功啦");

                                }
                            }

                        }
                    });
                }
            });
        }
        shareManager.open();

    }
}
