package com.phlx.anchorcollect_p.ui.fragment.vm;

import android.annotation.SuppressLint;
import android.app.Application;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.SparseIntArray;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableList;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.phlx.anchorcollect_p.App;
import com.phlx.anchorcollect_p.BR;
import com.phlx.anchorcollect_p.Configs;
import com.phlx.anchorcollect_p.R;
import com.phlx.anchorcollect_p.data.Repository;
import com.phlx.anchorcollect_p.db.DbUtil;
import com.phlx.anchorcollect_p.db.gen.CattleResumeEntityDao;
import com.phlx.anchorcollect_p.db.gen.DictEntityDao;
import com.phlx.anchorcollect_p.db.gen.WeightManEntityDao;
import com.phlx.anchorcollect_p.db.interf.DbIDUCallBack;
import com.phlx.anchorcollect_p.db.interf.DbQueryCallBack;
import com.phlx.anchorcollect_p.entity.CattleResumeEntity;
import com.phlx.anchorcollect_p.entity.DictEntity;
import com.phlx.anchorcollect_p.entity.GenTableColumn;
import com.phlx.anchorcollect_p.entity.PerformanceEntity;
import com.phlx.anchorcollect_p.entity.WeightManEntity;
import com.phlx.anchorcollect_p.event.EventMsg;
import com.phlx.anchorcollect_p.event.EventTag;
import com.phlx.anchorcollect_p.ui.fragment.list.CollectGridItem;
import com.phlx.anchorcollect_p.ui.setting.SettingActivity;
import com.phlx.anchorcollect_p.ui.setting.SyncActivity;
import com.phlx.anchorcollect_p.util.BaseImageUtils;
import com.phlx.anchorcollect_p.util.EntityUtils;
import com.phlx.anchorcollect_p.util.TextUtil;
import com.uhf.structures.InventoryData;
import com.uhf.structures.OnInventoryListener;

import org.greenrobot.greendao.query.QueryBuilder;

import java.io.File;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import cn.hutool.core.util.IdUtil;
import io.reactivex.disposables.Disposable;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.bus.RxSubscriptions;
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;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

public class BasicsCollectVM extends BaseViewModel<Repository> implements OnInventoryListener {

    public Drawable drawableImg;
    //照片路径
    public String markeImgUrl;
    private File markFile;

    public GenTableColumn currentParamEntity;
    public GenTableColumn remarkParamEntity = new GenTableColumn();
    public GenTableColumn photoParamEntity = new GenTableColumn();

    //给RecyclerView添加ObservableList
    public ObservableList<CollectGridItem> observableList = new ObservableArrayList<>();
    //给RecyclerView添加ItemBinding
    public ItemBinding<CollectGridItem> itemBinding = ItemBinding.of(BR.viewModel, R.layout.item_collect_grid);

    public SingleLiveEvent<Boolean> onCattleClickEvent = new SingleLiveEvent<>();
    public SingleLiveEvent<Boolean> onCardClickEvent = new SingleLiveEvent<>();
    public SingleLiveEvent<Boolean> onTagClickEvent = new SingleLiveEvent<>();
    public SingleLiveEvent<Boolean> onNotifyAllEvent = new SingleLiveEvent<>();//true是清空页面

    public SingleLiveEvent<String> onShowDialogEvent = new SingleLiveEvent<>();//弹窗提示

    public ObservableField<String> tag = new ObservableField<>("");
    public ObservableField<String> rfid = new ObservableField<>("");
    public ObservableField<String> weight = new ObservableField<>("----");

    public ObservableField<Double> lastGainWeight = new ObservableField<>(0.0);//上次增重
    public ObservableField<Double> adgGainWeight = new ObservableField<>(0.0);//日增重
    public ObservableField<Double> totalGainWeight = new ObservableField<>(0.0);//总增重
    public ObservableField<String> lastGainDate = new ObservableField<>("");//上次增重日期
    public ObservableField<String> adgGainDate = new ObservableField<>("");//日增重日期
    public ObservableField<String> totalGainDate = new ObservableField<>("");//总增重日期


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

    private SimpleDateFormat dateFormat;

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

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

    public boolean isModify = false;
    private long uuid;

    private List<CattleResumeEntity> uploadData;


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

