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

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.Quarantine;
import com.phlx.wool.entity.QuarantineDetail;
import com.phlx.wool.entity.QuarantineDetailDao;
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 org.greenrobot.greendao.query.QueryBuilder;

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.ToastUtils;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class QuarantineVM extends BackBarVM<Repository> {

    public Quarantine entity;
    public List<IKeyAndValue> varietyItemData;
    public SingleLiveEvent<Boolean> quarantineDay = new SingleLiveEvent<>();
    public SingleLiveEvent<Boolean> immunityDay = new SingleLiveEvent<>();
    private ArrayList<Label> labels;
    public SingleLiveEvent<Boolean> showSearch = new SingleLiveEvent<>();
    private SimpleDateFormat dateFormat;
    private long parentId = -1;

    public QuarantineVM(@NonNull Application application, Repository repository) {
        super(application, repository);
        if (entity == null) {
            entity = new Quarantine();
        }
        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");
    }

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

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

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

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


    public BindingCommand onQuarantineTimeClick = new BindingCommand(() -> quarantineDay.call());

    public BindingCommand onImmunityTimeClick = new BindingCommand(() -> immunityDay.call());
    public BindingCommand onQuarantinePersonClick = new BindingCommand(() -> showSearch.call());

    public void setQuarantineTime(Date date) {


        entity.setQuarantineTime(dateFormat.format(date));
        entity.notifyChange();
    }

    public void setImmunityTime(Date date) {
        entity.setImmuneDate(dateFormat.format(date));
        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 (parentId == -1) {
            entity.setManagerName(SPUtils.getInstance().getString(Configs.SP_UNIT_NAME));
            entity.setManagerCode(SPUtils.getInstance().getString(Configs.SP_UNIT_CODE));
            entity.setManagerPhone(SPUtils.getInstance().getString(Configs.SP_UNIT_PHONE));
            entity.setCreateBy(SPUtils.getInstance().getString(Configs.SP_LOGIN_NAME));
            entity.setCreateTime(dateFormat.format(new Date(System.currentTimeMillis())));
            entity.setStatus(1);
            parentId = DbUtil.getInstance().insertOrReplace(entity);
            KLog.e(parentId + "---");
            List<QuarantineDetail> detailList = new ArrayList<>();
            for (int i = 0; i < labels.size(); i++) {
                QuarantineDetail quarantineDetail = new QuarantineDetail();
                quarantineDetail.setQuarantineId(parentId);
                quarantineDetail.setEpc(labels.get(i).getEpc());
                quarantineDetail.setTid(labels.get(i).getTid());
                quarantineDetail.setIsLegalStatus(labels.get(i).getIsLegalStatus());
                quarantineDetail.setTwodimensionno(labels.get(i).getTwodimensionno());
                quarantineDetail.setReceivingUnit(labels.get(i).getReceivingUnit());
                quarantineDetail.setCreateBy(SPUtils.getInstance().getString(Configs.SP_LOGIN_NAME));
                quarantineDetail.setCreateTime(dateFormat.format(new Date(System.currentTimeMillis())));
                detailList.add(quarantineDetail);
            }
            DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                @Override
                public void onNotification(boolean result) {
                    if (result) {
                        dismissDialog();
                        if (Configs.isOnLine) {
                            uploadQuarantine();
                        } else {
                            backInventory();
                        }
                    }
                }
            }).insertAsyncBatch(QuarantineDetail.class, detailList);

        } else {
            entity.setId(parentId);
            entity.setStatus(1);
            DbUtil.getInstance().insertOrReplace(entity);
            if (Configs.isOnLine) {
                uploadQuarantine();
            } else {
                backInventory();
            }
        }
    }

    /**
     * 上传数据
     */
    private void uploadQuarantine() {
        Quarantine quarantine = DbUtil.getInstance().queryById(Quarantine.class, parentId);
        if (quarantine.getList() != null && quarantine.getList().size() > 0) {
            quarantine.setList(null);
        }
        QueryBuilder<QuarantineDetail> builder =
                DbUtil.getInstance().getQueryBuilder(QuarantineDetail.class).
                        where(QuarantineDetailDao.Properties.QuarantineId.eq(parentId));
        List<QuarantineDetail> quarantineDetails =
                DbUtil.getInstance().queryAll(QuarantineDetail.class, builder);
        quarantine.setList(quarantineDetails);
        String postInfoStr =
                new GsonBuilder().serializeNulls()
//                        .excludeFieldsWithoutExposeAnnotation()
                        .create().toJson(new UploadParams<Quarantine>(quarantine));
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),
                postInfoStr);
        KLog.e(postInfoStr);
        addSubscribe(model.submitQuarantine(body)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(disposable -> showDialog("正在上传检疫数据..."))
                .subscribe((Consumer<CattleResponse<List<Quarantine>>>) response -> {
                    KLog.e(response.getCode() + response.getMsg());
                    dismissDialog();
                    if (response.getCode() == 0) {
                        DbUtil.getInstance().deleteById(Quarantine.class, parentId);

                        DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                            @Override
                            public void onNotification(boolean result) {
                                if (result) {
                                    backInventory();
                                }
                            }
                        }).deleteAsyncBatch(QuarantineDetail.class, quarantineDetails);
                    } else {
                        ToastUtils.showShort("上传失败");
                    }
                }, (Consumer<ResponseThrowable>) throwable -> {
                    dismissDialog();
                    ToastUtils.showShort(throwable.message);
                })
        );

    }


}
