package xn.xxp.main.msds;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;

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

import com.blankj.utilcode.util.ClickUtils;
import com.blankj.utilcode.util.LogUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;

import core.ui.activity.BaseCountDownActivity;
import core.util.EscapeUnescape;
import core.util.WebViewHelper;
import http.client.ApiRepository;
import http.vo.response.HazardBook;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import xn.xxp.R;
import xn.xxp.databinding.ActivityInstructionBinding;
import xn.xxp.utils.QrTool;
import xn.xxp.widget.ITitleBar;
import xn.xxp.widget.NavViewCompat;
import xn.xxp.widget.SelectHazardBookDialog;

public class InstructionActivity extends BaseCountDownActivity<ActivityInstructionBinding> {

    private InstructionAdapter mInstructionAdapter;
    private HazardBook mCurrentData;

    @Override
    public ITitleBar getMTitleBar() {
        return binding.titleBar;
    }

    @Override
    public NavViewCompat getMNavView() {
        return binding.navView;
    }

    @Override
    public ActivityInstructionBinding createViewBinding() {
        return ActivityInstructionBinding.inflate(getLayoutInflater());
    }

    @Override
    public void initViews(Bundle savedInstanceState) {
        super.initViews(savedInstanceState);
        WebViewHelper webViewHelper = new WebViewHelper(binding.webView, binding.progressbar);
        webViewHelper.initWebView(null, null);
    }