        //ImageView的占位图片，可以解决RecyclerView中图片错误问题
        drawableImg = ContextCompat.getDrawable(getApplication(), R.drawable.no_image);

        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));


    }

    public String getMarkImgUrl() {
        return markeImgUrl;
    }

    public void setMarkImgUrl() {

        File externalFileRootDir = getApplication().getExternalFilesDir("/collect/picture/");
//                                    externalFileRootDir.mkdirs();
        String savePath = externalFileRootDir.getAbsolutePath();//不分开就少个斜杠
        markeImgUrl = savePath + "/anchorCiq" + Configs.tempCattleResume.getUnid() + ".jpg";
        markFile = new File(markeImgUrl);
    }


    public void addInventoryListener() {
        App.getInstance().getLinkage().setOnInventoryListener(this);
    }

    public void removeInventoryListener() {
        App.getInstance().getLinkage().setOnInventoryListener(null);
    }

    public void initGen() {

        for (GenTableColumn gtc : Configs.cattleresume) {
            CollectGridItem cgi = new CollectGridItem(this, gtc, Configs.BASE_ARCHIVES);
            observableList.add(cgi);
        }

        //初始化一下备注
        remarkParamEntity.setColumnName("备注");
        remarkParamEntity.setContent("");
        remarkParamEntity.setShowName("");
        remarkParamEntity.setColumnComment("备注");
        remarkParamEntity.setHtmlType("input");
        remarkParamEntity.setJavaType("String");
        remarkParamEntity.setColumnType("varchar(500)");
        remarkParamEntity.setIsEdit("1");

        //初始化照片
        photoParamEntity.setContent("");
        photoParamEntity.setShowName("");
        photoParamEntity.setHtmlType("photo");
        photoParamEntity.setIsEdit("1");

    }

    public void initDataForTag(String tag) {

        if (isModify)
            clearTempInfo();
        this.tag.set(tag);
        Configs.tempTag = tag;
        if (StringUtils.isEmpty(tag))
            return;

        QueryBuilder<CattleResumeEntity> builder =
                DbUtil.getInstance().getQueryBuilder(CattleResumeEntity.class)
                        .where(CattleResumeEntityDao.Properties.IndividualNo.eq(tag));
        queryCattleResume(builder);
    }

    public void initDataForRfid(String rfid) {

        this.rfid.set(rfid);
        Configs.tempRfid = rfid;
        if (StringUtils.isEmpty(rfid))
            return;

        QueryBuilder<CattleResumeEntity> builder =
                DbUtil.getInstance().getQueryBuilder(CattleResumeEntity.class)
                        .where(CattleResumeEntityDao.Properties.RegistrationNo.eq(rfid));
        queryCattleResume(builder);
    }

    public void initDataForUnid(Long unid) {

        clearTempInfo();
        Configs.tempUnid = unid;
        if (unid == null)
            return;

        QueryBuilder<CattleResumeEntity> builder =
                DbUtil.getInstance().getQueryBuilder(CattleResumeEntity.class)
                        .where(CattleResumeEntityDao.Properties.Unid.eq(unid));
        queryCattleResume(builder);
    }

    //扫描rfid
    private void scanRfid() {

        if (!isScan) {
            rfidTag = "";
            if (isModify)
                clearTempInfo();

            App.getInstance().getLinkage().startInventory(1, 0);
            isScan = true;
            ToastUtils.showShort("开始盘点");

            //几秒后停止盘点
            Message messenger = handler.obtainMessage();
            messenger.what = 0x222;
            handler.sendMessageDelayed(messenger, 5000);
        }
//        else{
//            App.getInstance().getLinkage().stopInventory();
//            isScan = false;
//            ToastUtils.showShort("停止盘点");
//            scanBtnTextContent.set("标签查询");
//        }
    }


    public void onItemClick(GenTableColumn entity) {

        if (Configs.tempUnid!=null &&!"1".equals(entity.getIsEdit())) {
            ToastUtils.showShort("该项无法修改！");
            return;
        }

        if (Configs.tempTag == null) {
            ToastUtils.showShort("请输入耳标信息");
            return;
        }

        currentParamEntity = entity;
        onCardClickEvent.call();
    }

    //输入可视耳标
    public BindingCommand onTagInputClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            onTagClickEvent.call();
        }
    });

    //设置
    public BindingCommand onSettingClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            startActivity(SettingActivity.class);
        }
    });

    //同步数据
    public BindingCommand onSyncClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (!Configs.isOnLine) {
                ToastUtils.showShort("请在联网模式下同步数据！");
                return;
            }
            startActivity(SyncActivity.class);
        }
    });

    public BindingCommand onSaveClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            if (StringUtils.isEmpty(tag.get())) {
                onShowDialogEvent.setValue("请完成可视耳标的录入");
                return;
            }
            //在这判断一下图片
            if (Configs.tempCattleResume == null || StringUtils.isEmpty(Configs.tempCattleResume.getPhotoPath())) {
                ToastUtils.showShort("请上传打标图片");
                return;
            }
            //判断必填
            for (GenTableColumn gtc : Configs.cattleresume) {
                if ("1".equals(gtc.getIsRequired()) && StringUtils.isEmpty(gtc.getContent())) {
                    onShowDialogEvent.setValue("请完成" + gtc.getColumnComment() + "的录入");
                    return;
                }
            }

            saveCattleresume();
        }
    });

    //点击去扫描rfid
    public BindingCommand onWeightChangedClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            scanRfid();
        }
    });

    public void click(int id) {

        if (StringUtils.isEmpty(tag.get())) {
            ToastUtils.showShort("请扫描耳标或者输入耳标信息");
            return;
        }

        //99备注，100照片
        if (id == 99) {
            currentParamEntity = remarkParamEntity;
        } else if (id == 100) {
            if (Configs.tempCattleResume == null) {
                Configs.tempCattleResume = new CattleResumeEntity();
            }
            if (Configs.tempCattleResume.getUnid() == null) {
                Configs.tempCattleResume.setUnid(IdUtil.createSnowflake(3, 1).nextId());
            }
            setMarkImgUrl();

            currentParamEntity = photoParamEntity;
        }

        onCardClickEvent.call();
    }

    private void queryCattleResume(QueryBuilder<CattleResumeEntity> builder) {

        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<CattleResumeEntity>() {
            @Override
            public void onSuccess(List<CattleResumeEntity> result) {

                if (result != null && result.size() > 0) {

                    isModify = true;
                    File externalFileRootDir = getApplication().getExternalFilesDir("/collect/picture/");
//                                    externalFileRootDir.mkdirs();
                    String savePath = externalFileRootDir.getAbsolutePath();
                    markeImgUrl = savePath + "/anchorCiq" + result.get(0).getUnid() + ".jpg";
                    markFile = new File(markeImgUrl);

                    Configs.tempCattleResume = result.get(0);
                    Configs.tempTag = result.get(0).getIndividualNo();
                    Configs.tempRfid = result.get(0).getRegistrationNo();
                    Configs.tempUnid = result.get(0).getUnid();
                    tag.set(Configs.tempTag);
                    rfid.set(Configs.tempRfid);
                    remarkParamEntity.setShowName(result.get(0).getRemark());
                    Configs.tempCattleResume.setPhotoPath(markeImgUrl);

                    String[] filedName = EntityUtils.getFiledName(result.get(0));
                    for (String name : filedName) {

                        for (GenTableColumn gtc : Configs.cattleresume) {

                            if (name.equals(gtc.getJavaField())) {
                                try {
//                                    Log.e("key:", name);
                                    Object fieldValueByName = EntityUtils.getFieldValueByName(name, result.get(0));
                                    String value = fieldValueByName == null ? "" : fieldValueByName.toString();
//                                    Log.e("value:", value);
                                    gtc.setContent(value);
                                    String showName = value;
                                    // 如果是选择的，查字典项
                                    if (!StringUtils.isEmpty(gtc.getDictType())) {
                                        QueryBuilder<DictEntity> builder =
                                                DbUtil.getInstance().getQueryBuilder(DictEntity.class)
                                                        .where(DictEntityDao.Properties.DictType.eq(gtc.getDictType())
                                                                , DictEntityDao.Properties.DictValue.eq(value));
                                        List<DictEntity> dictEntities = DbUtil.getInstance().queryAll(DictEntity.class, builder);
                                        if (dictEntities != null && dictEntities.size() > 0) {
                                            showName = dictEntities.get(0).getDictLabel();
                                        }
                                    }
                                    gtc.setShowName(showName);

                                } catch (IllegalAccessException e) {
                                    e.printStackTrace();
                                }
                            }
                        }

                    }

                    onNotifyAllEvent.setValue(false);
                } else {
                    if (isModify)
                        onNotifyAllEvent.setValue(true);
                    isModify = false;
                }

            }

            @Override
            public void onFailed() {
                onNotifyAllEvent.setValue(true);
                ToastUtils.showShort("基础档案数据库查询失败");
            }
        }).queryAsyncAll(CattleResumeEntity.class, builder);
    }

    private void saveCattleresume() {

        JsonObject jsonObject = new JsonObject();
        for (GenTableColumn gtc : Configs.cattleresume) {
            //防止转json类型错误
            if ("".equals(gtc.getContent())) {
                switch (gtc.getJavaType()) {
                    case "Long":
                    case "Double":
                    case "Integer":
                    case "BigDecimal":
                        gtc.setContent("0");
                        break;
                }
            }
            jsonObject.addProperty(gtc.getJavaField(), gtc.getContent());
        }

        Gson gson = new Gson();
        CattleResumeEntity cattleResumeEntity = gson.fromJson(jsonObject, CattleResumeEntity.class);

        dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (!isModify) {//新增
//            uuid = IdUtil.createSnowflake(3, 1).nextId();
            cattleResumeEntity.setUnid(Configs.tempCattleResume.getUnid());
            cattleResumeEntity.setIndividualNo(tag.get());//修改去配置里修改
            cattleResumeEntity.setCreateBy(SPUtils.getInstance().getString(Configs.SP_LOGIN_NAME));

            cattleResumeEntity.setCreateTime(dateFormat.format(new Date()));
        } else {
            cattleResumeEntity.setCreateBy(Configs.tempCattleResume.getCreateBy());
            cattleResumeEntity.setCreateTime(Configs.tempCattleResume.getCreateTime());
            cattleResumeEntity.setUnid(Configs.tempUnid);
            cattleResumeEntity.setUpdateBy(SPUtils.getInstance().getString(Configs.SP_LOGIN_NAME));
            cattleResumeEntity.setUpdateTime(dateFormat.format(new Date()));

        }
        //保存图片
        if (Configs.tempCattleResume.getPhotoPath() != null && !Configs.tempCattleResume.getPhotoPath().equals("")) {
            cattleResumeEntity.setPhoto(BaseImageUtils.bitmapToString(Configs.tempCattleResume.getPhotoPath(), getApplication()));
        }
            cattleResumeEntity.setDeptId(Long.parseLong(SPUtils.getInstance().getString(Configs.SP_DEPT_ID)));
        cattleResumeEntity.setRegistrationNo(rfid.get());
        cattleResumeEntity.setRemark(remarkParamEntity.getContent());
        cattleResumeEntity.setUploadStatus("0");


        uploadData = new ArrayList<>();
        uploadData.add(cattleResumeEntity);

        DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
            @Override
            public void onNotification(boolean result) {
                dismissDialog();
                if (result) {
                    isModify = false;
                    clearTempInfo();
                    onNotifyAllEvent.setValue(true);
                    onShowDialogEvent.setValue("保存基础信息成功!");
                } else {
                    ToastUtils.showShort("保存基础信息失败");
                }
            }
        }).insertAsyncBatch(CattleResumeEntity.class, uploadData);


    }


    @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();
                    isScan = false;

                    if ("".equals(rfidTag))
                        checkEpc(epc, tid);
                }
            } else if (msg.what == 0x222) {
                App.getInstance().getLinkage().stopInventory();
                isScan = false;
                ToastUtils.showShort("停止盘点");
            }
        }
    };

    private void checkEpc(String epc, String tid) {
        ToastUtils.showShort("盘点到标签：" + epc + "|停止盘点");
        rfidTag = epc + tid;
        initDataForRfid(epc);
    }

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

    private void clearTempInfo() {

        Configs.tempTag = "";
        Configs.tempUnid = null;
        Configs.tempRfid = "";
        Configs.tempCattleResume = null;
        tag.set("");
        rfid.set("");
        rfidTag = "";
    }


    //清空数据源
    public void clearParamList() {

        //备注清除数据
        markeImgUrl = "";
        remarkParamEntity.setContent("");
        remarkParamEntity.setShowName("");
        currentParamEntity = new GenTableColumn();
        for (GenTableColumn gtc : Configs.cattleresume) {
            gtc.setShowName("");
            gtc.setContent("");
        }
    }

}
