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

import android.app.Application;
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.DivisionEntity;
import com.phlx.wool.entity.VillusBuyEntity;
import com.phlx.wool.entity.VillusGaugeEntity;
import com.phlx.wool.params.CattleResponse;
import com.phlx.wool.params.UploadParams;
import com.phlx.wool.ui.base.BackBarVM;
import com.phlx.wool.widget.ItemData;

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

import cn.hutool.core.util.IdUtil;
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 VillusGaugeVM extends BackBarVM<Repository> {

    public VillusGaugeEntity entity;
    public List<IKeyAndValue> batchItemData;

    public SingleLiveEvent<Boolean> gaugeDay = new SingleLiveEvent<>();
    private SimpleDateFormat dateFormat;

    private List<VillusGaugeEntity> uploadData;

    private Long id;

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

        id = IdUtil.createSnowflake(3, 1).nextId();

        if (entity == null) {
            entity = new VillusGaugeEntity();
        }

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

        batchItemData = new ArrayList<>();
        List<VillusBuyEntity> villusBuyEntities = model.getVillusBuy();
        if (villusBuyEntities != null && villusBuyEntities.size() > 0) {
            for (VillusBuyEntity villusBuyEntity : villusBuyEntities) {
                batchItemData.add(new ItemData(villusBuyEntity.getBuyBatch(), villusBuyEntity.getBuyBatch()));
            }
        }
    }

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

    //出生日期
    public BindingCommand onGaugeDateClick = new BindingCommand(() -> gaugeDay.call());

    public void setGaugeDate(Date date) {
        entity.setMeasuringTime(dateFormat.format(date));
        entity.notifyChange();
    }

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

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

        if (StringUtils.isEmpty(entity.getBuyBatch())) {
            ToastUtils.showShort("请选择收购批次");
            return;
        }
        if (StringUtils.isEmpty(entity.getMeasuringTime())) {
            ToastUtils.showShort("请选择测量日期");
            return;
        }
        if (StringUtils.isEmpty(entity.getDiameter())) {
            ToastUtils.showShort("请填写直径");
            return;
        }
        if (StringUtils.isEmpty(entity.getLength())) {
            ToastUtils.showShort("请填写长度");
            return;
        }
        if (StringUtils.isEmpty(entity.getLenghtRsd())) {
            ToastUtils.showShort("请填写长度变异系数");
            return;
        }
        if (StringUtils.isEmpty(entity.getVillusStraightLong())) {
            ToastUtils.showShort("请填写绒伸直长");
            return;
        }

        uploadData = new ArrayList<>();
        entity.setId(id);
        entity.setCreateBy(SPUtils.getInstance().getString(Configs.SP_LOGIN_NAME));
        entity.setCreateTime(dateFormat.format(new Date()));
        entity.setStatus(1);
        uploadData.add(entity);

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

    private void uploadVillusGauge() {

        String postInfoStr =
                new GsonBuilder().serializeNulls()
//                        .excludeFieldsWithoutExposeAnnotation()
                        .create().toJson(new UploadParams<List<VillusGaugeEntity>>(uploadData));
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), postInfoStr);
        KLog.e(postInfoStr);
        addSubscribe(model.submitVillusGauge(body)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(disposable -> showDialog("正在上传绒毛测量数据..."))
                .subscribe((Consumer<CattleResponse<List<VillusBuyEntity>>>) 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();
                                    backMain();
                                }
                            }
                        }).deleteAsyncBatch(VillusGaugeEntity.class, uploadData);
                    } else {
                        dismissDialog();
                        ToastUtils.showShort("上传失败");
                    }
                }, (Consumer<ResponseThrowable>) throwable -> {
                    dismissDialog();
                    ToastUtils.showShort(throwable.message);
                })
        );
    }

    private void backMain() {
        finish();
    }

}
