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

import android.app.Application;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.google.gson.GsonBuilder;
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.entity.DivisionEntity;
import com.phlx.wool.entity.Marking;
import com.phlx.wool.entity.Variety;
import com.phlx.wool.entity.VillusBuyEntity;
import com.phlx.wool.event.EventMsg;
import com.phlx.wool.event.EventTag;
import com.phlx.wool.params.CattleResponse;
import com.phlx.wool.params.UploadParams;
import com.phlx.wool.ui.base.BackBarVM;
import com.phlx.wool.ui.setting.SettingActivity;
import com.phlx.wool.ui.villus.VillusBuyActivity;
import com.phlx.wool.util.PrintLabel;
import com.phlx.wool.util.StringUtil;
import com.phlx.wool.widget.ItemData;
import com.printer.sdk.PrinterInstance;

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.disposables.Disposable;
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.RxBus;
import me.goldze.mvvmhabit.bus.RxSubscriptions;
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 VillusBuyVM extends BackBarVM<Repository> {

    public VillusBuyEntity entity;
    public List<IKeyAndValue> superiorPertainItemData;
    public List<IKeyAndValue> pertainItemData;
    private List<String> lists;

    private List<VillusBuyEntity> uploadData;

    public SingleLiveEvent<Boolean> buyDay = new SingleLiveEvent<>();
    public SingleLiveEvent<Boolean> changeDivision = new SingleLiveEvent<>();
    public SingleLiveEvent<Boolean> printEvent = new SingleLiveEvent<>();
    private SimpleDateFormat dateFormat;

    private Disposable inventoryBus;

    private ArrayAdapter<String> spinnerAdapter;

    private Long id;


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

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

        if (entity == null) {
            entity = new VillusBuyEntity();
        }
        dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        Date _date = new Date();
        entity.setBuyBatch(dateFormat.format(_date) + "-" + SPUtils.getInstance().getString(Configs.SP_ID));
        dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        superiorPertainItemData = new ArrayList<>();
        List<DivisionEntity> superiorDivisionEntities = model.getPertain("152900");
        if (superiorDivisionEntities != null && superiorDivisionEntities.size() > 0) {
            for (DivisionEntity divisionEntity : superiorDivisionEntities) {
                superiorPertainItemData.add(new ItemData(divisionEntity.getName(), divisionEntity.getCode()));
            }
        }
        pertainItemData = new ArrayList<>();
        lists = new ArrayList<>();
        if (superiorDivisionEntities != null && superiorDivisionEntities.size() > 0) {
            List<DivisionEntity> divisionEntities = model.getPertain(superiorDivisionEntities.get(0).getCode());
            if (divisionEntities != null && divisionEntities.size() > 0) {
                for (DivisionEntity divisionEntity : divisionEntities) {
                    pertainItemData.add(new ItemData(divisionEntity.getName(), divisionEntity.getCode()));
                    lists.add(divisionEntity.getName());
                }
            }
        }
    }


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

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

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

    public BindingCommand<IKeyAndValue> onSuperiorPertainSelectorCommand = new BindingCommand<>(new BindingConsumer<IKeyAndValue>() {
        @Override
        public void call(IKeyAndValue iKeyAndValue) {
            pertainItemData = new ArrayList<>();
            List<DivisionEntity> divisionEntities = model.getPertain(iKeyAndValue.getValue());
            pertainItemData.clear();
            lists.clear();
            if (divisionEntities != null && divisionEntities.size() > 0) {
                for (DivisionEntity divisionEntity : divisionEntities) {
                    pertainItemData.add(new ItemData(divisionEntity.getName(), divisionEntity.getCode()));
                    lists.add(divisionEntity.getName());
                }
            }
            changeDivision.call();
        }
    });

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

    public ArrayAdapter getAdapter(VillusBuyActivity 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.getBuyDate())) {
            ToastUtils.showShort("请选择收购日期");
            return;
        }
        if (StringUtils.isEmpty(entity.getRevision())) {
            ToastUtils.showShort("请选择所属苏木");
            return;
        }
        if (StringUtils.isEmpty(entity.getBuyFactory())) {
            ToastUtils.showShort("请填写收购厂家");
            return;
        }
        if (StringUtils.isEmpty(entity.getBuyWeight())) {
            ToastUtils.showShort("请填写收购重量");
            return;
        }
        if (StringUtils.isEmpty(entity.getPersonInCharge())) {
            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);
        entity.setProductId(StringUtil.to32String(IdUtil.createSnowflake(3, 1).nextId()));
        entity.setPrintCount(0);
        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) {
                        uploadVillusBuy();
                    } else {
                        ToastUtils.showShort("绒毛购买保存成功");
                        backMain();
                    }
                }
            }
        }).insertAsyncBatch(VillusBuyEntity.class, uploadData);
    }

    private void uploadVillusBuy() {

        String postInfoStr =
                new GsonBuilder().serializeNulls()
//                        .excludeFieldsWithoutExposeAnnotation()
                        .create().toJson(new UploadParams<List<VillusBuyEntity>>(uploadData));
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), postInfoStr);
        KLog.e(postInfoStr);
        addSubscribe(model.submitVillusBuy(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();
                                    ToastUtils.showShort("绒毛购买上传成功");
                                    printEvent.call();
                                }
                            }
                        }).insertAsyncBatch(VillusBuyEntity.class, uploadData);
                    } else {
                        dismissDialog();
                        ToastUtils.showShort("绒毛购买上传失败");
                    }
                }, (Consumer<ResponseThrowable>) throwable -> {
                    dismissDialog();
                    ToastUtils.showShort(throwable.message);
                })
        );
    }

    //写打印内容
    public void printVillusBuy() {

        if (!Configs.isConnected) {
            Bundle bun = new Bundle();
            bun.putInt("settingStatus", 1);
            startActivity(SettingActivity.class, bun);
        } else {
            List<VillusBuyEntity> villusBuyEntities = model.getVillusBuy();
            if (Configs.myPrinter != null && villusBuyEntities != null) {
                CharSequence[] text = new CharSequence[1];
                text[0] = entity.getBuyBatch();
                PrintLabel.printVillusBuy(model, Configs.myPrinter, villusBuyEntities, text);
                backMain();
            }
        }
    }

    public void backMain() {
        finish();
    }

    @Override
    public void registerRxBus() {
        super.registerRxBus();
        inventoryBus =
                RxBus.getDefault().toObservable(EventMsg.class).subscribe(eventType -> {
                    if (eventType.getAction().equals(EventTag.EVENT_INVENTORY_DATA)) {


                    }
                });
        RxSubscriptions.add(inventoryBus);
    }

    @Override
    public void removeRxBus() {
        super.removeRxBus();
        RxSubscriptions.remove(inventoryBus);
    }
}
