package com.zztrapp.zztrapp.ui.currency.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnExternalPreviewEventListener;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.zztrapp.zztrapp.R;
import com.zztrapp.zztrapp.base.BaseActivity;
import com.zztrapp.zztrapp.bean.HttpResult;
import com.zztrapp.zztrapp.bean.WdPageListBean;
import com.zztrapp.zztrapp.constant.Constant;
import com.zztrapp.zztrapp.databinding.ActivityFaLvFaGuiFileBinding;
import com.zztrapp.zztrapp.download.TCallBackUtil;
import com.zztrapp.zztrapp.download.TOkhttpUtil;
import com.zztrapp.zztrapp.http.HttpApi;
import com.zztrapp.zztrapp.http.HttpMethods;
import com.zztrapp.zztrapp.http.ISubscriberOnNextListener;
import com.zztrapp.zztrapp.http.ProgressSubscriber;
import com.zztrapp.zztrapp.http.RxApiManager;
import com.zztrapp.zztrapp.ui.currency.adapter.FaLvFaGuiFileAdapter;
import com.zztrapp.zztrapp.utilcode.klogs.KLog;
import com.zztrapp.zztrapp.utilcode.mUtil.MyGlideEngine;
import com.zztrapp.zztrapp.utilcode.util.ToastUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;

/**
 * Describe 法律法规文件列表
 * Created by Bby on 2022/7/2
 * Email bby0856@163.com
 */
public class FaLvFaGuiFileActivity extends BaseActivity {


    private ActivityFaLvFaGuiFileBinding binding;
    private FaLvFaGuiFileAdapter adapter;
    private String searchName = "";//搜索值
    private int pageNo = 1;//页数
    private int total = 0;//总共多少页
    private String id = "";
    private boolean isShowDialog = true;
    private boolean isRefresh = true;//true 刷新 false 加载
    private List<WdPageListBean.RecordsBean> list = new ArrayList<>();
    private Dialog mDialogDownLoad;

    @Override
    public View getLayoutId() {
        return binding.getRoot();
    }

