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.Unit;
import com.phlx.wool.entity.UnitDao;
import com.phlx.wool.ui.search.adapter.UnitSearchAdapter;
import com.phlx.wool.ui.search.anim.CircularRevealAnim;
import com.phlx.wool.ui.search.interf.IOnUnitItemClickListener;
import com.phlx.wool.ui.search.interf.IOnUnitSearchClickListener;
import com.phlx.wool.util.KeyBoardUtils;

import org.greenrobot.greendao.query.QueryBuilder;

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

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

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

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

    private View view;
    //动画
    private CircularRevealAnim mCircularRevealAnim;
    //历史搜索记录
    private ArrayList<Unit> queryUnits = new ArrayList<>();
    private ArrayList<Unit> units = new ArrayList<>();
    //适配器
    private UnitSearchAdapter searchUnitAdapter;

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

    @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 rvSearchUnit = view.findViewById(R.id.rv_search);

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

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


        //初始化recyclerView
        rvSearchUnit.setLayoutManager(new LinearLayoutManager(getContext()));//list类型
        searchUnitAdapter = new UnitSearchAdapter(getContext(), units);
        rvSearchUnit.setAdapter(searchUnitAdapter);

        //设置删除单个记录的监听
        searchUnitAdapter.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<Unit>() {
            @Override
            public void onSuccess(List<Unit> result) {
                queryUnits.clear();
                queryUnits.addAll(result);
                setAllUnits();
            }

            @Override
            public void onFailed() {

            }
        }).queryAsyncAll(Unit.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(Unit unit) {
        onUnitSearchClickListener.OnSelectedClick(unit);
        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())) {
                setAllUnits();

            } else {
                setKeyWordUnits(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 {
            onUnitSearchClickListener.OnSearchClick(searchKey);//接口回调
            hideAnim();
        }
    }


    private void setAllUnits() {
        units.clear();
        units.addAll(queryUnits);
        searchUnitAdapter.notifyDataSetChanged();
    }

    private void setKeyWordUnits(String keyword) {
        units.clear();
        QueryBuilder<Unit> builder =
                DbUtil.getInstance().getQueryBuilder(Unit.class)
                        .whereOr(UnitDao.Properties.ManagerName.like("%" + keyword + "%"),
                                UnitDao.Properties.ManagerPhone.like(keyword + "%")
                                , UnitDao.Properties.ManagerCode.like(keyword + "%")
                                , UnitDao.Properties.IdCard.like("%" + keyword));
        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<Unit>() {
            @Override
            public void onSuccess(List<Unit> result) {
                if (result != null && result.size() > 0) {
                    units.addAll(result);
                    searchUnitAdapter.setHighlightStr(keyword);
                    searchUnitAdapter.notifyDataSetChanged();
                } else {
                    units.clear();
                    searchUnitAdapter.setHighlightStr(null);
                    searchUnitAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailed() {

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

    private IOnUnitSearchClickListener onUnitSearchClickListener;

    public void setIOnUnitSearchClickListener(IOnUnitSearchClickListener onUnitSearchClickListener) {
        this.onUnitSearchClickListener = onUnitSearchClickListener;
    }

}
