package com.phlx.wool.ui.cattle.vm;

import android.app.Application;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.view.View;
import android.widget.ArrayAdapter;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import com.phlx.wool.Configs;
import com.phlx.wool.R;
import com.phlx.wool.data.Repository;
import com.phlx.wool.db.DbUtil;
import com.phlx.wool.db.interf.DbIDUCallBack;
import com.phlx.wool.db.interf.DbQueryCallBack;
import com.phlx.wool.entity.AncestryinfoEntity;
import com.phlx.wool.entity.CattleLabelEntity;
import com.phlx.wool.entity.DivisionEntity;
import com.phlx.wool.entity.EntryRegistrationEntity;
import com.phlx.wool.entity.Unit;
import com.phlx.wool.ui.base.BackBarVM;
import com.phlx.wool.ui.cattle.activity.CattleMarkActivity;
import com.phlx.wool.ui.villus.VillusBuyActivity;
import com.phlx.wool.util.BaseImageUtils;
import com.phlx.wool.widget.ItemData;

import org.greenrobot.greendao.query.QueryBuilder;
import org.greenrobot.greendao.query.WhereCondition;

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.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.binding.command.BindingConsumer;
import me.goldze.mvvmhabit.binding.viewadapter.spinner.IKeyAndValue;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.SPUtils;
import me.goldze.mvvmhabit.utils.StringUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class CattleMarkVM extends BackBarVM<Repository> {

    public CattleLabelEntity entity;

    private SimpleDateFormat dateFormat;

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

    public SingleLiveEvent<Boolean> birthDay = new SingleLiveEvent<>();
    public SingleLiveEvent<Boolean> markPhotoOnClick = new SingleLiveEvent<>();
    public SingleLiveEvent<Boolean> scanLabelOnClick = new SingleLiveEvent<>();
    public SingleLiveEvent<Boolean> ancestryOnClick = new SingleLiveEvent<>();

    private List<CattleLabelEntity> uploadData;

    public List<IKeyAndValue> ancestryItemData, sexItemData;

    //品种刷新用
    private ArrayAdapter<String> spinnerAdapter;
    private List<String> lists = new ArrayList<>();


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


    //初始化ToolBar
    public void initToolbar() {
        setBackTitleText("基础信息录入");
        setSettingVisibleObservable(View.GONE);
        setBackRightTextVisible(View.VISIBLE);
        setBackRightText("保存");

        initData();
    }

    private void initData() {

        entity = new CattleLabelEntity();
        long idNo = IdUtil.createSnowflake(3, 1).nextId();
        entity.setId(idNo + "");
        entity.setPastureUnitId(SPUtils.getInstance().getString(Configs.SP_UNIT_CODE, ""));
        dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        entity.setBirthdate(dateFormat.format(new Date()));
        entity.setWeight(100 + "");

        markeImgUrl = Environment.getExternalStorageDirectory().getAbsolutePath() +
                "/tracing/picture/"
                + "markCiq" + idNo + ".jpg";
        markFile = new File(markeImgUrl);

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

        dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        //血统数据
        ancestryItemData = new ArrayList<>();
        QueryBuilder<AncestryinfoEntity> builder =
                DbUtil.getInstance().getQueryBuilder(AncestryinfoEntity.class);
        DbUtil.getInstance().setDbQueryCallBack(new DbQueryCallBack<AncestryinfoEntity>() {
            @Override
            public void onSuccess(List<AncestryinfoEntity> result) {
                for (AncestryinfoEntity ae : result) {
                    ancestryItemData.add(new ItemData(ae.getAncestryname(), ae.getAncestryid()));
                    lists.add(ae.getAncestryname());
                }
                ancestryOnClick.call();
            }

            @Override
            public void onFailed() {
                ToastUtils.showShort("牲畜品种数据库查询失败");
            }
        }).queryAsyncAll(AncestryinfoEntity.class, builder);

        //性别
        sexItemData = new ArrayList<>();
        sexItemData.add(new ItemData("母", "0"));
        sexItemData.add(new ItemData("公", "1"));
        sexItemData.add(new ItemData("其他", "2"));
    }

    public BindingCommand<IKeyAndValue> onAncestrySelectorCommand = new BindingCommand<>(new BindingConsumer<IKeyAndValue>() {
        @Override
        public void call(IKeyAndValue iKeyAndValue) {
            entity.setAncestryId(iKeyAndValue.getValue());
        }
    });

    public BindingCommand<IKeyAndValue> onSexSelectorCommand = new BindingCommand<>(new BindingConsumer<IKeyAndValue>() {
        @Override
        public void call(IKeyAndValue iKeyAndValue) {
            entity.setSex(iKeyAndValue.getValue());
        }
    });

    //畜生日期
    public BindingCommand onBirthDateClick = new BindingCommand(() -> birthDay.call());

    public void setBirthDate(Date date) {
        dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        entity.setBirthdate(dateFormat.format(date));
        entity.notifyChange();
    }

    public String getMarkImgUrl() {
        return markeImgUrl;
    }

    public BindingCommand markPhotoOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            markPhotoOnClick.call();
        }
    });

    public BindingCommand onScanLabelClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            scanLabelOnClick.call();
        }
    });

    public void setScanLabel(String scanLabel) {
        if (scanLabel.length() == 15) {
            ToastUtils.showShort("scan:" + scanLabel);
            entity.setRegistrationNo(scanLabel);
            entity.notifyChange();
        } else {
            ToastUtils.showShort("非法扫描:" + scanLabel);
        }
    }


    public ArrayAdapter getAdapter(CattleMarkActivity cls) {
        spinnerAdapter = new ArrayAdapter<>(cls, R.layout.simple_spinner_item, lists);
        spinnerAdapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
        return spinnerAdapter;
    }

    /**
     * 离线保存本地，在线先上传，后保存本地
     */
    @Override
    protected void backRightTextOnClick() {

        if (StringUtils.isEmpty(entity.getRegistrationNo())) {
            ToastUtils.showShort("请扫描耳标");
            return;
        }
//        if (StringUtils.isEmpty(entity.getIndividualNo())) {
//            ToastUtils.showShort("请填写个体号");
//            return;
//        }
        if (StringUtils.isEmpty(entity.getBirthdate())) {
            ToastUtils.showShort("请选择出生日期");
            return;
        }
        if (StringUtils.isEmpty(entity.getWeight())) {
            ToastUtils.showShort("请填写体重");
            return;
        }
        if (StringUtils.isEmpty(entity.getMarkImgPath())) {
            ToastUtils.showShort("请上传打标图片");
            return;
        }
        entity.setCreateBy(SPUtils.getInstance().getString(Configs.SP_LOGIN_NAME));
        dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        entity.setCreateTime(dateFormat.format(new Date()));
        if (entity.getMarkImgPath() != null && !entity.getMarkImgPath().equals(""))
            entity.setPhoto(BaseImageUtils.bitmapToString(entity.getMarkImgPath(), getApplication()));
        uploadData = new ArrayList<>();
        uploadData.add(entity);

        KLog.e(uploadData.size() + uploadData.toString());
        /**
         * 存储数据库
         */
        showDialog("正在保存本地...");
        DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
            @Override
            public void onNotification(boolean result) {
                dismissDialog();
                if (result) {
                    ToastUtils.showShort("打标保存成功");
                    backMain();
                } else {
                    ToastUtils.showShort("打标保存失败");
                }
            }
        }).insertAsyncBatch(CattleLabelEntity.class, uploadData);
    }

    public void backMain() {
        finish();
    }


}
