package com.tofly.ghrq_route.common.ui.activity;

import android.content.DialogInterface;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.lcp.arecyclerview.widget.ARecycleView;
import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.base.ui.BaseUi;
import com.tofly.ghrq_route.common.ui.dialog.DownloadListDialog;
import com.tofly.ghrq_route.module.download.controller.DownloadController;
import com.tofly.ghrq_route.module.download.domain.DownloadData;
import com.tofly.ghrq_route.module.download.domain.UpDownloadData;
import com.tofly.ghrq_route.module.download.service.DownloadListCallback;
import com.tofly.ghrq_route.module.service.DownloadReceiver;
import com.tofly.ghrq_route.module.sqlite.DBDaoHelper;
import com.tofly.ghrq_route.common.ui.adapter.DownloadListAdapter;

import java.text.MessageFormat;
import java.util.List;

import com.tofly.ghrq_route.R;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class DownloadMapActivity extends BaseUi {
    @BindView(R.id.download_rlv)
    ARecycleView aRecycleView;
    @BindView(R.id.download_ll)
    ConstraintLayout linearLayout;
    @BindView(R.id.main_toolbar)
    View toolbar;
    private String token;
    private DownloadController downloadController;
    private DownloadListAdapter downloadListAdapter;
    private DownloadListDialog downloadListDialog;
    private Resources resources;
    private boolean isDownloading = false;
    private DBDaoHelper dbDaoHelper;
    private DownloadReceiver downloadReceiver;
    private Unbinder unbinder;
    private String which;

    private ProgressBar mProgressBar;//进度条
    private TextView textTitle;
    private TextView textFileName;
    private TextView textState;
    private TextView textProgress;
    private AlertDialog mDownloadDialog;//对话框

    private boolean mIsCancel = false;//是否取消下载标示符

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(downloadReceiver);
        unbinder.unbind();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initview();
        initData();
        initListener();
        downloadReceiver = new DownloadReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(DownloadReceiver.DownloadReceiverProgress);
        intentFilter.addAction(DownloadReceiver.DownloadReceiverFinished);
        registerReceiver(downloadReceiver, intentFilter);
    }

    /**
     *
     */
    public void refreshDownloadState(String fileName, String dataId, int position, int result) {
        dbDaoHelper = DBDaoHelper.getInstance();
        List<DownloadData> downloadList = dbDaoHelper.getDownloadList();
        initialRecylerView(downloadList);
        updateDownloadFinish(fileName, dataId, position, result);
    }

    private void initListener() {
        aRecycleView.setOnRefreshListener(() -> getDownloadList());
        downloadListAdapter.setOnDownloadClickListener((canDownload, view, position, downloadData, downloadResultCallback) -> {

            if (!canDownload) {
                return;
            }
            if (downloadListDialog == null) {
                downloadListDialog = new DownloadListDialog(DownloadMapActivity.this, linearLayout, R.layout.layout_download_map);
//                downloadListDialog.setCanceledOnTouchOutside(false);
//                downloadListDialog.setCancelable(false);
            }
            downloadListDialog.show();
            Window window = downloadListDialog.getWindow();
            if (resources == null) {
                resources = DownloadMapActivity.this.getResources();
                DisplayMetrics displayMetrics = resources.getDisplayMetrics();
                WindowManager.LayoutParams attributes = window.getAttributes();
                attributes.width = displayMetrics.widthPixels;
                window.setAttributes(attributes);
            }
            downloadListDialog.setTitle(downloadData.getName());
            if (!TextUtils.isEmpty(downloadData.getDatasize())) {
                downloadListDialog.setSize(downloadData.getDatasize());
            }
            downloadListDialog.setStartDownloadServiceCallback(downloadResultCallback);

        });

    }

    private void initData() {
        dbDaoHelper = DBDaoHelper.getInstance();
//        UserBean userBean = BaseApp.getInstance().getLoginUser();
//        List<DownloadData> downloadList = dbDaoHelper.getDownloadList(userBean.getUserid());
        List<DownloadData> downloadList = dbDaoHelper.getDownloadList();
        initialRecylerView(downloadList);
        if (downloadList.size() == 0) {
            initLoadList();
        } else {
            getDownloadList();
        }
    }

    private void initialRecylerView(List<DownloadData> list) {
        if (downloadListAdapter == null) {
            aRecycleView.setItemAnimator(new DefaultItemAnimator());
            aRecycleView.setLayoutManager(new LinearLayoutManager(DownloadMapActivity
                    .this));
            downloadListAdapter = new DownloadListAdapter(DownloadMapActivity.this, list);
            aRecycleView.setAdapter(downloadListAdapter);
        } else {
            downloadListAdapter.setData(list);
        }
    }

    private void initview() {
        setContentView(R.layout.activity_download_map);
        unbinder = ButterKnife.bind(this);
    }

    //    private void getDownloadList(){