    @Override
    public void initData() {
        mInstructionAdapter = new InstructionAdapter();

        mInstructionAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                HazardBook item = (HazardBook) adapter.getItem(position);
                mInstructionAdapter.setSelectedItemId(item.id);
                mInstructionAdapter.notifyDataSetChanged();
                showHazardBookDetail(item.id);
            }
        });

        binding.sdms.setLayoutManager(new LinearLayoutManager(this));
        binding.sdms.setAdapter(mInstructionAdapter);

        showLoading("加载中...");
        Disposable disposable = ApiRepository.INSTANCE.hazardBookList()
                .subscribe(data -> {
                    dismissLoading();
                    mInstructionAdapter.setList(data != null ? new ArrayList<>(data) : Collections.emptyList());
                    if (data == null || data.isEmpty()) {
                        mInstructionAdapter.setEmptyView(R.layout.view_list_empty);
                    } else {
                        mInstructionAdapter.setSelectedItemId(data.get(0).id);
                        showHazardBookDetail(data.get(0).id);
                    }
                }, throwable -> {
                    dismissLoading();
                    showNetError(throwable);
                    throwable.printStackTrace();
                    mInstructionAdapter.setEmptyView(R.layout.view_list_empty);
                });
        addDisposable(disposable);
        binding.search.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {
                Editable searchETText = binding.searchET.getText();
                if (TextUtils.isEmpty(searchETText)) {
                    showToast("请输入MSDS!");
                    return;
                }
                showLoading("查询中...");
                addDisposable(ApiRepository.INSTANCE.hazardBookList(searchETText.toString()).subscribe(new Consumer<List<HazardBook>>() {
                    @Override
                    public void accept(List<HazardBook> hazardBooks) throws Throwable {
                        dismissLoading();
                        new SelectHazardBookDialog(InstructionActivity.this, "请选择", hazardBooks, new SelectHazardBookDialog.SelectedListener() {
                            @Override
                            public void selected(HazardBook hazardBook) {
                                mInstructionAdapter.setSelectedItemId(hazardBook.id);
                                mInstructionAdapter.notifyDataSetChanged();
                                showHazardBookDetail(hazardBook.id);
                            }

                        }).show();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Throwable {
                        LogUtils.e(Log.getStackTraceString(throwable));
                        dismissLoading();
                        showNetError(throwable);
                    }
                }));
            }
        });
    }

    private void showHazardBookDetail(String id) {
        if (id == null) return;
        showLoading("查询中...");
        Disposable disposable = ApiRepository.INSTANCE.hazardBookDetail(id)
                .subscribe(data -> {
                    dismissLoading();
                    refreshDetailUI(data);
                }, throwable -> {
                    dismissLoading();
                    showNetError(throwable);
                    throwable.printStackTrace();
                });
        addDisposable(disposable);
    }

    private void refreshDetailUI(HazardBook data) {
        mCurrentData = data;
        if (data != null) {
            // 文件内容
            if (data.content != null && !data.content.isEmpty()) {
                StringBuilder html = new StringBuilder();
                html.append("<HTML><HEAD></HEAD><body>");
                html.append(EscapeUnescape.unescape(data.content));
                html.append("</body></HTML>");

                binding.webView.loadDataWithBaseURL(
                        "file:///android_asset/",
                        html.toString(),
                        "text/html",
                        "utf-8",
                        null
                );
            }

            // 二维码处理
            new Thread(() -> {
                try {
                    final android.graphics.Bitmap bitmap = QrTool.generateQRCode(data.qrCodeUrl, 150);
                    runOnUiThread(() -> {
                        Glide.with(this)
                                .asBitmap()
                                .load(bitmap)
                                .error(R.mipmap.img_error)
                                .into(binding.qrCode);
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }

    @Override
    public void initListener() {
        binding.fullScreen.setOnClickListener(v -> {
            if (mCurrentData != null) {
                Intent intent = new Intent(this, HtmlFullScreenActivity.class);
                intent.putExtra("html_content", mCurrentData.content);
                intent.putExtra("onEboard", onEboard());
                intent.putExtra("name", mCurrentData.name);
                startActivity(intent);
            }
        });
    }

    protected boolean onEboard() {
        return true;
    }

    @Override
    public boolean enabledBackCountDown() {
        return true;
    }
}

class InstructionAdapter extends BaseQuickAdapter<HazardBook, BaseViewHolder> {

    private String selectedItemId;

    public InstructionAdapter() {
        super(R.layout.item_instruction);
    }

    public void setSelectedItemId(String selectedItemId) {
        this.selectedItemId = selectedItemId;
    }

    @Override
    protected void convert(BaseViewHolder holder, HazardBook item) {
        TextView textView = (TextView) holder.itemView;
        textView.setText((item.code != null ? item.code : "") + " " + (item.name != null ? item.name : ""));

        int backgroundRes = (selectedItemId != null && selectedItemId.equals(item.id))
                ? R.drawable.bg_item_checked
                : R.drawable.bg_item_normal;

        textView.setBackgroundResource(backgroundRes);
    }
}

class AutoCompleteAdapter extends BaseAdapter implements Filterable {

    private List<HazardBook> originalData;
    private List<HazardBook> visibilityData;
    private final Object mLock = new Object();
    private Filter mFilter;

    public AutoCompleteAdapter(List<HazardBook> data) {
        originalData = data != null ? new ArrayList<>(data) : new ArrayList<>();
        visibilityData = new ArrayList<>(originalData);
    }

    @Override
    public int getCount() {
        return visibilityData.size();
    }

    @Override
    public HazardBook getItem(int position) {
        return visibilityData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_auto_complete_drop_down, parent, false);
            holder = new ViewHolder(convertView.findViewById(R.id.text1));
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.item.setText(getItem(position).name);
        return convertView;
    }

    @Override
    public Filter getFilter() {
        if (mFilter == null) {
            mFilter = new InstructionFilter();
        }
        return mFilter;
    }

    private static class ViewHolder {
        TextView item;

        ViewHolder(TextView item) {
            this.item = item;
        }
    }

    private class InstructionFilter extends Filter {

        @Override
        protected FilterResults performFiltering(CharSequence prefix) {
            FilterResults results = new FilterResults();

            if (prefix == null || prefix.length() == 0) {
                synchronized (mLock) {
                    results.values = new ArrayList<>(originalData);
                    results.count = originalData.size();
                }
            } else {
                String filterString = prefix.toString().toLowerCase(Locale.getDefault());
                List<HazardBook> filteredList = new ArrayList<>();

                for (HazardBook item : originalData) {
                    String name = item.name != null ? item.name.toLowerCase(Locale.getDefault()) : "";
                    String pinYinChar = item.pinYinChar != null ? item.pinYinChar.toLowerCase(Locale.getDefault()) : "";

                    if (name.contains(filterString) || pinYinChar.contains(filterString)) {
                        filteredList.add(item);
                    }
                }

                results.values = filteredList;
                results.count = filteredList.size();
            }
            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            visibilityData.clear();

            if (results.values != null) {
                visibilityData.addAll((List<HazardBook>) results.values);
            }

            if (results.count > 0) {
                notifyDataSetChanged();
            } else {
                notifyDataSetInvalidated();
            }
        }
    }
}