package com.phlx.wool.ui.work.mark;

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

import androidx.annotation.NonNull;

import com.google.gson.GsonBuilder;
import com.phlx.wool.Configs;
import com.phlx.wool.data.Repository;
import com.phlx.wool.db.DbUtil;
import com.phlx.wool.db.interf.DbIDUCallBack;
import com.phlx.wool.entity.Label;
import com.phlx.wool.entity.Marking;
import com.phlx.wool.entity.Variety;
import com.phlx.wool.params.CattleResponse;
import com.phlx.wool.params.UploadParams;
import com.phlx.wool.ui.base.BackBarVM;
import com.phlx.wool.ui.inventory.InventoryActivity;
import com.phlx.wool.widget.ItemData;

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

import io.reactivex.functions.Consumer;
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.http.ResponseThrowable;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.SPUtils;
import me.goldze.mvvmhabit.utils.StringUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class MarkingVM extends BackBarVM<Repository> {


    public Marking entity;
    public List<IKeyAndValue> varietyItemData;
    public SingleLiveEvent<Boolean> birthDay = new SingleLiveEvent<>();
    private ArrayList<Label> labels;
    private List<Marking> uploadData;
    public SingleLiveEvent<Boolean> showSearch = new SingleLiveEvent<>();
    private SimpleDateFormat dateFormat;

    public MarkingVM(@NonNull Application application, Repository repository) {
        super(application, repository);
        if (entity == null) {
            entity = new Marking();
        }

        entity.setBirthPlace(SPUtils.getInstance().getString(Configs.SP_UNIT_VILLAGE_NAME));

        varietyItemData = new ArrayList<>();
        List<Variety> varieties = model.getVariety();
        if (varieties != null && varieties.size() > 0) {
            for (Variety variety : varieties) {
                varietyItemData.add(new ItemData(variety.getVarietyName(), variety.getVarietyCode()));
            }
        }
        dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    }

    //初始化ToolBar
    public void initToolbar() {
        setBackTitleText("打标");
        setSettingVisibleObservable(View.GONE);
        setBackRightTextVisible(View.VISIBLE);
        setBackRightText("保存");
    }

    public void setLabels(ArrayList<Label> labels) {
        this.labels = labels;
    }

    public BindingCommand<Boolean> onBreedCheckedChangeCommand =
            new BindingCommand<>(new BindingConsumer<Boolean>() {
                @Override
                public void call(Boolean isChecked) {
                    if (isChecked)
                        entity.setIsBreedSheep(1);
                    else
                        entity.setIsBreedSheep(0);
                }
            });

    public BindingCommand<Boolean> onSexCheckedChangeCommand =
            new BindingCommand<>(new BindingConsumer<Boolean>() {
                @Override
                public void call(Boolean isChecked) {
                    if (isChecked)
                        entity.setSex(1);
                    else
                        entity.setSex(0);

                }
            });

    public BindingCommand<Boolean> onTwinCheckedChangeCommand =
            new BindingCommand<>(new BindingConsumer<Boolean>() {
                @Override
                public void call(Boolean isChecked) {
                    if (isChecked)
                        entity.setIsTwins(1);
                    else
                        entity.setIsTwins(0);
                }
            });

    //出生日期
    public BindingCommand onBirthTimeClick = new BindingCommand(() -> birthDay.call());
    public BindingCommand onVeterinaryNameClick = new BindingCommand(() -> showSearch.call());

    public void setBirthTime(Date date) {
        String dateStr = dateFormat.format(date);
        entity.setBirthTime(dateStr.substring(0, dateStr.length() - 3));
        entity.notifyChange();
    }

    public BindingCommand<IKeyAndValue> onVarietySelectorCommand =
            new BindingCommand<>(new BindingConsumer<IKeyAndValue>() {
                @Override
                public void call(IKeyAndValue iKeyAndValue) {
                    entity.setVarietyCode(iKeyAndValue.getValue());
                    entity.setVarietyName(iKeyAndValue.getKey());
                }
            });

    /**
     * 离线保存本地，在线先上传，后保存本地
     */
    @Override
    protected void backRightTextOnClick() {
        if (StringUtils.isEmpty(entity.getVeterinaryCode())) {
            ToastUtils.showShort("请输入兽医名字");
            return;
        }
        if (StringUtils.isEmpty(entity.getVarietyCode())) {
            ToastUtils.showShort("请选择品种");
            return;
        }
        if (StringUtils.isEmpty(entity.getBirthTime())) {
            ToastUtils.showShort("请选择出生日期");
            return;
        }
        entity.setManagerName(SPUtils.getInstance().getString(Configs.SP_UNIT_NAME));
        entity.setManagerCode(SPUtils.getInstance().getString(Configs.SP_UNIT_CODE));

        uploadData = new ArrayList<>();

        KLog.e(labels.size() + labels.toString());

        for (int i = 0; i < labels.size(); i++) {
            Marking marking = new Marking();
            marking.setEpc(labels.get(i).getEpc());
            marking.setTid(labels.get(i).getTid());
            marking.setState("0");
            marking.setIsLegalStatus(labels.get(i).getIsLegalStatus());
            //未上传
            marking.setStatus(1);
            marking.setBirthNum(entity.getBirthNum());
            marking.setBirthPlace(entity.getBirthPlace());
            marking.setBirthTime(entity.getBirthTime());
            marking.setBirthWeight(entity.getBirthWeight());
            marking.setEweEpc(entity.getEweEpc());
            marking.setRamEpc(entity.getRamEpc());
            marking.setRemark(entity.getRemark());
            marking.setSex(entity.getSex());
            marking.setVarietyCode(entity.getVarietyCode());
            marking.setVarietyName(entity.getVarietyName());
            marking.setVeterinaryCode(entity.getVeterinaryCode());
            marking.setVeterinaryName(entity.getVeterinaryName());
            marking.setManagerCode(entity.getManagerCode());
            marking.setManagerName(entity.getManagerName());
            marking.setCreateTime(dateFormat.format(new Date(System.currentTimeMillis())));
            marking.setCreateBy(SPUtils.getInstance().getString(Configs.SP_LOGIN_NAME));
            uploadData.add(marking);
        }

        KLog.e(uploadData.size() + uploadData.toString());
        /**
         * 存储数据库
         */
        showDialog("正在保存本地...");
        DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
            @Override
            public void onNotification(boolean result) {
                if (result) {
                    dismissDialog();
                    if (Configs.isOnLine) {
                        uploadMarking();
                    } else {
                        backInventory();
                    }
                }
            }
        }).insertAsyncBatch(Marking.class, uploadData);
    }

    /**
     * 上传数据
     */
    private void uploadMarking() {
        String postInfoStr =
                new GsonBuilder().serializeNulls()
//                        .excludeFieldsWithoutExposeAnnotation()
                        .create().toJson(new UploadParams<List<Marking>>(uploadData));
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),
                postInfoStr);
        KLog.e(postInfoStr);
        addSubscribe(model.submitMarking(body)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(disposable -> showDialog("正在上传打标数据..."))
                .subscribe((Consumer<CattleResponse<List<Marking>>>) response -> {
                    KLog.e(response.getCode() + response.getMsg());
                    if (response.getCode() == 0) {
                        for (int i = 0; i < uploadData.size(); i++) {
                            uploadData.get(i).setStatus(0);
                        }
                        DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                            @Override
                            public void onNotification(boolean result) {
                                if (result) {
                                    dismissDialog();
                                    backInventory();
                                }
                            }
                        }).deleteAsyncBatch(Marking.class, uploadData);
                    } else {
                        dismissDialog();
                        ToastUtils.showShort("上传失败");
                    }
                }, (Consumer<ResponseThrowable>) throwable -> {
                    dismissDialog();
                    ToastUtils.showShort(throwable.message);
                })
        );

    }

    @Override
    protected void backIconOnClick() {
        backInventory();
    }

    public void backInventory() {
        Bundle mBundle = new Bundle();
        mBundle.putString("type", Configs.WORK_TYPE_M);
        startActivity(InventoryActivity.class, mBundle);
        finish();
    }


}