    @Override
    protected void initBinding() {
        binding = ActivityFaLvFaGuiFileBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void init() {
        mDialogDownLoad = initProgressDialogDownLoad(this, "下载中...");
        id = getIntent().getStringExtra("id");
        binding.navView.navTitle.setText(R.string.laws_regulations);
        binding.navView.navBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        binding.refresh.setRefreshHeader(new ClassicsHeader(this));
        binding.refresh.setRefreshFooter(new ClassicsFooter(this));
        binding.refresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isShowDialog = false;
                isRefresh = false;
                pageNo += 1;
                if (pageNo <= total) {
                    loadList();
                }
                refreshLayout.finishLoadMore();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                isShowDialog = false;
                isRefresh = true;
                pageNo = 1;
                loadList();
                refreshLayout.finishRefresh();
            }
        });
        binding.rv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        adapter = new FaLvFaGuiFileAdapter(this);
        binding.rv.setAdapter(adapter);
        binding.searchEd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                searchName = charSequence.toString();
                if (charSequence.length() > 0) {
                    binding.del.setVisibility(View.VISIBLE);
                } else {
                    binding.del.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });
        loadList();
    }

    @Override
    protected void initOnClick() {
        adapter.setOnItemClickListener(new FaLvFaGuiFileAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(String filePath, String fileName, String fileType) {
//                ArrayList<LocalMedia> imgList = new ArrayList<>();
//                LocalMedia localMedia=new LocalMedia();
//                String ss="https://pics0.baidu.com/feed/902397dda144ad34220e011b7d549efe33ad85fe.jpeg?token=83a99dfc463941d56880bcb26f30c2ef";
//                localMedia.setPath(ss);
//                imgList.add(localMedia);
//                PictureSelector.create(FaLvFaGuiFileActivity.this)
//                        .openPreview()
//                        .setImageEngine(GlideEngine.createGlideEngine())
//                        .setExternalPreviewEventListener(new OnExternalPreviewEventListener() {
//                            @Override
//                            public void onPreviewDelete(int position) {
//
//                            }
//
//                            @Override
//                            public boolean onLongPressDownload(LocalMedia media) {
//                                return false;
//                            }
//                        }).startActivityPreview(0, false, imgList);
                if (!mDialogDownLoad.isShowing()) {
                    mDialogDownLoad.show();
                }
                if (fileType.equals("zip")) {
                    if (mDialogDownLoad != null && mDialogDownLoad.isShowing()) {
                        mDialogDownLoad.dismiss();
                    }
                    ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show("该文件不支持预览，请到PC端查看");
                } else if (fileType.equals("jpg") || fileType.equals("jpeg") || fileType.equals("png") || fileType.equals("gif")) {
//                    upLoadFile(filePath, fileName);

                    if (mDialogDownLoad != null && mDialogDownLoad.isShowing()) {
                        mDialogDownLoad.dismiss();
                    }
                    ArrayList<LocalMedia> imgList = new ArrayList<>();
                    LocalMedia localMedia=new LocalMedia();
                    localMedia.setPath(filePath);
                    imgList.add(localMedia);
                    PictureSelector.create(FaLvFaGuiFileActivity.this)
                            .openPreview()
                            .setImageEngine(MyGlideEngine.createGlideEngine())
                            .setExternalPreviewEventListener(new OnExternalPreviewEventListener() {
                                @Override
                                public void onPreviewDelete(int position) {

                                }

                                @Override
                                public boolean onLongPressDownload(LocalMedia media) {
                                    return false;
                                }
                            }).startActivityPreview(0, false, imgList);
                } else {
                    upLoadFile(filePath, fileName);
                }
            }
        });
        binding.search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isShowDialog = true;
                isRefresh = true;
                pageNo = 1;
                loadList();
            }
        });
        binding.del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                searchName = "";
                binding.searchEd.setText(searchName);
                binding.del.setVisibility(View.GONE);
            }
        });
        binding.searchEd.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
                if (arg1 == EditorInfo.IME_ACTION_SEARCH) {
                    searchName = arg0.getText().toString().trim();
                    isShowDialog = true;
                    isRefresh = true;
                    pageNo = 1;
                    loadList();
                }
                return false;
            }
        });
    }

    //列表数据
    private void loadList() {
        ISubscriberOnNextListener<HttpResult<WdPageListBean>> iSubscriberOnNextListener = new ISubscriberOnNextListener<HttpResult<WdPageListBean>>() {
            @Override
            public void onNext(HttpResult<WdPageListBean> httpResult) {
                if (httpResult.getCode() == 200) {
                    total = httpResult.getResult().getPages();
                    if (isRefresh) {
                        list.clear();
                    }
                    list.addAll(httpResult.getResult().getRecords());
                    adapter.setData(list);
                } else {
                    ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show(httpResult.getMessage());
                }
            }

            @Override
            public void onError(int code, String message) {
                ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show(message);
            }
        };
        ProgressSubscriber<HttpResult<WdPageListBean>> httpResultProgressSubscriber = new ProgressSubscriber<>(iSubscriberOnNextListener, this, isShowDialog);
        RxApiManager.get().add("wdPageList", httpResultProgressSubscriber);
        HttpMethods.getInstance(this).wdPageList(httpResultProgressSubscriber, pageNo, Constant.PAGE_SIZE, id, searchName);
    }

    public Dialog initProgressDialogDownLoad(Context context, String title) {
        if (mDialogDownLoad == null) {
            mDialogDownLoad = new Dialog(context, R.style.LoadingDialogStyle);
            mDialogDownLoad.setContentView(R.layout.layout_dialog);
            mDialogDownLoad.setCancelable(true);
            mDialogDownLoad.setCanceledOnTouchOutside(false);
            mDialogDownLoad.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
            TextView msg = mDialogDownLoad.findViewById(R.id.id_tv_loadingmsg);
            msg.setText(title);
            msg.setVisibility(View.GONE);
            mDialogDownLoad.setCancelable(false);
        }
        return mDialogDownLoad;
    }

    //下载
    private void upLoadFile(String filePath, String fileName) {
        HashMap<String, String> map = new HashMap<>();
//        String appPath = Environment.getExternalStorageDirectory().getAbsolutePath();//手机内存的根目录
        String appPath = getApplicationContext().getFilesDir().getAbsolutePath();//此APP的files路径

        String p = "?filePath=";
        TOkhttpUtil.okHttpDownloadFile( HttpApi.BASE_URL + HttpApi.DOWNLOAD_FTP + p + filePath, map, new TCallBackUtil.TCallBackFile(appPath, fileName) {
//        TOkhttpUtil.okHttpDownloadFile(HttpApi.BASE_URL + filePath, map, new TCallBackUtil.TCallBackFile(appPath, fileName) {
            @Override
            public void onFailure(Call call, Exception e) {
                if (mDialogDownLoad != null && mDialogDownLoad.isShowing()) {
                    mDialogDownLoad.dismiss();
                }
                ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show("打开失败,请稍后重试");
            }

            @Override
            public void onResponse(File response) {
                if (mDialogDownLoad != null && mDialogDownLoad.isShowing()) {
                    mDialogDownLoad.dismiss();
                }
                Intent intent = new Intent(FaLvFaGuiFileActivity.this, TBSWebViewActivity.class);
                intent.putExtra("filePath", appPath + "/" + fileName);
//                intent.putExtra("filePath", appPath +"/"+ "abc.docx");
                intent.putExtra("fileName", fileName);
                KLog.e("filePath" + appPath + "/" + fileName);
                startActivity(intent);

//                ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show("下载成功，已保存到手机");
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding = null;
        RxApiManager.get().cancel("wdPageList");
    }
}