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

import android.app.Application;
import android.graphics.drawable.Drawable;
import android.os.Environment;

import androidx.annotation.NonNull;
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.BR;
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.entity.GenTableColumn;
import com.phlx.anchorcollect.entity.PerformanceEntity;
import com.phlx.anchorcollect.ui.fragment.list.CollectGridItem;
import com.phlx.anchorcollect.util.EntityUtils;

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

import cn.hutool.core.util.IdUtil;
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.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 PerformanceVM extends BaseViewModel<Repository> {

    public Drawable drawableImg;
    //照片路径
    private String imgUrl;
    private File imgFile;

    //存放非list控件
    public List<GenTableColumn> uiList = new ArrayList<>();
    public GenTableColumn currentParamEntity;
    public GenTableColumn remarkParamEntity = 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> weight = new ObservableField<>("125.5");

    private long uuid;

    private SimpleDateFormat dateFormat;

    private List<PerformanceEntity> uploadData;


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

    public void initGen() {

        imgUrl = Environment.getExternalStorageDirectory().getAbsolutePath() +
                "/collect/picture/"
                + "anchorCiq" + tag + ".jpg";
        imgFile = new File(imgUrl);

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

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


        uuid = IdUtil.createSnowflake(3, 1).nextId();

    }

    public void initData(String tag) {

        uuid = IdUtil.createSnowflake(3, 1).nextId();

        queryPerformance(tag);
    }


    public void onItemClick(GenTableColumn entity) {

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

        if (!"1".equals(entity.getIsEdit())) return;

        currentParamEntity = entity;
        onCardClickEvent.call();
    }

    public void click(int id) {

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

        //99备注，100照片
        if (id == 99) {
            currentParamEntity = remarkParamEntity;
        } else {
            currentParamEntity = uiList.get(id);
        }

        if (!"1".equals(currentParamEntity.getIsEdit())) return;
        onCardClickEvent.call();
    }

    private void queryPerformance(String tag) {

    }

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

    private void savePerformance() {

        JsonObject jsonObject = new JsonObject();
        for (GenTableColumn gtc : Configs.performance) {
            jsonObject.addProperty(gtc.getJavaField(), gtc.getContent());
        }

        Gson gson = new Gson();
        PerformanceEntity performanceEntity = gson.fromJson(jsonObject, PerformanceEntity.class);
        performanceEntity.setUnid(uuid + "");
        performanceEntity.setUploadStatus("0");
        performanceEntity.setDeptId(SPUtils.getInstance().getString(Configs.SP_DEPT_ID));
        performanceEntity.setCreateBy(SPUtils.getInstance().getString(Configs.SP_LOGIN_NAME));

        dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        performanceEntity.setCreateTime(dateFormat.format(new Date()));

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

        DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
            @Override
            public void onNotification(boolean result) {
                dismissDialog();
                if (result) {
                    clearParamList();
                    onShowDialogEvent.setValue("保存性能测定成功!");
                } else {
                    ToastUtils.showShort("保存性能测定失败");
                }
            }
        }).insertAsyncBatch(PerformanceEntity.class, uploadData);


    }

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

        //备注清除数据
        remarkParamEntity.setContent("");
        remarkParamEntity.setShowName("");
        currentParamEntity = new GenTableColumn();
        uuid = IdUtil.createSnowflake(3, 1).nextId();
        for (GenTableColumn gtc : Configs.cattleresume) {
            gtc.setShowName("");
            gtc.setContent("");
        }
    }


}
