package com.phlx.wool.ui.search;

import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import com.phlx.wool.R;
import com.phlx.wool.db.DbUtil;
import com.phlx.wool.db.interf.DbQueryCallBack;
import com.phlx.wool.entity.Veterinary;
import com.phlx.wool.entity.VeterinaryDao;
import com.phlx.wool.ui.search.adapter.VeterinaryAdapter;
import com.phlx.wool.ui.search.anim.CircularRevealAnim;
import com.phlx.wool.ui.search.interf.IOnSearchVeterinaryClickListener;
import com.phlx.wool.ui.search.interf.IOnVeterinaryItemClickListener;
import com.phlx.wool.util.KeyBoardUtils;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.ArrayList;
import java.util.List;

import me.goldze.mvvmhabit.utils.ToastUtils;

/**
 * Created by Won on 2017/1/13.
 */

public class SearchVeterinaryFragment extends DialogFragment implements DialogInterface.OnKeyListener,
        ViewTreeObserver.OnPreDrawListener, CircularRevealAnim.AnimListener, IOnVeterinaryItemClickListener
        , View.OnClickListener {

    public static final String TAG = "SearchVeterinaryFragment";
    private EditText etSearchKeyword;
    private ImageView ivSearchSearch;

    private View view;
    //动画
    private CircularRevealAnim mCircularRevealAnim;
    //历史搜索记录
    private ArrayList<Veterinary> queryVeterinaries = new ArrayList<>();
    private ArrayList<Veterinary> Veterinaries = new ArrayList<>();
    //适配器
    private VeterinaryAdapter veterinaryAdapter;

    public static SearchVeterinaryFragment newInstance() {
        return new SearchVeterinaryFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NO_FRAME, R.style.DialogStyle);
    }

    @Override
    public void onStart() {
        super.onStart();
        initDialog();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.dialog_search, container, false);

        init();//实例化

        return view;
    }

    private void init() {
        ImageView ivSearchBack = view.findViewById(R.id.iv_search_back);
        etSearchKeyword = view.findViewById(R.id.et_search_keyword);
        ivSearchSearch = view.findViewById(R.id.iv_search_search);
        RecyclerView rvSearchVeterinary = view.findViewById(R.id.rv_search);

        //实例化动画效果
        mCircularRevealAnim = new CircularRevealAnim();
        //监听动画
        mCircularRevealAnim.setAnimListener(this);

        getDialog().setOnKeyListener(this);//键盘按键监听
        ivSearchSearch.getViewTreeObserver().addOnPreDrawListener(this);//绘制监听


        //初始化recyclerView
        rvSearchVeterinary.setLayoutManager(new LinearLayoutManager(getContext()));//list类型
        veterinaryAdapter = new VeterinaryAdapter(getContext(), Veterinaries);
        rvSearchVeterinary.setAdapter(veterinaryAdapter);

        veterinaryAdapter.setOnItemClickListener(this);
        //监听编辑框文字改变
        etSearchKeyword.addTextChangedListener(new TextWatcherImpl());
        //监听点击
        ivSearchBack.setOnClickListener(this);
        ivSearchSearch.setOnClickListener(this);


    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<Veterinary>() {
            @Override
            public void onSuccess(List<Veterinary> result) {
                queryVeterinaries.clear();
                queryVeterinaries.addAll(result);
                setAllVeterinaries();
            }

            @Override
            public void onFailed() {

            }
        }).queryAsyncAll(Veterinary.class, null);
    }

    /**
     * 显示Fragment，防止多次打开导致崩溃
     */
    public void showFragment(FragmentManager fragmentManager, String tag) {
        if (!this.isAdded()) {
            this.show(fragmentManager, tag);
        }
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.iv_search_back) {
            hideAnim();
        } else if (view.getId() == R.id.iv_search_search) {
            search();
        }
    }

    /**
     * 初始化SearchFragment
     */
    private void initDialog() {
        Window window = getDialog().getWindow();
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        int width = (int) (metrics.widthPixels * 0.98); //DialogSearch的宽
        window.setLayout(width, WindowManager.LayoutParams.MATCH_PARENT);
        window.setGravity(Gravity.TOP);
        window.setWindowAnimations(R.style.DialogEmptyAnimation);//取消过渡动画 , 使DialogSearch的出现更加平滑
    }

    /**
     * 监听键盘按键
     */
    @Override
    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
            hideAnim();
        } else if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
            search();
        }
        return false;
    }

    /**
     * 监听搜索键绘制时
     */
    @Override
    public boolean onPreDraw() {
        ivSearchSearch.getViewTreeObserver().removeOnPreDrawListener(this);
        mCircularRevealAnim.show(ivSearchSearch, view);
        return true;
    }

    /**
     * 搜索框动画隐藏完毕时调用
     */
    @Override
    public void onHideAnimationEnd() {
        etSearchKeyword.setText("");
        dismiss();
    }

    /**
     * 搜索框动画显示完毕时调用
     */
    @Override
    public void onShowAnimationEnd() {
        if (isVisible()) {
            KeyBoardUtils.openKeyboard(getContext(), etSearchKeyword);
        }
    }

    @Override
    public void onItemClick(Veterinary veterinary) {
        onSearchVeterinaryClickListener.OnSelectedClick(veterinary);
        hideAnim();
    }

    /**
     * 监听编辑框文字改变
     */
    private class TextWatcherImpl implements 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) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            String keyword = editable.toString();
            if (TextUtils.isEmpty(keyword.trim())) {
                setAllVeterinaries();
            } else {
                setKeyWordVeterinaries(editable.toString());
            }
        }
    }


    private void hideAnim() {
        KeyBoardUtils.closeKeyboard(getContext(), etSearchKeyword);
        mCircularRevealAnim.hide(ivSearchSearch, view);
    }

    private void search() {
        String searchKey = etSearchKeyword.getText().toString();
        if (TextUtils.isEmpty(searchKey.trim())) {
            Toast.makeText(getContext(), "请输入关键字", Toast.LENGTH_SHORT).show();
        } else {
            QueryBuilder<Veterinary> builder =
                    DbUtil.getInstance().getQueryBuilder(Veterinary.class)
                            .whereOr(VeterinaryDao.Properties.VeterinaryName.eq(searchKey),
                                    VeterinaryDao.Properties.VeterinaryPhone.eq(searchKey));
            List<Veterinary> veterinaries = DbUtil.getInstance().queryAll(Veterinary.class,
                    builder);
            if (veterinaries == null || veterinaries.size() == 0) {
                ToastUtils.showShort("未找到符合 "+searchKey+" 的搜索结果");
            }else {
                onSearchVeterinaryClickListener.OnSelectedClick(veterinaries.get(0));
                hideAnim();
            }
        }
    }


    private void setAllVeterinaries() {
        Veterinaries.clear();
        Veterinaries.addAll(queryVeterinaries);
        veterinaryAdapter.notifyDataSetChanged();
    }

    private void setKeyWordVeterinaries(String keyword) {
        Veterinaries.clear();
        QueryBuilder<Veterinary> builder =
                DbUtil.getInstance().getQueryBuilder(Veterinary.class)
                        .whereOr(VeterinaryDao.Properties.VeterinaryName.like("%" + keyword + "%"),
                                VeterinaryDao.Properties.VeterinaryPhone.like( keyword + "%"));
        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<Veterinary>() {
            @Override
            public void onSuccess(List<Veterinary> result) {
                if (result != null && result.size() > 0) {
                    Veterinaries.addAll(result);
                    veterinaryAdapter.notifyDataSetChanged();
                }else {
                    Veterinaries.clear();
                    veterinaryAdapter.notifyDataSetChanged();
                }
            }
            @Override
            public void onFailed() {

            }
        }).queryAsyncAll(Veterinary.class, builder);
    }

    private IOnSearchVeterinaryClickListener onSearchVeterinaryClickListener;

    public void setIOnSearchVeterinaryClickListener(IOnSearchVeterinaryClickListener onSearchVeterinaryClickListener) {
        this.onSearchVeterinaryClickListener = onSearchVeterinaryClickListener;
    }

}
