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.gen.DictEntityDao;
import com.phlx.anchorcollect.db.gen.MedicalRecordEntityDao;
import com.phlx.anchorcollect.db.gen.PerformanceEntityDao;
import com.phlx.anchorcollect.db.interf.DbIDUCallBack;
import com.phlx.anchorcollect.db.interf.DbQueryCallBack;
import com.phlx.anchorcollect.entity.DictEntity;
import com.phlx.anchorcollect.entity.GenTableColumn;
import com.phlx.anchorcollect.entity.MedicalRecordEntity;
import com.phlx.anchorcollect.entity.PerformanceEntity;
import com.phlx.anchorcollect.ui.fragment.list.CollectGridItem;
import com.phlx.anchorcollect.util.EntityUtils;

import org.greenrobot.greendao.query.QueryBuilder;

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 MedicalRecordVM extends BaseViewModel<Repository> {

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

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

    //存放非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");

    public boolean isModify = false;
    private long uuid;

    private SimpleDateFormat dateFormat;

    private List<MedicalRecordEntity> uploadData;

    public MedicalRecordVM(@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.medicalrecords) {
            CollectGridItem cgi = new CollectGridItem(this, gtc, Configs.TREATMENT_RECORD);
            observableList.add(cgi);
        }

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

    }

    private void initData(MedicalRecordEntity medicalRecordEntity) {

        remarkParamEntity.setShowName(medicalRecordEntity.getRemark());
        remarkParamEntity.setContent(medicalRecordEntity.getRemark());

        String[] filedName = EntityUtils.getFiledName(medicalRecordEntity);
        for (String name : filedName) {

            for (GenTableColumn gtc : Configs.medicalrecords) {

                if (name.equals(gtc.getJavaField())) {
                    try {
                        Object fieldValueByName = EntityUtils.getFieldValueByName(name, medicalRecordEntity);
                        String value = fieldValueByName == null ? "" : fieldValueByName.toString();
//                        Log.e("fieldValue:", "key:" + name + " | 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);
        }

    }

    public void queryMedicalRecord() {

        QueryBuilder<MedicalRecordEntity> builder =
                DbUtil.getInstance().getQueryBuilder(MedicalRecordEntity.class)
                        .where(MedicalRecordEntityDao.Properties.Unid.eq(Configs.resumeId));
        DbUtil.getInstance().queryAsyncAll(MedicalRecordEntity.class, builder, new DbQueryCallBack<MedicalRecordEntity>() {
            @Override
            public void onSuccess(List<MedicalRecordEntity> result) {

                if (result != null && result.size() > 0) {
                    initData(result.get(0));
                }
            }

            @Override
            public void onFailed() {

                //清除选中unid
                Configs.resumeId = null;
                onNotifyAllEvent.setValue(true);
                ToastUtils.showShort("诊疗记录-数据库查询失败");
            }
        });

    }

    public void onItemClick(GenTableColumn entity) {

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

        if (!"1".equals(entity.getIsEdit()) && isModify) {
            ToastUtils.showShort("此数据无法修改!!");
            return;
        }

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

        currentParamEntity = entity;
        onCardClickEvent.call();
    }

    public void click(int id) {

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

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

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


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

            //判断必填
            for (GenTableColumn gtc : Configs.medicalrecords) {
                if ("1".equals(gtc.getIsRequired()) && StringUtils.isEmpty(gtc.getContent())) {
                    onShowDialogEvent.setValue("请完成" + gtc.getColumnComment() + "的录入");
                    return;
                }
            }

            saveMedicalRecord();
        }
    });

    private void saveMedicalRecord() {

        JsonObject jsonObject = new JsonObject();
        for (GenTableColumn gtc : Configs.medicalrecords) {
            //防止转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();
        MedicalRecordEntity medicalRecordEntity = gson.fromJson(jsonObject, MedicalRecordEntity.class);

        dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (!isModify) {//新增
            uuid = IdUtil.createSnowflake(3, 1).nextId();
            medicalRecordEntity.setUnid(uuid);
            medicalRecordEntity.setCattleresumeId(Configs.tempUnid);
            medicalRecordEntity.setCreateBy(SPUtils.getInstance().getString(Configs.SP_LOGIN_NAME));

            medicalRecordEntity.setCreateTime(dateFormat.format(new Date()));
        } else {
            medicalRecordEntity.setUnid(Configs.resumeId);
            medicalRecordEntity.setCattleresumeId(Configs.tempUnid);
            medicalRecordEntity.setUpdateBy(SPUtils.getInstance().getString(Configs.SP_LOGIN_NAME));
            medicalRecordEntity.setUpdateTime(dateFormat.format(new Date()));
            //清除选中unid
            Configs.resumeId = null;
        }
        medicalRecordEntity.setDeptId(Long.parseLong(SPUtils.getInstance().getString(Configs.SP_DEPT_ID)));
        medicalRecordEntity.setRemark(remarkParamEntity.getContent());
        medicalRecordEntity.setUploadStatus("0");

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

        DbUtil.getInstance().insertAsyncBatch(MedicalRecordEntity.class, uploadData, new DbIDUCallBack() {
            @Override
            public void onNotification(boolean result) {
                dismissDialog();
                if (result) {
                    onNotifyAllEvent.setValue(true);
                    onShowDialogEvent.setValue("保存诊疗记录成功!");
                } else {
                    ToastUtils.showShort("保存诊疗记录失败");
                }
            }
        });


    }

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

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

}
