package com.phlx.anchorcollect.ui.info;

import android.app.Application;
import android.view.View;

import androidx.annotation.NonNull;

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.BreedingRecordDetailEntityDao;
import com.phlx.anchorcollect.db.gen.BreedingRecordEntityDao;
import com.phlx.anchorcollect.db.gen.DictEntityDao;
import com.phlx.anchorcollect.db.gen.ImmuneBatchDetailEntityDao;
import com.phlx.anchorcollect.db.gen.ImmuneBatchEntityDao;
import com.phlx.anchorcollect.db.gen.MedicalRecordEntityDao;
import com.phlx.anchorcollect.db.gen.PerformanceEntityDao;
import com.phlx.anchorcollect.db.interf.DbQueryCallBack;
import com.phlx.anchorcollect.entity.BreedingRecordDetailEntity;
import com.phlx.anchorcollect.entity.BreedingRecordEntity;
import com.phlx.anchorcollect.entity.DictEntity;
import com.phlx.anchorcollect.entity.GenTableColumn;
import com.phlx.anchorcollect.entity.ImmuneBatchDetailEntity;
import com.phlx.anchorcollect.entity.ImmuneBatchEntity;
import com.phlx.anchorcollect.entity.MedicalRecordEntity;
import com.phlx.anchorcollect.entity.PerformanceEntity;
import com.phlx.anchorcollect.ui.base.BackBarVM;
import com.phlx.anchorcollect.util.DateUtils;
import com.phlx.anchorcollect.util.EntityUtils;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.StringUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

public class CattleVM extends BackBarVM<Repository> {

    //刷新list

    public SingleLiveEvent<Integer> observableRefreshList = new SingleLiveEvent<>();

//    private static String registrationNo;

    private List<PerformanceEntity> performanceEntityList;
    private List<MedicalRecordEntity> medicalRecordEntityList;
    private List<ImmuneBatchEntity> immuneBatchEntityList;
    //    private  List<ImmuneBatchDetailEntity> immuneBatchDetailEntityList;
    private List<BreedingRecordEntity> breedingRecordEntityList;
    private List<BreedingRecordDetailEntity> breedingRecordDetailEntityList;

