package com.rv.poster.plugin;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
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.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.CommonPresenter;
import com.ruiwenliu.wrapper.bean.BeanUserInfo;
import com.ruiwenliu.wrapper.bean.UserInfoBean;
import com.ruiwenliu.wrapper.util.TransformationUtil;
import com.ruiwenliu.wrapper.util.glide.GlideManager;
import com.ruiwenliu.wrapper.util.glide.GlideOptions;
import com.ruiwenliu.wrapper.util.um.CustomShareListener;
import com.ruiwenliu.wrapper.util.um.ShareManager;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.rv.component.utils.CacheEnum;
import com.rv.component.utils.DisplayUtil;
import com.rv.component.utils.IsAppInstall;
import com.rv.component.utils.RvCache;
import com.rv.component.utils.ShareUtils;
import com.rv.component.utils.ZxingUtils;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.ShareBoardlistener;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 租车、旅游、营地海报分享
 */
@Route(path = Constance.ACTIVITY_URL_POSTERACTIVITY)
public class PosterActivity extends BaseStatusActivity<CommonPresenter> {


    @BindView(R2.id.img_bill_top)
    ImageView imgBillTop;
    @BindView(R2.id.ring_header)
    ImageView ringHeader;
    @BindView(R2.id.tv_name)
    TextView tvName;
    @BindView(R2.id.img_qrcode)
    ImageView imgQrcode;
    @BindView(R2.id.ll_bill_content)
    CardView llBillContent;

    @Autowired()
    String url;

    @Autowired()
    String imageUrl;


    private ShareManager shareManager;
    private Bitmap bitmap = null;
    private UMImage image = null;

    @Override
    protected int setLayout() {
        return R.layout.activity_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(imageUrl)
                .apply(options)
                .apply(RequestOptions
                        .bitmapTransform(new RoundedCorners(12)).override(imgBillTop.getWidth(), imgBillTop.getHeight())
                        .disallowHardwareConfig())
                .into(utils);

        UserInfoBean userInfoBean = (UserInfoBean) RvCache.getInstance(getApplicationContext()).get(CacheEnum.USER);
        if (userInfoBean != null && userInfoBean.getData() != null) {
            String name = userInfoBean.getData().getNickname();
            String url = userInfoBean.getData().getHeadimgurl();
            if (!TextUtils.isEmpty(url)) {
                GlideManager.getInstance(mActivity).loadCircleImage(url, ringHeader);
            } else {
                ringHeader.setImageResource(R.drawable.icon_bill_defult);
            }
            if (!TextUtils.isEmpty(name)) {
                tvName.setText(name);
            }
        }
    }

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

    }


    @OnClick({R2.id.tv_item_save_bill, R2.id.tv_item_share})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.tv_item_save_bill) {
            preShare(0, 1001);
        } else if (id == R.id.tv_item_share) {
            preShare(1, 1002);
        }
    }


    /**
     * 预备下载 进行 6.0权限检查
     */
    private void preShare(int type, int requestCode) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            if (type == 0) {
                saveBill(llBillContent);
            } else {
                share(llBillContent);
            }
        } else {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                if (type == 0) {
                    saveBill(llBillContent);
                } else {
                    share(llBillContent);
                }
            } else {//申请权限
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
            }
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1001:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    saveBill(llBillContent);
                } else {
                    showToast("授权失败,无法分享海报");
                }
                break;
            case 1002:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    share(llBillContent);
                } else {
                    showToast("授权失败,无法分享海报");
                }
                break;
        }
    }

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


    /******
     * 分享
     */
    public void share(View view) {
        if (shareManager == null) {

            if (view != null && bitmap == null) {
                bitmap = ShareUtils.viewConversionBitmap(view);
            }
            File file = null;
            if (bitmap != null) {
                file = ShareUtils.saveBitmapFile(mActivity, bitmap);
            }
            if (file != null) {
                image = new UMImage(mActivity, file);//bitmap文件
                UMImage thumb = new UMImage(this, file);
                image.setThumb(thumb);
                image.compressStyle = UMImage.CompressStyle.SCALE;//大小压缩，默认为大小压缩，适合普通很大的图
                image.compressStyle = UMImage.CompressStyle.QUALITY;//质量压缩，适合长图的分享
                image.compressFormat = Bitmap.CompressFormat.PNG;
            }

            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.showShareImage2(share_media, image, 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();
    }


    /*****
     * 保存海报
     * @param view
     */
    public void saveBill(View view) {
        if (view != null) {
            Bitmap bitmap = ShareUtils.viewConversionBitmap(view);
            File file = null;
            if (bitmap != null) {
                file = ShareUtils.saveBitmapFile(mActivity, bitmap);
            }
            if (file != null) {
                showToast("海报保存在" + file.getAbsolutePath());
            }
        }
    }
}