//        final UserBean userBean = BaseApp.getInstance().getLoginUser();
//        if (TextUtils.isEmpty(token)) {
//            token = userBean.getToken();
//        }
//        if (downloadController == null) {
//            downloadController = new DownloadController(DownloadMapActivity.this);
//        }
//        aRecycleView.setRefreshing(true);
//        downloadController.getDownloadList(token, new DownloadListCallback() {
//            @Override
//            public void getList(boolean isSuccess, int errorCode, String errMsg, List<DownloadData> list) {
//                aRecycleView.setRefreshing(false);
//                if (isSuccess) {
//                    if (list == null) {
//                        toast(errMsg);
//                    } else {
//                        dbDaoHelper.asyDownloadList(list, userBean.getUserid());
//
//                        UserBean userBean = BaseApp.getInstance().getLoginUser();
//                        List<DownloadData> downloadList = dbDaoHelper.getDownloadList(userBean.getUserid());
//                        if (downloadList != null)
//                            initialRecylerView(downloadList);
//                    }
//                } else {
//                    errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
//                    toast(errMsg);
//                }
//            }
//        });
//    }
    private void initLoadList() {
        if (downloadController == null) {
            downloadController = new DownloadController(DownloadMapActivity.this);
        }
        aRecycleView.setRefreshing(true);
        downloadController.getDownloadList(new DownloadListCallback() {
            @Override
            public void getList(boolean suc, int what, String msg, List<DownloadData> list) {
                aRecycleView.setRefreshing(false);
                if (suc) {
                    if (list == null) {
                        toast(msg);
                    } else {
                        dbDaoHelper.asyDownloadList1(list);
                       getDownloadList();
                    }
                } else {
                    msg = BaseApp.formatErrorMessage(what, msg);
                    toast(msg);
                }
            }

            @Override
            public void getList1(boolean suc, int what, String msg, List<UpDownloadData> list) {
            }
        });
    }

    //更新数据列表
    private void getDownloadList() {
        if (downloadController == null) {
            downloadController = new DownloadController(DownloadMapActivity.this);
        }
        aRecycleView.setRefreshing(true);
        downloadController.getDownloadList1(new DownloadListCallback() {

            @Override
            public void getList(boolean suc, int what, String msg, List<DownloadData> list) {

            }

            @Override
            public void getList1(boolean suc, int what, String msg, List<UpDownloadData> list) {
                aRecycleView.setRefreshing(false);
                if (suc) {
                    if (list == null) {
                        toast(msg);
                    } else {
                        dbDaoHelper.asyDownloadList(list);
                        List<DownloadData> downloadList = dbDaoHelper.getDownloadList();
                        if (downloadList != null)
                            initialRecylerView(downloadList);
                    }
                } else {
                    msg = BaseApp.formatErrorMessage(what, msg);
                    toast(msg);
                }
            }
        });
    }

    /*
     * 显示正在下载对话框
     */
    public void showDownloadDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_progress, null);
        textTitle = (TextView) view.findViewById(R.id.tv_dialog_title);
        textTitle.setText(getResources().getString(R.string.downloading));

        textFileName = (TextView) view.findViewById(R.id.text_file_name);
        mProgressBar = (ProgressBar) view.findViewById(R.id.myprogress);
        textProgress = (TextView) view.findViewById(R.id.progressbar_tv1);
        textState = (TextView) view.findViewById(R.id.progressbar_tv2);
        builder.setView(view);

        // 设置按钮(左)
       /* builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 隐藏当前对话框
                dialog.dismiss();
                // 设置下载状态为取消
                mIsCancel = true;
            }
        });*/
        // 设置按钮(右)
        builder.setNegativeButton("隐藏", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        mDownloadDialog = builder.create();
        mDownloadDialog.setCancelable(false);
        mDownloadDialog.setCanceledOnTouchOutside(false);
        mDownloadDialog.show();
    }

    public void updateDownloadProgress(int downloaded, int total, int progress, String fileName, String dataId, int position) {
        if (mDownloadDialog != null && mDownloadDialog.isShowing()) {
            if (total >= 0 && downloaded >= 0) {
                mProgressBar.setIndeterminate(false);
                mProgressBar.setProgress(progress);
                textProgress.setText(MessageFormat.format("{0}%", progress));

                long length = downloaded;
                double len = (double) length / 1024.00;
                double totalLen = (double) total / 1024.00;
                textState.setText(String.format("%.2fM / %.2fM", len, totalLen));
            } else {
                mProgressBar.setIndeterminate(true);
            }
            textTitle.setText(getResources().getString(R.string.downloading));
            textFileName.setText(fileName);
        }
    }

    private void updateDownloadFinish(String fileName, String dataId, int position, int result) {
        if (mDownloadDialog != null && mDownloadDialog.isShowing()) {
            textFileName.setText(fileName);
            if (result == 1) {
                textTitle.setText(getResources().getString(R.string.downloaded));
            } else {
                textTitle.setText(getResources().getString(R.string.download_failed));
            }
            mDownloadDialog.getButton(DialogInterface.BUTTON_NEGATIVE)
                    .setText(getResources().getString(R.string.close));
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        BaseApp.cancelRequest(getClass().getName());

    }

}
