package hf.lskj.com.carstockcount.activity;

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.AppCompatSpinner;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

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

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import hf.lskj.com.carstockcount.ExportBean;
import hf.lskj.com.carstockcount.MyApplication;
import hf.lskj.com.carstockcount.R;
import hf.lskj.com.carstockcount.adapter.CountRecordAdapter;
import hf.lskj.com.carstockcount.db.MyDao;
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.db.RecordDao;
import hf.lskj.com.carstockcount.event.ChooseRecordEvent;
import hf.lskj.com.carstockcount.utils.DateUtils;
import hf.lskj.com.carstockcount.utils.FileUtils;
import hf.lskj.com.carstockcount.utils.ToastUtils;

public class RecordListActivity extends BaseActivity {

    @Bind(R.id.tv_date)
    TextView tvDate;
    @Bind(R.id.lv_records)
    ListView lvRecords;
    @Bind(R.id.spi_status)
    AppCompatSpinner spiStatus;
    @Bind(R.id.view_root)
    View rootView;
    private Calendar calendar;
    private List<Record> records = new ArrayList<>();
    private CountRecordAdapter adapter;
    private String[] statuses = new String[]{"全部", Record.TYPE_PANDIAN, Record.TYPE_BANGDING, Record.TYPE_JIEBANG};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_count_list);
        ButterKnife.bind(this);
        setTitle("操作记录");
        calendar = Calendar.getInstance();
        tvDate.setText(DateUtils.formatDate(calendar.getTime()));
        setListener();
        adapter = new CountRecordAdapter(this, records);
        lvRecords.setAdapter(adapter);
        getRecords();
    }

    private void setListener() {
        tvDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DatePickerDialog dialog = new DatePickerDialog(RecordListActivity.this,
                        new DatePickerDialog.OnDateSetListener() {
                            @Override
                            public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
                                tvDate.setText(i + "-" + (i1 + 1) + "-" + i2);
                                calendar.set(i, i1, i2);
                                getRecords();

                            }
                        }, calendar.get(Calendar.YEAR),
                        calendar.get(Calendar.MONTH),
                        calendar.get(Calendar.DAY_OF_MONTH));
                dialog.show();
            }
        });
        lvRecords.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ChooseRecordEvent event = new ChooseRecordEvent();
                event.record = adapter.getItem(i);
                EventBus.getDefault().post(event);
                finish();
            }
        });
        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) {
                getRecords();
                rootView.requestFocus();
            }

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

            }
        });
    }

    private void getRecords() {
        String status = spiStatus.getSelectedItemPosition() == 0 ? "" : statuses[spiStatus.getSelectedItemPosition()];
        Calendar temp = (Calendar) calendar.clone();
        temp.set(Calendar.HOUR_OF_DAY, 0);
        temp.set(Calendar.MINUTE, 0);
        String startTime = temp.getTimeInMillis() + "";
        temp.add(Calendar.DAY_OF_MONTH, 1);
        String endTime = temp.getTimeInMillis() + "";
        RecordDao recordDao = MyApplication.getInstances().getDaoSession().getRecordDao();
        QueryBuilder<Record> queryBuilder = recordDao.queryBuilder();
        if (!TextUtils.isEmpty(status)) {
            queryBuilder = queryBuilder.where(RecordDao.Properties.Type.eq(status));
        }
        List<Record> list = queryBuilder
                .where(RecordDao.Properties.CreateTime.between(startTime, endTime))
                .orderDesc(RecordDao.Properties.CreateTime)
                .list();
        records.clear();
        records.addAll(list);
        adapter.notifyDataSetChanged();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add("导出").setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getTitle() != null && item.getTitle().equals("导出")) {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                showPd("正在导出...");
                String fileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + FileUtils.FILE_RECORD;
                try (FileWriter fileWriter = new FileWriter(fileName, false)) {
                    CarInfoDao carInfoDao = MyApplication.getInstances().getDaoSession().getCarInfoDao();
                    List<CarInfo> cars = carInfoDao.loadAll();
                    List<Record> tmpRecords=new ArrayList<>(records);
                    boolean b = MyDao.saveToDb(cars, tmpRecords);
                    if (b) {
                        ExportBean exportBean = new ExportBean(tmpRecords, cars);
                        String data = new Gson().toJson(exportBean);
                        fileWriter.write(data);
                        records.clear();
                        records.addAll(tmpRecords);
                        adapter.notifyDataSetChanged();
                        FileUtils.fileScan(fileName);
                        cancelPd();
                        Toast.makeText(RecordListActivity.this, "导出成功", Toast.LENGTH_SHORT).show();
                    }else{
                        ToastUtils.showShort("导出失败，本地数据保存失败");
                    }
                } catch (IOException e) {
                    cancelPd();
                    e.printStackTrace();
                    Toast.makeText(RecordListActivity.this, "导出失败!", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(RecordListActivity.this, "导出失败,无法读取SD卡!", Toast.LENGTH_SHORT).show();
            }
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


}
