package com.stm.asset.page;

import android.os.Bundle;

import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.room.Room;

import com.seuic.uhf.EPC;
import com.seuic.uhf.UHFService;
import com.stm.asset.R;
import com.stm.asset.adapter.InventoryAdapter;
import com.stm.asset.base.BaseActivity;
import com.stm.asset.base.StmApplication;
import com.stm.asset.dao.InventoryInfoDao;
import com.stm.asset.database.InventoryInfoDatabase;
import com.stm.asset.model.InventoryInfo;

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

/**
 * 类名称：InventoryActivity
 * 类描述：盘询页面
 * 创建人：story
 * 创建时间：2021-12-09 10:33
 */
public class InventoryActivity extends BaseActivity implements View.OnClickListener {

    private Button beginBtn;
    private TextView txtCountTxt;

    private UHFService uhfService;
    private boolean isInventory;
    private Thread inventoryThread;
    private InventoryRunnable inventoryRunnable;

    private long mRefreshTime;
    private InventoryAdapter inventoryAdapter;
    private InventoryInfoDao inventoryInfoDao;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.actitity_inventory);
        initView();
        inventoryRunnable = new InventoryRunnable();
        try {
            InventoryInfoDatabase database = Room.databaseBuilder(this, InventoryInfoDatabase.class, "inventoryInfoDemo").build();
            inventoryInfoDao = database.inventoryInfoDao();
            uhfService = UHFService.getInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        uhfService.open();
    }

    @Override
    protected void onPause() {
        super.onPause();
        uhfService.close();
    }

    private void initView() {
        initTitle();
        titleTxt.setText("资产盘询");
        findViewById(R.id.common_title_back_layout).setOnClickListener(this);
        beginBtn = findViewById(R.id.inventory_begin_btn);
        beginBtn.setOnClickListener(this);
        beginBtn.setClickable(true);
        txtCountTxt = findViewById(R.id.inventory_txt_count_txt);
        ListView listView = findViewById(R.id.inventory_data_list);
        inventoryAdapter = new InventoryAdapter(this);
        listView.setAdapter(inventoryAdapter);
        findViewById(R.id.inventory_finish_btn).setOnClickListener(this);
        findViewById(R.id.inventory_save_btn).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back_layout:
                finish();
                break;
            case R.id.inventory_begin_btn:
                if (uhfService.inventoryStart()) {
                    beginBtn.setClickable(false);
                    beginBtn.setText(R.string.inventory_btn_doing);
                    isInventory = true;
                    mRefreshTime = new Date().getTime();
                    inventoryThread = new Thread(inventoryRunnable);
                    inventoryThread.start();
                } else {
                    StmApplication.getInstance().showToastShort("开启盘询失败，请稍后操作");
                }
                break;
            case R.id.inventory_finish_btn:
                if (uhfService.inventoryStop()) {
                    isInventory = false;
                    if (inventoryThread != null) {
                        inventoryThread.interrupt();
                        inventoryThread = null;
                    }
                    beginBtn.setClickable(true);
                    beginBtn.setText(R.string.inventory_btn_begin);
                } else {
                    StmApplication.getInstance().showToastShort("关闭盘询失败，请稍后操作");
                }
                break;
            case R.id.inventory_save_btn:
                if (isInventory) {
                    StmApplication.getInstance().showToastShort("正在盘询，请稍后操作");
                } else {
                    List<EPC> dataList = inventoryAdapter.queryData();
                    if (dataList != null && dataList.size() > 0) {
                        List<InventoryInfo> insertList = new ArrayList<>();
                        for (EPC map : dataList) {
                            try {
                                InventoryInfo inventoryInfo = new InventoryInfo();
                                inventoryInfo.setNumber(map.getId().replaceAll(" ", ""));
                                inventoryInfo.setStatus("0");
                                inventoryInfo.setItem01("0"); // 未盘点
                                insertList.add(inventoryInfo);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        StmApplication.getInstance().getAppExecutors().diskIO().execute(new Runnable() {
                            @Override
                            public void run() {
                                inventoryInfoDao.insertInventoryList(insertList);
                                StmApplication.getInstance().getAppExecutors().mainThread().execute(new Runnable() {
                                    @Override
                                    public void run() {
                                        StmApplication.getInstance().showToastShort("保存成功");
                                        inventoryAdapter.setData(null, true);
                                    }
                                });
                            }
                        });
                    }
                }
                break;
        }
    }

    private void refreshText() {
        String countTxtFormat = InventoryActivity.this.getString(R.string.inventory_count_text);
        String text = String.format(countTxtFormat, inventoryAdapter.getCount());
        txtCountTxt.setText(text);
    }

    private class InventoryRunnable implements Runnable {
        @Override
        public void run() {
            while (isInventory) {
                StmApplication.getInstance().getAppExecutors().mainThread().execute(new Runnable() {
                    @Override
                    public void run() {
                        List<EPC> epcList = uhfService.getTagIDs();
                        if (epcList != null && epcList.size() > 0) {
                            inventoryAdapter.setData(epcList, false);
                            refreshText();
                        }
                    }
                });
                try {
                    Thread.sleep(500);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
