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

import android.app.Application;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

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.EntryRegistrationEntity;
import com.phlx.wool.entity.Label;
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.util.BaseImageUtils;
import com.phlx.wool.util.StringUtil;

import java.io.File;
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.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
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 SlaughterEntryVM extends BackBarVM<Repository> {

    public EntryRegistrationEntity entity;
    private ArrayList<Label> labels;

    public Drawable drawableImg;
    //照片路径
    private String quarantineImgUrl;
    private File quarantineFile;

    private Disposable inventoryBus;

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

    private List<EntryRegistrationEntity> uploadData;


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

    //初始化ToolBar
    public void initToolbar() {
        setBackTitleText("屠宰进场");
        setSettingVisibleObservable(View.GONE);
        setBackRightTextVisible(View.VISIBLE);
        setBackRightText("保存");

        if (entity == null) {
            initEntity();
        }

        //养殖单位
        entity.setPastureUnitName(SPUtils.getInstance().getString(Configs.SP_UNIT_NAME, ""));
        entity.setPastureUnitId(SPUtils.getInstance().getString(Configs.SP_UNIT_CODE, ""));
//        entity.setPastureUnitPhone(SPUtils.getInstance().getString(Configs.SP_UNIT_PHONE, ""));
//        entity.setRevision(SPUtils.getInstance().getString(Configs.SP_UNIT_REVISION, ""));

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

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

    public void initEntity() {

        entity = new EntryRegistrationEntity();
        long batchNo = IdUtil.createSnowflake(3, 1).nextId();
        entity.setId(batchNo);
        entity.setCreateBy(SPUtils.getInstance().getString("name"));

        dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        Date _date = new Date();
        entity.setSerialNo(dateFormat.format(_date) + "-" + SPUtils.getInstance().getString(Configs.SP_ID));
        dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        entity.setEntryNum(String.valueOf(labels.size()));

        quarantineImgUrl = Environment.getExternalStorageDirectory().getAbsolutePath() +
                "/tracing/picture/"
                + "slaughterCiq" + batchNo + ".jpg";
        quarantineFile = new File(quarantineImgUrl);

        //ImageView的占位图片，可以解决RecyclerView中图片错误问题
        drawableImg = ContextCompat.getDrawable(getApplication(), R.drawable.no_image);

        List<String> epcList = new ArrayList<>();
        for (Label label : labels) {
            epcList.add(label.getEpc());
        }
        entity.setList(epcList);

    }

    public String getQuarantineImgUrl() {
        return quarantineImgUrl;
    }

    //进场日期
    public BindingCommand onEntryDateClick = new BindingCommand(() -> entryDay.call());

    public void setEntryDate(Date date) {
        dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        entity.setEntryDate(dateFormat.format(date));
        entity.notifyChange();
    }


    public BindingCommand quarantinePhotoOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            quarantinePhotoOnClick.call();
        }
    });

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

        if (StringUtils.isEmpty(entity.getEntryDate())) {
            ToastUtils.showShort("请选择收购日期");
            return;
        }
//        if (StringUtils.isEmpty(entity.getRevision())) {
//            ToastUtils.showShort("请选择所属苏木");
//            return;
//        }
        if (StringUtils.isEmpty(entity.getEntryNum())) {
            ToastUtils.showShort("请填写进场数量");
            return;
        }
        if (StringUtils.isEmpty(entity.getRecorder())) {
            ToastUtils.showShort("请填写负责人");
            return;
        }
        if (StringUtils.isEmpty(entity.getQuarantineImgPath())) {
            ToastUtils.showShort("请上传检疫合格证图片");
            return;
        }

        uploadData = new ArrayList<>();
        entity.setCreateBy(SPUtils.getInstance().getString(Configs.SP_LOGIN_NAME));
        dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        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) {
                dismissDialog();
                if (result) {
                    if (Configs.isOnLine) {
                        uploadSlaughterEntry();
                    } else {
                        ToastUtils.showShort("屠宰入场保存成功");
                        backMain();
                    }
                } else {
                    ToastUtils.showShort("屠宰入场保存失败");
                }
            }
        }).insertAsyncBatch(EntryRegistrationEntity.class, uploadData);
    }

    private void uploadSlaughterEntry() {

        if (uploadData != null && uploadData.size() > 0) {
            EntryRegistrationEntity _entryRegistrationEntity = uploadData.get(0);
            if (_entryRegistrationEntity.getQuarantineImgPath() != null && !_entryRegistrationEntity.getQuarantineImgPath().equals(""))
                _entryRegistrationEntity.setQuarantineCertificateImg(BaseImageUtils.bitmapToString(_entryRegistrationEntity.getQuarantineImgPath(), getApplication()));
        }

        String postInfoStr =
                new GsonBuilder().serializeNulls()
//                        .excludeFieldsWithoutExposeAnnotation()
                        .create().toJson(new UploadParams<List<EntryRegistrationEntity>>(uploadData));
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), postInfoStr);
        KLog.e(postInfoStr);
        addSubscribe(model.submitSlaughterEntry(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("屠宰进场上传成功");
                                    finish();
                                }
                            }
                        }).insertAsyncBatch(EntryRegistrationEntity.class, uploadData);
                    } else {
                        dismissDialog();
                        ToastUtils.showShort("屠宰进场上传失败");
                    }
                }, (Consumer<ResponseThrowable>) throwable -> {
                    dismissDialog();
                    ToastUtils.showShort(throwable.message);
                })
        );
    }

    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);
    }
}
