package com.phlx.anchorcollect.ui.bind;

import android.annotation.SuppressLint;
import android.app.Application;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Handler;
import android.os.Message;
import android.util.SparseIntArray;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableField;

import com.phlx.anchorcollect.App;
import com.phlx.anchorcollect.Configs;
import com.phlx.anchorcollect.R;
import com.phlx.anchorcollect.data.Repository;
import com.phlx.anchorcollect.db.DbUtil;
import com.phlx.anchorcollect.db.gen.CattleResumeEntityDao;
import com.phlx.anchorcollect.db.interf.DbQueryCallBack;
import com.phlx.anchorcollect.entity.CattleResumeEntity;
import com.phlx.anchorcollect.ui.base.BackBarVM;
import com.phlx.anchorcollect.util.TextUtil;
import com.phlx.anchorcollect.widget.ItemData;
import com.uhf.structures.InventoryData;
import com.uhf.structures.OnInventoryListener;

import org.greenrobot.greendao.query.QueryBuilder;

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

import cn.wandersnail.commons.util.ToastUtils;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.binding.command.BindingConsumer;
import me.goldze.mvvmhabit.binding.viewadapter.spinner.IKeyAndValue;
import me.goldze.mvvmhabit.utils.SPUtils;
import me.goldze.mvvmhabit.utils.StringUtils;

public class BindVM extends BackBarVM<Repository> implements OnInventoryListener {

    public ObservableArrayList<IKeyAndValue> tagItemData;

    private List<CattleResumeEntity> cattleResumeEntityList;

    public ObservableField<String> individualNo = new ObservableField<>("");
    public ObservableField<String> registrationNo = new ObservableField<>("");

    private SoundPool soundPool;//盘点到标签时的提示音
    private SparseIntArray musicId;

    private boolean isScan = false;//是否在扫描

    private String tag = "";//扫描到的标记

    private CattleResumeEntity entity;
    private SimpleDateFormat dateFormat;

