package cn.muchinfo.rma.view.base.future;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.blankj.utilcode.util.ToastUtils;
import com.jakewharton.rxbinding2.widget.RxTextView;

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

import cn.muchinfo.rma.R;
import cn.muchinfo.rma.global.data.account.loginQeruy.GoodsInfo;
import cn.muchinfo.rma.global.room.Builder;
import cn.muchinfo.rma.view.autoWidget.utils.WordUtil;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 模糊查询的页面  可以用过代码或者股票数字进行查询
 */
public class SearchActivity extends AppCompatActivity {

    EditText input_editText;
    ImageView back_img;
    ImageView close_icon;
    ListView search_list;

    int type = 0;

    List<GoodsInfo> valueList = new ArrayList<>(); //搜索到的数据
    SearchAdapter searchAdapter;
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        type = getIntent().getIntExtra("type",0);
        initView();
        setListener();
        initData();
    }

    @Override
    protected void onRestart() {
        super.onRestart();

    }

    private void initView(){
        input_editText = findViewById(R.id.input_editText);
        back_img = findViewById(R.id.back_img);
        close_icon = findViewById(R.id.close_icon);
        search_list = findViewById(R.id.search_list);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void setListener(){
        close_icon.setOnClickListener(view -> {
            input_editText.setText("");
            close_icon.setVisibility(View.INVISIBLE);
        });

        input_editText.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) {
                if (charSequence.toString().equals("")) {
                    return;
                }
                findGoodsInfo(charSequence.toString(), goodsInfos -> {
                    searchAdapter.setData(goodsInfos);
                });

                if(searchAdapter != null){
                    searchAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        back_img.setOnClickListener(view -> finish());

        RxTextView.textChanges(input_editText)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<CharSequence>() {

                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(CharSequence charSequence) {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

        search_list.setOnItemClickListener((adapterView, view, i, l) -> {
//            if(type == 1){
//                Intent intent = new Intent(mtp.polymer.com.information_management.hongkongstocks.search.SearchActivity.this, ManagerChartAcitivity.class);
//                GlobalDataCollention.getInstance().getGoodsInfoData().add(((SearchAdapter) (adapterView).getAdapter()).getItem(i));
//                MarketDataTools.initMarketData();
//                Optional.ofNullable(((SearchAdapter) (adapterView).getAdapter()).getItem(i).getGoodsId()).ifPresent(integer -> intent.putExtra("key_goodsId", integer));
//                startActivityForResult(intent, 10001);
//            }else {
                Intent intent = new Intent();
//                GlobalDataCollention.getInstance().getGoodsInfoData().add(((SearchAdapter) (adapterView).getAdapter()).getItem(i));
//                MarketDataTools.initMarketData();
                Optional.ofNullable(((SearchAdapter) (adapterView).getAdapter()).getItem(i).getGoodsid()).ifPresent(integer -> intent.putExtra("goodsId", integer));
                intent.putExtra("outGoodsCode", ((SearchAdapter) (adapterView).getAdapter()).getItem(i).getOutgoodscode());
                setResult(10086, intent);
                finish();
//            }
        });
    }

    /**
     * 模糊查询数据库中的商品
     * @param findStr
     * @return
     */
    @SuppressLint("CheckResult")
    public void findGoodsInfo(String findStr, IGoodsInfoListener i) {
        StringBuilder sb = new StringBuilder();
        if (findStr.length() > 1 && !WordUtil.isInteger(findStr)) {
            sb.append("%");
            for (int j = 0; j < findStr.length(); j++) {
                char c = findStr.charAt(j);
                sb.append(c).append("%");
            }
        } else {
            sb.append("%" + findStr + "%");
        }
        Disposable subscribe = Builder.getDatabase().getGoodsInfoDao().findGoodsInfo(sb.toString()).
                subscribeOn(Schedulers.io()).
                observeOn(AndroidSchedulers.mainThread()).
                subscribe((goodsInfoData) -> {
                    if (i != null) {
                        i.callBack(goodsInfoData);
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(type == 1){
            if (requestCode == 10001 &&
                    resultCode == 40002) {
                if (data != null) {
                    setResult(10002, data);
                }
                finish();
            }
        }
    }

    private void initData(){
        searchAdapter = new SearchAdapter(valueList, this);
        search_list.setAdapter(searchAdapter);
    }

}