    //给RecyclerView添加ItemBinding
    public ItemBinding<CattleItem> itemBinding = ItemBinding.of(BR.viewModel, R.layout.item_cattle_rv);


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

    }

    public void initToolbar() {
        setBackTitleText("牛信息汇总");
        setBackRightTextVisible(View.GONE);
    }

    public void querySignMeasureList() {

        QueryBuilder<PerformanceEntity> builder =
                DbUtil.getInstance().getQueryBuilder(PerformanceEntity.class)
                        .where(PerformanceEntityDao.Properties.CattleresumeId.eq(Configs.tempUnid))
                        .orderDesc(PerformanceEntityDao.Properties.CreateTime);
        DbUtil.getInstance().queryAsyncAll(PerformanceEntity.class, builder, new DbQueryCallBack<PerformanceEntity>() {
            @Override
            public void onSuccess(List<PerformanceEntity> result) {

                performanceEntityList = new ArrayList<>();
                if (result != null && result.size() > 0) {
                    performanceEntityList = result;
                }
                observableRefreshList.setValue(0);
            }

            @Override
            public void onFailed() {
                ToastUtils.showShort("性能测定-数据库查询失败");
            }
        });
    }

    public void queryMedicalRecordList() {

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

                medicalRecordEntityList = new ArrayList<>();
                if (result != null && result.size() > 0) {
                    medicalRecordEntityList = result;
                }
                observableRefreshList.setValue(1);
            }

            @Override
            public void onFailed() {
                ToastUtils.showShort("诊疗记录-数据库查询失败");
            }
        });
    }

    public void queryImmunRecordList() {

        QueryBuilder<ImmuneBatchDetailEntity> detailBuilder =
                DbUtil.getInstance().getQueryBuilder(ImmuneBatchDetailEntity.class)
                        .where(ImmuneBatchDetailEntityDao.Properties.CattleresumeUnid.eq(Configs.tempUnid));
        DbUtil.getInstance().queryAsyncAll(ImmuneBatchDetailEntity.class, detailBuilder, new DbQueryCallBack<ImmuneBatchDetailEntity>() {
            @Override
            public void onSuccess(List<ImmuneBatchDetailEntity> result) {

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

                    List<Long> immuneIds = new ArrayList<>();
                    for (ImmuneBatchDetailEntity ibde : result) {
                        immuneIds.add(ibde.getImmunebatchUnid());
                    }

                    if (immuneIds.size() > 0) {
                        QueryBuilder<ImmuneBatchEntity> builder =
                                DbUtil.getInstance().getQueryBuilder(ImmuneBatchEntity.class)
                                        .where(ImmuneBatchEntityDao.Properties.Unid.in(immuneIds))
                                        .orderDesc(ImmuneBatchEntityDao.Properties.CreateTime);
                        DbUtil.getInstance().queryAsyncAll(ImmuneBatchEntity.class, builder, new DbQueryCallBack<ImmuneBatchEntity>() {
                            @Override
                            public void onSuccess(List<ImmuneBatchEntity> result) {

                                immuneBatchEntityList = new ArrayList<>();
                                if (result != null && result.size() > 0) {
                                    immuneBatchEntityList = result;
                                }
                                observableRefreshList.setValue(2);
                            }

                            @Override
                            public void onFailed() {
                                ToastUtils.showShort("免疫记录-数据库查询失败");
                            }
                        });
                    }
                } else {
                    observableRefreshList.setValue(2);
                }
            }

            @Override
            public void onFailed() {
                ToastUtils.showShort("免疫记录-子表-数据库查询失败");
            }
        });

    }

    public void queryBreedingRecordList() {

        QueryBuilder<BreedingRecordEntity> builder =
                DbUtil.getInstance().getQueryBuilder(BreedingRecordEntity.class)
                        .where(BreedingRecordEntityDao.Properties.CattleresumeId.eq(Configs.tempUnid))
                        .orderDesc(BreedingRecordEntityDao.Properties.CreateTime);
        DbUtil.getInstance().queryAsyncAll(BreedingRecordEntity.class, builder, new DbQueryCallBack<BreedingRecordEntity>() {
            @Override
            public void onSuccess(List<BreedingRecordEntity> result) {

                breedingRecordEntityList = new ArrayList<>();
                if (result != null && result.size() > 0) {
                    breedingRecordEntityList = result;
                }
                observableRefreshList.setValue(3);
            }

            @Override
            public void onFailed() {
                ToastUtils.showShort("配种记录主表-数据库查询失败");
            }
        });

    }

    public void queryBreedingRecordDetailList() {

        QueryBuilder<BreedingRecordEntity> builder =
                DbUtil.getInstance().getQueryBuilder(BreedingRecordEntity.class)
                        .where(BreedingRecordEntityDao.Properties.CattleresumeId.eq(Configs.tempUnid)
//                                , BreedingRecordEntityDao.Properties.CreateTime.like(DateUtils.getYear() + "%")
                        )
                        .orderDesc(BreedingRecordEntityDao.Properties.CreateTime);
        DbUtil.getInstance().queryAsyncAll(BreedingRecordEntity.class, builder, new DbQueryCallBack<BreedingRecordEntity>() {
            @Override
            public void onSuccess(List<BreedingRecordEntity> result) {

                if (result != null && result.size() > 0) {
                    //查询子表
                    QueryBuilder<BreedingRecordDetailEntity> builder2 =
                            DbUtil.getInstance().getQueryBuilder(BreedingRecordDetailEntity.class)
                                    .where(BreedingRecordDetailEntityDao.Properties.FUnid.eq(result.get(0).getUnid())
//                                            , BreedingRecordDetailEntityDao.Properties.CreateTime.like(DateUtils.getYear() + "%")
                                    )
                                    .orderDesc(BreedingRecordDetailEntityDao.Properties.CreateTime);
                    DbUtil.getInstance().queryAsyncAll(BreedingRecordDetailEntity.class, builder2, new DbQueryCallBack<BreedingRecordDetailEntity>() {
                        @Override
                        public void onSuccess(List<BreedingRecordDetailEntity> result) {

                            breedingRecordDetailEntityList = new ArrayList<>();
                            if (result != null && result.size() > 0) {
                                breedingRecordDetailEntityList = result;
                                for (BreedingRecordDetailEntity detailEntity:breedingRecordDetailEntityList) {
                                    detailEntity.setRaiseVarieties(Configs.raiseVarieties);
                                    detailEntity.setBreedingPlantId(Configs.deptName);
                                }
                            }
                            observableRefreshList.setValue(3);
                        }

                        @Override
                        public void onFailed() {
                            ToastUtils.showShort("配种记录子表-数据库查询失败");
                        }
                    });
                }
            }

            @Override
            public void onFailed() {
                ToastUtils.showShort("配种记录主表-数据库查询失败");
            }
        });


    }

    public List<PerformanceEntity> getPerformanceEntityList() {

        List<PerformanceEntity> resultList = new ArrayList<>();

        if (performanceEntityList == null) {
            return resultList;
        }

        for (PerformanceEntity pe : performanceEntityList) {

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

                for (GenTableColumn gtc : Configs.performance) {

                    if (name.equals(gtc.getJavaField())) {
                        try {
//                                    Log.e("key:", name);
                            Object fieldValueByName = EntityUtils.getFieldValueByName(name, pe);
                            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);
                            gtc.setContent(showName);

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

            }

            //再把格式bean里的数据转换为数据bean
            JsonObject jsonObject = new JsonObject();
            for (GenTableColumn gtc : Configs.performance) {
                //防止转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();
            Long unidTemp = pe.getUnid();
            pe = gson.fromJson(jsonObject, PerformanceEntity.class);
            pe.setUnid(unidTemp);
            resultList.add(pe);

        }
//        resultList.clear();
//        Arrays.copyOf()
//        System.arraycopy(performanceEntityList, 0, resultList, 0 , performanceEntityList.size());
        return resultList;
    }

    public List<MedicalRecordEntity> getMedicalRecordEntityList() {


        List<MedicalRecordEntity> resultList = new ArrayList<>();

        if (medicalRecordEntityList == null) {
            return resultList;
        }

        for (MedicalRecordEntity pe : medicalRecordEntityList) {

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

                for (GenTableColumn gtc : Configs.medicalrecords) {

                    if (name.equals(gtc.getJavaField())) {
                        try {
//                                    Log.e("key:", name);
                            Object fieldValueByName = EntityUtils.getFieldValueByName(name, pe);
                            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);
                            gtc.setContent(showName);

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

            }

            //再把格式bean里的数据转换为数据bean
            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();
            Long unidTemp = pe.getUnid();
            pe = gson.fromJson(jsonObject, MedicalRecordEntity.class);
            pe.setUnid(unidTemp);
            resultList.add(pe);

        }
//        resultList.clear();
//        Arrays.copyOf()
//        System.arraycopy(performanceEntityList, 0, resultList, 0 , performanceEntityList.size());
        return resultList;
    }

    public List<ImmuneBatchEntity> getImmuneBatchEntityList() {

        List<ImmuneBatchEntity> resultList = new ArrayList<>();

        if (immuneBatchEntityList == null) {
            return resultList;
        }

        for (ImmuneBatchEntity pe : immuneBatchEntityList) {

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

                for (GenTableColumn gtc : Configs.immunebatch) {

                    if (name.equals(gtc.getJavaField())) {
                        try {
//                                    Log.e("key:", name);
                            Object fieldValueByName = EntityUtils.getFieldValueByName(name, pe);
                            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);
                            gtc.setContent(showName);

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

            }

            //再把格式bean里的数据转换为数据bean
            JsonObject jsonObject = new JsonObject();
            for (GenTableColumn gtc : Configs.immunebatch) {
                //防止转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();
            Long unidTemp = pe.getUnid();
            pe = gson.fromJson(jsonObject, ImmuneBatchEntity.class);
            pe.setUnid(unidTemp);
            resultList.add(pe);

        }
//        resultList.clear();
//        Arrays.copyOf()
//        System.arraycopy(performanceEntityList, 0, resultList, 0 , performanceEntityList.size());
        return resultList;

    }

    public List<BreedingRecordDetailEntity> getBreedingRecordEntityList() {


        List<BreedingRecordDetailEntity> resultList = new ArrayList<>();

        if (breedingRecordDetailEntityList == null) {
            return resultList;
        }

        for (BreedingRecordDetailEntity pe : breedingRecordDetailEntityList) {

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

                for (GenTableColumn gtc : Configs.cattlematingMasterList) {

                    if (name.equals(gtc.getJavaField())) {
                        try {
//                                    Log.e("key:", name);
                            Object fieldValueByName = EntityUtils.getFieldValueByName(name, pe);
                            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);
                            gtc.setContent(showName);

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

            }

            //再把格式bean里的数据转换为数据bean
            JsonObject jsonObject = new JsonObject();
            for (GenTableColumn gtc : Configs.cattlematingMasterList) {
                //防止转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();
            Long unidTemp = pe.getUnid();
            pe = gson.fromJson(jsonObject, BreedingRecordDetailEntity.class);
            pe.setUnid(unidTemp);
            resultList.add(pe);

        }
//        resultList.clear();
//        Arrays.copyOf()
//        System.arraycopy(performanceEntityList, 0, resultList, 0 , performanceEntityList.size());
        return resultList;

    }

    //    private void refreshCard() {
//
//        String sql = ("REGISTRATION_NO IN " +
//                "(SELECT REGISTRATION_NO FROM CARD_ENTITY WHERE REGISTRATION_NO =" + registrationNo + " )");
//        WhereCondition.StringCondition stringCondition = new WhereCondition.StringCondition(sql);
//        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<CardEntity>() {
//            @Override
//            public void onSuccess(List<CardEntity> result) {
//                observablePedigreeList.clear();
//                if (result.size() > 0) {
//                    CardEntity cardEntity = result.get(0);
//                    observablePedigreeList.add(new CattleItem(CattleVM.this, "耳标", cardEntity.getRegistrationNo()));
//                    observablePedigreeList.add(new CattleItem(CattleVM.this, "出生", cardEntity.getEaseBirth()));
//                    observablePedigreeList.add(new CattleItem(CattleVM.this, "性别", cardEntity.getSex()));
//                    observablePedigreeList.add(new CattleItem(CattleVM.this, "品种", cardEntity.getVarieties()));
//                    observablePedigreeList.add(new CattleItem(CattleVM.this, "生日", cardEntity.getBirthdate()));
//                    observablePedigreeList.add(new CattleItem(CattleVM.this, "胎次", cardEntity.getChildTime()));
//                }
//                refreshSign();
//            }
//
//            @Override
//            public void onFailed() {
//                ToastUtils.showShort("基础档案数据库查询失败");
//                refreshSign();
//            }
//        }).queryAsync(CardEntity.class, stringCondition);
//    }


}
