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

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.Harmless;
import com.phlx.wool.entity.HarmlessDetail;
import com.phlx.wool.entity.HarmlessDetailDao;
import com.phlx.wool.entity.Label;
import com.phlx.wool.entity.TreatmentMethod;
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 HarmlessVM extends BackBarVM<Repository> {

    public Harmless entity;
    public List<IKeyAndValue> TreatmentMethodItemData;
    public SingleLiveEvent<Boolean> onsetTime = new SingleLiveEvent<>();
    public SingleLiveEvent<Boolean> deathTime = new SingleLiveEvent<>();
    public SingleLiveEvent<Boolean> treatmentTime = new SingleLiveEvent<>();
    public SingleLiveEvent<Boolean> showSearch = new SingleLiveEvent<>();
    private ArrayList<Label> labels;
    private SimpleDateFormat dateFormat;
    private long parentId= -1;

    public HarmlessVM(@NonNull Application application, Repository repository) {
        super(application, repository);
        if (entity == null) {
            entity = new Harmless();
        }
        List<TreatmentMethod> treatmentMethods = model.getTreatmentMethod();
        TreatmentMethodItemData = new ArrayList<>();
        if (treatmentMethods != null && treatmentMethods.size() > 0) {
            for (TreatmentMethod item : treatmentMethods) {
                TreatmentMethodItemData.add(new ItemData(item.getTreatmentMethodName(),
                        item.getTreatmentMethodCode()));
            }
        }
        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 onOnsetTimeClick = new BindingCommand(() -> onsetTime.call());
    public BindingCommand onDeathTimeClick = new BindingCommand(() -> deathTime.call());
    public BindingCommand onTreatmentTimeClick = new BindingCommand(() -> treatmentTime.call());
    public BindingCommand onVeterinaryNameClick = new BindingCommand(() -> showSearch.call());

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

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

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

    public BindingCommand<IKeyAndValue> onTreatmentMethodSelectorCommand =
            new BindingCommand<>(new BindingConsumer<IKeyAndValue>() {
                @Override
                public void call(IKeyAndValue iKeyAndValue) {
                    entity.setTreatmentMethodCode(iKeyAndValue.getValue());
                    entity.setTreatmentMethodName(iKeyAndValue.getKey());
                }
            });


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

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

    /**
     * 离线保存本地，在线先上传，后保存本地
     */
    @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.setCreateBy(SPUtils.getInstance().getString(Configs.SP_LOGIN_NAME));
            entity.setCreateTime(dateFormat.format(new Date(System.currentTimeMillis())));
            entity.setStatus(1);
            parentId = DbUtil.getInstance().insertOrReplace(entity);
            List<HarmlessDetail> detailList = new ArrayList<>();
            for (int i = 0; i < labels.size(); i++) {
                HarmlessDetail harmlessDetail = new HarmlessDetail();
                harmlessDetail.setHarmlessId(parentId);
                harmlessDetail.setEpc(labels.get(i).getEpc());
                harmlessDetail.setTid(labels.get(i).getTid());
                harmlessDetail.setIsLegalStatus(labels.get(i).getIsLegalStatus());
                harmlessDetail.setTwodimensionno(labels.get(i).getTwodimensionno());
                harmlessDetail.setReceivingUnit(labels.get(i).getReceivingUnit());
                harmlessDetail.setCreateBy(SPUtils.getInstance().getString(Configs.SP_LOGIN_NAME));
                harmlessDetail.setCreateTime(dateFormat.format(new Date(System.currentTimeMillis())));
                detailList.add(harmlessDetail);
            }
            DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                @Override
                public void onNotification(boolean result) {
                    if (result) {
                        dismissDialog();
                        if (Configs.isOnLine) {
                            uploadHarmless();
                        } else {
                            backInventory();
                        }
                    }
                }
            }).insertAsyncBatch(HarmlessDetail.class, detailList);

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

    /**
     * 上传数据
     */
    private void uploadHarmless() {
        Harmless harmless = DbUtil.getInstance().queryById(Harmless.class, parentId);
        if (harmless.getList() != null && harmless.getList().size() > 0) {
            harmless.setList(null);
        }
        QueryBuilder<HarmlessDetail> builder =
                DbUtil.getInstance().getQueryBuilder(HarmlessDetail.class).
                        where(HarmlessDetailDao.Properties.HarmlessId.eq(parentId));
        List<HarmlessDetail> harmlessDetails = DbUtil.getInstance().queryAll(HarmlessDetail.class, builder);
        harmless.setList(harmlessDetails);
        String postInfoStr =
                new GsonBuilder().serializeNulls()
//                        .excludeFieldsWithoutExposeAnnotation()
                        .create().toJson(new UploadParams<Harmless>(harmless));
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), postInfoStr);
        KLog.e(postInfoStr);
        addSubscribe(model.submitHarmless(body)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(disposable -> showDialog("正在上传无害化处理数据..."))
                .subscribe((Consumer<CattleResponse<List<Harmless>>>) response -> {
                    KLog.e(response.getCode());
                    dismissDialog();
                    if (response.getCode() == 0) {
                        DbUtil.getInstance().deleteById(Harmless.class, parentId);
                        DbUtil.getInstance().setDbIDUCallBack(new DbIDUCallBack() {
                            @Override
                            public void onNotification(boolean result) {
                                if (result) {
                                    backInventory();
                                }
                            }
                        }).deleteAsyncBatch(HarmlessDetail.class, harmlessDetails);

                    } else {
                        ToastUtils.showShort("上传失败");
                    }
                }, (Consumer<ResponseThrowable>) throwable -> {
                    dismissDialog();
                    ToastUtils.showShort(throwable.message);
                })
        );

    }

}

