package com.rv.im;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.daimajia.numberprogressbar.NumberProgressBar;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseStatusActivity;
import com.ruiwenliu.wrapper.base.presenter.CommonPresenter;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.rv.im.db.table.DownBean;
import com.rv.im.glide.GlideOptions;
import com.rv.im.glide.TransformationUtils;
import com.rv.im.mucfile.DownManager;
import com.rv.im.mucfile.FileOpenWays;
import com.rv.im.mucfile.XfileUtils;
import com.rv.im.mucfile.bean.MucFileBean;
import com.rv.im.util.SkinUtils;
import com.rv.im.video.ChatVideoPreviewActivity;

import java.io.File;


/**
 * Created by Administrator on 2017/7/4.
 */
public class MucFileDetails extends BaseStatusActivity<CommonPresenter> implements DownManager.DownLoadObserver, View.OnClickListener {
    private ImageView ivInco;
    private TextView tvName;
    private Button btnStart;
    private TextView tvSize;
    private NumberProgressBar progressPar;
    private MucFileBean data;
    private RelativeLayout rlProgress;
    private TextView tvType;

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

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        titleView.setTitle("详情");
        data = (MucFileBean) getIntent().getSerializableExtra("data");
        initView();
        initDatas();
    }

    @Override
    public void onResume() {
        super.onResume();
        DownManager.instance().addObserver(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        DownManager.instance().deleteObserver(MucFileDetails.this);
    }

    public void initView() {
        ivInco = findViewById(R.id.item_file_inco);
        tvName = findViewById(R.id.item_file_name);
        tvType = findViewById(R.id.item_file_type);
        tvSize = findViewById(R.id.muc_dateils_size);

        btnStart = findViewById(R.id.btn_muc_down);
        btnStart.setBackgroundColor(SkinUtils.getSkin(this).getAccentColor());
        progressPar = findViewById(R.id.number_progress_bar);
        rlProgress = findViewById(R.id.muc_dateils_rl_pro);
        btnStart.setOnClickListener(this);
        findViewById(R.id.muc_dateils_stop).setOnClickListener(this);
        findViewById(R.id.muc_dateils_stop).setOnClickListener(v -> stop());

        tvType.setOnClickListener(v -> {
            if (data.getState() == DownManager.STATE_DOWNLOADING) {
                DownManager.instance().pause(data);
            }
            if (!TextUtils.isEmpty(data.getName()) && data.getName().endsWith("mp3")) { // 音乐在线播放
                Intent intent = new Intent(getApplicationContext(), ChatVideoPreviewActivity.class);
                intent.putExtra(Constants.EXTRA_VIDEO_FILE_PATH, data.getUrl());
                startActivity(intent);
            } else if (!TextUtils.isEmpty(data.getName()) && data.getName().endsWith("mp4") || data.getName().endsWith("avi")) {  // 视频在线播放
                Intent intent = new Intent(getApplicationContext(), ChatVideoPreviewActivity.class);
                intent.putExtra(Constants.EXTRA_VIDEO_FILE_PATH, data.getUrl());
                startActivity(intent);
            } else if (data.getType() == 4 || data.getType() == 5 || data.getType() == 6 || data.getType() == 10) {
                // 在线预览文档，需要解析，上面为微软的，下面为谷歌的(google无法访问)
//                String url = "https://view.officeapps.live.com/op/view.aspx?src=" + data.getUrl();
//                //String url = "https://docs.google.com/viewer?url=" + data.getUrl();
//                Intent intent = new Intent(MucFileDetails.this, WebViewActivity.class);
//                intent.putExtra(EXTRA_URL, url);
//                startActivity(intent);
                Toast.makeText(MucFileDetails.this, "暂不支持该类型文件预览", Toast.LENGTH_SHORT).show();
//                ToastUtil.showToast(MucFileDetails.this, "暂不支持该类型文件预览");
            } else {
//                Intent intent = new Intent(MucFileDetails.this, MucFilePreviewActivity.class);
//                intent.putExtra("data", data);
//                startActivity(intent);
            }
        });
    }

    protected void initDatas() {
        if (data != null) {
            updateUI();
        }
    }

    private void updateUI() {
        if (!TextUtils.isEmpty(data.getUrl()) && data.getUrl().endsWith("png")
                || data.getUrl().endsWith("jpg") || data.getUrl().endsWith("gif")) {
            // 图片直接显示
            GlideOptions options = GlideOptions.placeholderOf(R.mipmap.default_error).
                    error(R.mipmap.default_error).skipMemoryCache(false).centerCrop();
            Glide.with(MucFileDetails.this)
                    .asBitmap()
                    .load(data.getUrl())
                    .apply(options)
                    .apply(RequestOptions.overrideOf(100, 100))
                    .into(new TransformationUtils(ivInco));
        } else {
            // 加载本地
            XfileUtils.setFileInco(data.getUrl(), ivInco);
        }
        tvName.setText(data.getName());

        if (data.getType() == 9) {
            tvType.setText("不支持在线预览");
        } else if (data.getType() == 4 || data.getType() == 5 || data.getType() == 6 || data.getType() == 10) {
            // tvType.setText("该文件暂不支持在线预览");
            tvType.setText("不支持在线预览");
        } else {
            SpannableString type = XfileUtils.matcherSearchTitle(Color.parseColor("#6699FF"),
                    "文件在线预览", "预览");
            tvType.setText(type);
        }

        tvName.setText(data.getName());
        DownBean info = DownManager.instance().getDownloadState(data);
        onDownLoadInfoChange(info);
    }

    @Override
    public void onClick(View v) {
        if (checkNet()) {
            // 检查网络
            switch (data.getState()) {
                case DownManager.STATE_DOWNLOADED:
                    open();
                    break;
                case DownManager.STATE_UNDOWNLOAD:
                    down();
                    break;
                case DownManager.STATE_DOWNLOADING:
                    stop();
                    break;
                case DownManager.STATE_PAUSEDOWNLOAD:
                    start();
                    break;
                case DownManager.STATE_WAITINGDOWNLOAD:
                    cancelDown();
                    break;
                case DownManager.STATE_DOWNLOADFAILED:
                    down();
                    break;
            }
        }
    }

    private void open() {
        File file = new File(DownManager.instance().getFileDir(), data.getName());
        FileOpenWays openWays = new FileOpenWays(this);
        openWays.openFiles(file.getAbsolutePath());
    }

    private void del() {
        DownManager.instance().detele(data);
    }

    private void cancelDown() {
        DownManager.instance().cancel(data);
    }

    private void stop() {
        DownManager.instance().pause(data);
    }

    private void down() {
        DownManager.instance().download(data);
    }

    private void start() {
        DownManager.instance().download(data);
    }

    private boolean checkNet() {
        return true;
    }

    @Override
    public void onDownLoadInfoChange(final DownBean info) {
        data.setState(info.state);

        int progress = (int) (info.cur / (float) info.max * 100);
        progressPar.setProgress(progress);

        rlProgress.setVisibility(View.VISIBLE);

        switch (info.state) {
            case DownManager.STATE_DOWNLOADED:
                tvType.setText("下载完成");
                btnStart.setText("打开");
                rlProgress.setVisibility(View.GONE);
                btnStart.setVisibility(View.VISIBLE);
                break;
            case DownManager.STATE_UNDOWNLOAD:
                tvSize.setText("未下载");
                btnStart.setText("下载" + "(" + XfileUtils.fromatSize(info.max) + ")");
                rlProgress.setVisibility(View.GONE);
                btnStart.setVisibility(View.VISIBLE);
                break;
            case DownManager.STATE_DOWNLOADING:
                tvSize.setText("下载中" + "…(" + XfileUtils.fromatSize(info.cur) + "/" + XfileUtils.fromatSize(info.max) + ")");
                btnStart.setVisibility(View.GONE);
                rlProgress.setVisibility(View.VISIBLE);
                break;
            case DownManager.STATE_PAUSEDOWNLOAD:
                rlProgress.setVisibility(View.GONE);
                btnStart.setVisibility(View.VISIBLE);
                tvSize.setText("暂停中" + "…(" + XfileUtils.fromatSize(info.cur) + "/" + XfileUtils.fromatSize(info.max) + ")");
                btnStart.setText("继续下载" + "(" + XfileUtils.fromatSize((info.max - info.cur)) + ")");
                break;
            case DownManager.STATE_WAITINGDOWNLOAD:
                break;
            case DownManager.STATE_DOWNLOADFAILED:
                tvType.setText("下载失败");
                rlProgress.setVisibility(View.GONE);
                tvSize.setText("重新下载");
                btnStart.setVisibility(View.VISIBLE);
                break;
        }
    }

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

    }
}
