package com.taikor.investment.modules.find;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.widget.TextView;

import com.taikor.investment.R;
import com.taikor.investment.base.BaseActivity;
import com.taikor.investment.mylibrary.TAnalytics;
import com.taikor.investment.utils.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import es.voghdev.pdfviewpager.library.PDFViewPager;
import okhttp3.Call;

/**
 * 研究报告详情
 * Created by Any on 2017/4/11.
 */
public class ReportDescActivity extends BaseActivity {

    @BindView(R.id.tv_bar_title)
    TextView tvBarTitle;

    private File file;
    PDFViewPager pdfView;
    private String fileId, fileName;
    private ProgressDialog progressDialog;

    private static final String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE"};
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static final String URL = "https://api.palaspom.com/investment/DownloadReport?FileId=";


    @Override
    public int getContentViewId() {
        return R.layout.activity_find_report_desc;
    }

    @Override
    public void initView() {
        tvBarTitle.setText("研究报告详情");
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage(getString(R.string.progress_hint));
        progressDialog.setCancelable(true);
        progressDialog.show();

        Intent intent = getIntent();
        fileId = intent.getStringExtra("fileId");
        fileName = intent.getStringExtra("fileName");

        verifyStoragePermissions(this);
    }

    // 获取权限
    public void verifyStoragePermissions(Activity activity) {

        try {
            //检测是否有写的权限
            int permission = ActivityCompat.checkSelfPermission(activity,
                    "android.permission.WRITE_EXTERNAL_STORAGE");
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有写的权限，去申请写的权限，会弹出对话框
                ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
            } else {
                loadFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 授权结果
     *
     * @param requestCode  请求码
     * @param permissions  权限
     * @param grantResults 授权结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_EXTERNAL_STORAGE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    loadFile();
                }
                break;
        }
    }

    //加载文件
    public void loadFile() {
        //文件存储
        file = new File(Environment.getExternalStorageDirectory(), fileName);
        if (file.exists()) { //如果本地有此文件，直接打开
            progressDialog.dismiss();
            pdfView = new PDFViewPager(ReportDescActivity.this, file.getAbsolutePath());
            setContentView(pdfView);
        } else {
            download(URL + fileId);//本地没有此文件 则从网上下载打开
        }
    }

    //下载文件
    public void download(String url) {
        OkHttpUtils.get().url(url).build()
                .execute(new FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath(), fileName) {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ToastUtils.showShort(ReportDescActivity.this, "文件加载失败");
                    }

                    @Override
                    public void onResponse(File response, int id) {
                        progressDialog.dismiss();
                        pdfView = new PDFViewPager(ReportDescActivity.this, file.getAbsolutePath());
                        setContentView(pdfView);
                    }
                });
    }

    //埋点
    @Override
    protected void onResume() {
        super.onResume();
        TAnalytics.onPageStart("reportDetailPage");
    }

    @Override
    protected void onPause() {
        super.onPause();
        TAnalytics.onPageLoad("reportDetailPage", "reportListPage", "", "");
    }

    @OnClick(R.id.tv_bar_back)
    public void onClick() {
        finish();
    }
}
