package com.phlx.anchorcollect.ui.labelchange;

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.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.interf.DbIDUCallBack;
import com.phlx.anchorcollect.db.interf.DbQueryCallBack;
import com.phlx.anchorcollect.entity.CattleResumeEntity;
import com.phlx.anchorcollect.entity.InspectEntity;
import com.phlx.anchorcollect.ui.base.BackBarVM;
import com.phlx.anchorcollect.util.TextUtil;
import com.uhf.structures.InventoryData;
import com.uhf.structures.OnInventoryListener;

import org.greenrobot.greendao.query.WhereCondition;

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

import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.SPUtils;
import me.goldze.mvvmhabit.utils.StringUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class LabelChangeVM extends BackBarVM<Repository> implements OnInventoryListener {

    public CattleResumeEntity entity = new CattleResumeEntity();

    private List<CattleResumeEntity> uploadData;

    public SingleLiveEvent<Boolean> initRFIDEvent = new SingleLiveEvent<>();


    public SingleLiveEvent<Boolean> uploadDataEvent = new SingleLiveEvent<>();


    private SimpleDateFormat dateFormat;

    public ObservableField<String> epc = new ObservableField<>();
    public ObservableField<String> noticeNo = new ObservableField<>();
    public ObservableField<InspectEntity> inspectEntity = new ObservableField<>();

    private boolean isModify;

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

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

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


    public LabelChangeVM(@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));

        uploadData = new ArrayList<>();
    }

    //初始化ToolBar
    public void initToolbar(String epc, String noticeNo, CattleResumeEntity entity, InspectEntity inspectEntity) {
        setBackTitleText(getApplication().getResources().getString(R.string.label_change));
        setSettingVisibleObservable(View.GONE);
        setBackRightTextVisible(View.VISIBLE);
        setBackRightText(getApplication().getResources().getString(R.string.save));

        if (entity == null) {
            this.epc.set(epc);
            this.noticeNo.set(noticeNo);
            getCattleResume();
        } else {
            this.epc.set(entity.getRegistrationNo());
            this.noticeNo.set(entity.getIndividualNo());
            this.entity.copyEntity(entity);
            this.inspectEntity.set(inspectEntity);
        }


    }

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

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

    private void initData() {

        epc.set(entity.getRegistrationNo());
        noticeNo.set(entity.getIndividualNo());
//        entity.notifyChange();

    }

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

    @Override
    protected void backRightTextOnClick() {
        saveCattleResume();
    }

    private void saveCattleResume() {

        if (StringUtils.isEmpty(epc.get()) && StringUtils.isEmpty(noticeNo.get())) {
            ToastUtils.showShort("请至少填一个耳标号!");
            return;
        }
        if (!StringUtils.isEmpty(epc.get()) && epc.get().length() > 50) {
            ToastUtils.showShort("电子耳标长度非法，请重新扫描!");
            return;
        }
        if (!StringUtils.isEmpty(noticeNo.get()) && noticeNo.get().length() > 25) {
            ToastUtils.showShort("可视耳标超长，请填写在25位内!");
            return;
        }

        int checkResult = checkCattleResume();

        if (checkResult != 0) {
            switch (checkResult) {
                case 1:
                    ToastUtils.showShort("电子耳标已存在，请重新扫描！");
                    return;
                case 3:
                    ToastUtils.showShort("可视耳标已存在，请重新填写！");
                    return;
            }
        }

        if (!StringUtils.isEmpty(epc.get()))
            entity.setRegistrationNo(epc.get());
        if (!StringUtils.isEmpty(noticeNo.get()))
            entity.setIndividualNo(noticeNo.get());
        entity.setUploadStatus("0");

        dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        entity.setUpdateBy(model.getUserName());
        entity.setUpdateTime(dateFormat.format(new Date(System.currentTimeMillis())));
        entity.setDeptId(Long.parseLong(SPUtils.getInstance().getString(Configs.SP_DEPT_ID)));
        uploadData.add(entity);

        DbUtil.getInstance().insertAsyncBatch(CattleResumeEntity.class, uploadData, new DbIDUCallBack() {
            @Override
            public void onNotification(boolean result) {
                if (result) {
                    ToastUtils.showShort("保存" + getApplication().getResources().getString(R.string.label_change) + "成功！");
                    finish();
                } else {
                    ToastUtils.showShort("保存" + getApplication().getResources().getString(R.string.label_change) + "失败！");
                }
            }
        });
    }


    private int checkCattleResume() {
        List<CattleResumeEntity> cattleResumeEntityList = DbUtil.getInstance().queryAll(CattleResumeEntity.class);
        if (cattleResumeEntityList != null && cattleResumeEntityList.size() > 0) {
            for (CattleResumeEntity cattleResumeEntity : cattleResumeEntityList) {
                if (cattleResumeEntity.getUnid().equals(entity.getUnid())) {
                    continue;
                }
                if (!StringUtils.isEmpty(epc.get()) && epc.get().equals(cattleResumeEntity.getRegistrationNo())) {
                    return 1;
                }
                if (!StringUtils.isEmpty(noticeNo.get()) && noticeNo.get().equals(cattleResumeEntity.getIndividualNo())) {
                    return 3;
                }
            }
            return 0;
        } else {
            return 0;
        }
    }


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


    //开始盘点一次
    public void startInventory() {
        if (!isScan) {
            App.getInstance().getLinkage().startInventory(1, 0);
            tag = "";
            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;
        ToastUtils.showShort(epc);
        this.epc.set(epc);
        isScan = false;
    }


    /**
     * 查询基础信息
     **/
    private void getCattleResume() {

        StringBuffer sbf = new StringBuffer();
        if (!StringUtils.isEmpty(epc.get()))
            sbf.append(" REGISTRATION_NO = '" + epc.get() + "'");
        if (!StringUtils.isEmpty(noticeNo.get())) {
            if (sbf.length() > 0)
                sbf.append(" AND ");
            sbf.append(" INDIVIDUAL_NO= '" + noticeNo.get() + "'");
        }

        String sql = sbf.toString();
        WhereCondition.StringCondition stringCondition = new WhereCondition.StringCondition(sql);

        DbUtil.getInstance().queryAsync(CattleResumeEntity.class, stringCondition, new DbQueryCallBack<CattleResumeEntity>() {
            @Override
            public void onSuccess(List<CattleResumeEntity> result) {
                if (result != null && result.size() > 0) {
                    entity.copyEntity(result.get(0));
                    initData();
                } else {
                    ToastUtils.showShort("耳标不存在，请重新扫描！");
                    finish();
                }
            }

            @Override
            public void onFailed() {
                ToastUtils.showShort("查询数据库失败");
                finish();
            }
        });

    }

    @Override
    public void onPause() {
        super.onPause();
        App.getInstance().getLinkage().stopInventory();
        App.getInstance().getLinkage().setOnInventoryListener(null);
    }
}
