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

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.ArrayList;
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;

    //给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().setDbQueryCallBack(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("性能测定-数据库查询失败");
            }
        }).queryAsyncAll(PerformanceEntity.class, builder);
    }

    public void queryMedicalRecordList() {

        QueryBuilder<MedicalRecordEntity> builder =
                DbUtil.getInstance().getQueryBuilder(MedicalRecordEntity.class)
                        .where(MedicalRecordEntityDao.Properties.CattleresumeId.eq(Configs.tempUnid))
                        .orderDesc(MedicalRecordEntityDao.Properties.CreateTime);
        DbUtil.getInstance().setDbQueryCallBack(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("诊疗记录-数据库查询失败");
            }
        }).queryAsyncAll(MedicalRecordEntity.class, builder);
    }

    public void queryImmunRecordList() {

        QueryBuilder<ImmuneBatchDetailEntity> detailBuilder =
                DbUtil.getInstance().getQueryBuilder(ImmuneBatchDetailEntity.class)
                        .where(ImmuneBatchDetailEntityDao.Properties.CattleresumeUnid.eq(Configs.tempUnid));
        DbUtil.getInstance().setDbQueryCallBack(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().setDbQueryCallBack(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("免疫记录-数据库查询失败");
                            }
                        }).queryAsyncAll(ImmuneBatchEntity.class, builder);
                    }
                }
            }

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

    }

    public void queryBreedingRecordList() {

        QueryBuilder<BreedingRecordEntity> builder =
                DbUtil.getInstance().getQueryBuilder(BreedingRecordEntity.class)
                        .where(BreedingRecordEntityDao.Properties.CattleresumeId.eq(Configs.tempUnid))
                        .orderDesc(BreedingRecordEntityDao.Properties.CreateTime);
        DbUtil.getInstance().setDbQueryCallBack(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("配种记录主表-数据库查询失败");
            }
        }).queryAsyncAll(BreedingRecordEntity.class, builder);

    }

    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<BreedingRecordEntity> getBreedingRecordEntityList() {



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

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

        for (BreedingRecordEntity pe : breedingRecordEntityList) {

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

                for (GenTableColumn gtc : Configs.cattlematingMaster) {

                    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.cattlematingMaster) {
                //防止转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, BreedingRecordEntity.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);
//    }


}
