package hf.lskj.com.carstockcount.activity;

import android.content.DialogInterface;
import android.database.sqlite.SQLiteConstraintException;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatSpinner;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.greendao.query.QueryBuilder;

import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import hf.lskj.com.carstockcount.MyApplication;
import hf.lskj.com.carstockcount.R;
import hf.lskj.com.carstockcount.adapter.CarListAdapter;
import hf.lskj.com.carstockcount.db.CarInfo;
import hf.lskj.com.carstockcount.db.CarInfoDao;
import hf.lskj.com.carstockcount.db.Record;
import hf.lskj.com.carstockcount.event.ChooseCarEvent;
import hf.lskj.com.carstockcount.utils.FileUtils;
import hf.lskj.com.carstockcount.utils.PreferencesUtils;

public class CarListActivity extends BaseActivity {

    @Bind(R.id.searchView)
    SearchView searchView;
    @Bind(R.id.spi_status)
    AppCompatSpinner spiStatus;
    @Bind(R.id.lv_cars)
    ListView lvCars;
    @Bind(R.id.view_root)
    View rootView;
    @Bind(R.id.tv_total)
    TextView tvTotal;
    @Bind(R.id.tv_checked)
    TextView tvChecked;
    @Bind(R.id.tv_not_checked)
    TextView tvNotChecked;
    private String[] statuses = new String[]{"全部", CarInfo.STATUS_IN, CarInfo.STATUS_MOVE, CarInfo.STATUS_WEIPANDAO};
    private CarInfoDao carInfoDao;
    CarListAdapter adapter;
    List<CarInfo> cars = new ArrayList<>();
    private static final String FIRST_IMPORT = "first_import";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_car_list);
        ButterKnife.bind(this);
        setTitle("库存列表");
        carInfoDao = MyApplication.getInstances().getDaoSession().getCarInfoDao();
        searchView.setSubmitButtonEnabled(true);//显示搜索按钮
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                if (TextUtils.isEmpty(newText)) {
                    lvCars.clearTextFilter();
                } else {
                    lvCars.setFilterText(newText);//该方法会通过Adapter得到Filter，然后调用Filter.filter(filterText)
                }
                return false;
            }
        });
        int id = searchView.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
        TextView textView = (TextView) searchView.findViewById(id);
        textView.setTextColor(Color.BLACK);
        textView.setHintTextColor(Color.parseColor("#CCCCCC"));
        spiStatus.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, statuses));
        spiStatus.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                getData(i == 0 ? "" : statuses[i]);
                rootView.requestFocus();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        adapter = new CarListAdapter(this, cars);
        lvCars.setTextFilterEnabled(true);
        lvCars.setAdapter(adapter);
        lvCars.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ChooseCarEvent event = new ChooseCarEvent();
                event.carInfo = adapter.getItem(i);
                EventBus.getDefault().post(event);
                finish();
            }
        });
        getData("");
    }

    private void getData(String status) {

        QueryBuilder<CarInfo> queryBuilder = carInfoDao.queryBuilder();
        if (!TextUtils.isEmpty(status)) {
            queryBuilder = queryBuilder.where(CarInfoDao.Properties.Status.eq(status));
        }
        List<CarInfo> list = queryBuilder.orderAsc(CarInfoDao.Properties.StockCountTime).list();
        cars.clear();
        cars.addAll(list);
        if (TextUtils.isEmpty(status)) {
            int checked = 0;
            for (CarInfo carInfo : list) {
                if (Record.TYPE_PANDIAN.equals(carInfo.getStockCountType())) {
                    checked++;
                }
            }
            tvTotal.setText("库存:" + list.size());
            tvChecked.setText("已盘点:" + checked);
            tvNotChecked.setText("未盘点:" + (list.size() - checked));
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        new MenuInflater(this).inflate(R.menu.car_list, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.input:
                if (PreferencesUtils.getBoolean(CarListActivity.this, FIRST_IMPORT, true)) {
                    //第一次导入时本地没有数据,无需提示
                    importData();
                    rootView.requestFocus();
                } else {
                    new AlertDialog.Builder(this)
                            .setTitle("导入")
                            .setMessage("此操作将覆盖本地数据,是否继续")
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    rootView.requestFocus();
                                }
                            })
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    importData();
                                    rootView.requestFocus();
                                }
                            }).show();
                }
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void importData() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String fileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/"+ FileUtils.FILE_CARS;
            try (FileReader fileReader = new FileReader(fileName)) {
                Gson gson = new Gson();
                List<CarInfo> inputCars = gson.fromJson(fileReader, new TypeToken<List<CarInfo>>() {
                }.getType());
                if (inputCars == null) {
                    Toast.makeText(this, "导入失败!", Toast.LENGTH_SHORT).show();
                    return;
                }
                carInfoDao.deleteAll();
                int count = 0;
                for (CarInfo inputCar : inputCars) {
                    try {
                        if (carInfoDao.insert(inputCar) > 0) {
                            count++;
                        }
                    } catch (SQLiteConstraintException e) {
                        e.printStackTrace();
                    }
                }
                PreferencesUtils.putBoolean(this, FIRST_IMPORT, false);
                Toast.makeText(this, "成功导入" + count + "条数据", Toast.LENGTH_SHORT).show();
                if (spiStatus.getSelectedItemPosition() == 0) {
                    getData("");
                } else {
                    spiStatus.setSelection(0);
                }
                searchView.setQuery("", false);
            } catch (JsonSyntaxException e) {
                e.printStackTrace();
                Toast.makeText(this, "导入失败,数据格式不正确", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(this, "导入失败,请检查是否有初始化文件,以及文件存放路径、文件名是否正确", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "导入失败,无法读取SD卡!", Toast.LENGTH_SHORT).show();
        }
    }
}