    public BindVM(@NonNull Application application, Repository model) {
        super(application, model);

        soundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 5);
        musicId = new SparseIntArray();
        musicId.put(1, soundPool.load(getApplication(), R.raw.readcard, 1));
        musicId.put(2, soundPool.load(getApplication(), R.raw.failure, 1));
    }

    @Override
    public void onResume() {
        super.onResume();

        isScan = false;
        tag = "";
        App.getInstance().getLinkage().setOnInventoryListener(this);
    }

    //初始化ToolBar
    public void initToolbar() {
        setBackTitleText("绑定耳标");
        setSettingVisibleObservable(View.GONE);
        setBackRightTextVisible(View.VISIBLE);
        setBackRightText(getApplication().getResources().getString(R.string.save));

        initData();
    }

    private void initData() {

        tagItemData = new ObservableArrayList<>();
        cattleResumeEntityList = new ArrayList<>();
        queryTag();
    }

    private void queryTag() {

        tagItemData.clear();
        cattleResumeEntityList.clear();
        QueryBuilder<CattleResumeEntity> builder0 =
                DbUtil.getInstance().getQueryBuilder(CattleResumeEntity.class)
                        .where(CattleResumeEntityDao.Properties.RegistrationNo.eq(""));
        DbUtil.getInstance().queryAsyncAll(CattleResumeEntity.class, builder0, new DbQueryCallBack<CattleResumeEntity>() {
            @Override
            public void onSuccess(List<CattleResumeEntity> result) {

                if (result != null && result.size() > 0) {
                    cattleResumeEntityList.addAll(result);
                    for (CattleResumeEntity cattleResumeEntity : result) {
                        tagItemData.add(new ItemData(cattleResumeEntity.getIndividualNo(), cattleResumeEntity.getIndividualNo()));
                    }
                }
            }

            @Override
            public void onFailed() {
                ToastUtils.showShort("查询基础数据数量失败！");
                dismissDialog();
            }
        });


    }

    public BindingCommand<IKeyAndValue> onTagSelectorCommand = new BindingCommand<>(new BindingConsumer<IKeyAndValue>() {
        @Override
        public void call(IKeyAndValue iKeyAndValue) {
            individualNo.set(iKeyAndValue.getValue());
        }
    });


    public BindingCommand onRegistrationNoClick = new BindingCommand(() -> startInventory());

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

        if (StringUtils.isEmpty(individualNo.get())) {
            ToastUtils.showShort("请选择可视耳标");
            return;
        }
        if (StringUtils.isEmpty(registrationNo.get())) {
            ToastUtils.showShort("请扫描标签");
            return;
        }

        //判断是否已经绑定过电子耳标
        QueryBuilder<CattleResumeEntity> builder0 =
                DbUtil.getInstance().getQueryBuilder(CattleResumeEntity.class)
                        .where(CattleResumeEntityDao.Properties.RegistrationNo.eq(registrationNo.get()));
        DbUtil.getInstance().queryAsyncAll(CattleResumeEntity.class, builder0, new DbQueryCallBack<CattleResumeEntity>() {
            @Override
            public void onSuccess(List<CattleResumeEntity> result) {

                if (result != null && result.size() > 0) {
                    ToastUtils.showShort("该耳标已被绑定，请重新扫描！");
                    return;
                } else {
                    bindRfid();
                }
            }

            @Override
            public void onFailed() {
                ToastUtils.showShort("查询基础数据数量失败！");
                dismissDialog();
            }
        });
    }

    private void bindRfid() {

        for (CattleResumeEntity cattleResumeEntity : cattleResumeEntityList) {
            if (cattleResumeEntity.getIndividualNo().equals(individualNo.get())) {
                entity = cattleResumeEntity;
                entity.setRegistrationNo(registrationNo.get());
                entity.setUploadStatus("0");
                cattleResumeEntity.setUpdateBy(SPUtils.getInstance().getString(Configs.SP_LOGIN_NAME));
                dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                cattleResumeEntity.setUpdateTime(dateFormat.format(new Date()));
                break;
            }
        }
        if (entity != null) {
            long saveStatus = DbUtil.getInstance().insertOrReplace(entity);
            if (saveStatus != -1) {
                ToastUtils.showShort("耳标绑定成功！");
                entity = null;
                individualNo.set("");
                registrationNo.set("");
                queryTag();
            } else {
                ToastUtils.showShort("耳标绑定失败！");
            }
        }
    }

    //开始盘点一次
    public void startInventory() {
        if (!isScan) {
            App.getInstance().getLinkage().startInventory(1, 0);
            tag = "";
            registrationNo.set("");
            isScan = true;
        } else {
            App.getInstance().getLinkage().stopInventory();
            isScan = false;
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0x333) {
                InventoryData inventoryData = (InventoryData) msg.obj;
                if (inventoryData.getDataLength() > 0 && inventoryData.getEpcLength() > 0) {
                    String epc = TextUtil.byteToHexString(inventoryData.getEPC_Data(), inventoryData.getEpcLength()).substring(1);
                    String tid = TextUtil.byteToHexString(inventoryData.getData(), inventoryData.getDataLength());
                    soundPool.play(musicId.get(1), 1, 1, 0, 0, 1);
                    App.getInstance().getLinkage().stopInventory();

                    if ("".equals(tag))
                        checkEpc(epc, tid);
                }
            }
        }
    };

    private void checkEpc(String epc, String tid) {
        tag = epc + tid;
        registrationNo.set(epc);
        isScan = false;
    }

    @Override
    public void getInventoryData(InventoryData inventoryData) {
        if (inventoryData != null) {
            Message messenger = handler.obtainMessage();
            messenger.what = 0x333;
            messenger.obj = inventoryData;
            handler.sendMessage(messenger);
        }
    }
}
