package com.example.chemical.ui.plan.add;

import android.app.Activity;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.example.chemical.ui.plan.room.bean.input_add.HxpChemical;
import com.example.chemical.weidith.BelongingPersonDialog;
import com.example.chemical.weidith.BluetoothWeighDialog;
import com.example.chemical.weidith.SelectChemicalDialog;
import com.example.chemical.weidith.SelectTopicDialog;
import com.example.chemical.weidith.prin_label_dialog.PrintLabelDialog;
import com.rc.httpcore.bean.HxpChemicalVo;
import com.rc.httpcore.client.ApiRepository;
import com.rc.httpcore.client.HttpTool;
import com.rc.httpcore.exception.NetException;

import java.util.List;

import io.reactivex.functions.Consumer;
import okhttp3.Response;

/**
 * activity帮助类 不得占用上下文
 */
public class AddActivityHelp {
    private AddActivity addActivity;

    public AddActivityHelp(AddActivity addActivity) {
        super();
        this.addActivity = addActivity;
    }

    /**
     * 课题组查询
     *
     * @param userId 归属人ID
     */
    public void topicSearch(String userId) {
        addActivity.showLoading("查询中...", false);
        addActivity.addDisposable(ApiRepository.INSTANCE.getTopicList(userId).subscribe(topicDataBeans -> {
            addActivity.dismissLoading();
            new SelectTopicDialog(addActivity, topicDataBeans, topicDataBean -> {
                addActivity.topicDataBean = topicDataBean;
                String topicName = topicDataBean.getTopicName();
                addActivity.binding.topicET.setText(TextUtils.isEmpty(topicName) ? "" : topicName);
                addActivity.binding.topicET.setTag(topicDataBean.getTopicId());
            }).show();
        }, throwable -> {
            LogUtils.e(Log.getStackTraceString(throwable));
            addActivity.dismissLoading();
            addActivity.showNetError(throwable);
        }));
    }

    /**
     * 归属人搜索
     */
    public void belongSearch(Editable belongETText) {
        addActivity.showLoading("查询中...", false);
        addActivity.addDisposable(ApiRepository.INSTANCE.getSelects(belongETText.toString()).subscribe(belongingPersonBeans -> {
            addActivity.dismissLoading();
            new BelongingPersonDialog(addActivity, belongingPersonBeans, data -> {
                addActivity.belongingPerson = data;
                String userName = data.getUserName();
                userName = TextUtils.isEmpty(userName) ? "" : userName;
                String account = data.getAccount();
                account = TextUtils.isEmpty(account) ? "" : account;
                addActivity.binding.belongET.setText(userName + "-" + account);
                addActivity.binding.belongET.setTag(data.getUserId());
            }).show();
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                LogUtils.e(Log.getStackTraceString(throwable));
                addActivity.dismissLoading();
                addActivity.showNetError(throwable);
            }
        }));
    }

    /**
     * 化学品搜索
     */
    public void hxpSearch(Editable chemicalSearchETText) {
        addActivity.showLoading("查询中...", false);
        ThreadUtils.executeByCached(new ThreadUtils.SimpleTask<List<HxpChemicalVo>>() {
            @Override
            public List<HxpChemicalVo> doInBackground() throws Throwable {
                Response response = HttpTool.searchchemical(chemicalSearchETText.toString(), "");
                if (response.isSuccessful()) {
                    String json = response.body().string();
                    HxpChemical hxpChemical = GsonUtils.fromJson(json, HxpChemical.class);
                    if (hxpChemical.getCode() == 200) {
                        List<HxpChemicalVo> hxpChemicalVoList = hxpChemical.getData();
                        if (null != hxpChemicalVoList && !hxpChemicalVoList.isEmpty()) {
                            return hxpChemicalVoList;
                        }
                    } else {
                        throw new NetException("" + hxpChemical.getCode(), hxpChemical.getMessage());
                    }
                } else {
                    throw new NetException("" + response.code(), response.message());
                }
                return null;
            }

            @Override
            public void onSuccess(List<HxpChemicalVo> hxpChemicalVoList) {
                addActivity.dismissLoading();
                new SelectChemicalDialog(addActivity, hxpChemicalVoList, new SelectChemicalDialog.SelectedListener() {
                    @Override
                    public void selected(HxpChemicalVo hxpChemicalVo) {
                        chemicalSearchResult(hxpChemicalVo);
                    }
                }).show();
            }

            @Override
            public void onFail(Throwable t) {
                super.onFail(t);
                LogUtils.e(Log.getStackTraceString(t));
                addActivity.showNetError(t);
                addActivity.dismissLoading();
            }
        });
    }

    /**
     * 化学品名查询结果
     */
    private void chemicalSearchResult(HxpChemicalVo hxpChemicalVo) {
        // 化学品名
        String chemicalName = hxpChemicalVo.getChemicalName();
        addActivity.binding.chemicalSearchET.setText(TextUtils.isEmpty(chemicalName) ? "" : chemicalName);
        addActivity.hxpChemicalVo.setChemicalName(chemicalName);
        // CAS
        String casNum = hxpChemicalVo.getCasNum();
        addActivity.binding.casET.setText(TextUtils.isEmpty(casNum) ? "" : casNum);
        addActivity.hxpChemicalVo.setCasNum(casNum);
        // 密度
        double chemicalDensity = hxpChemicalVo.getChemicalDensity();
        addActivity.binding.chemicalDensityET.setText("" + chemicalDensity);
        addActivity.hxpChemicalVo.setChemicalDensity(chemicalDensity);
        // 规格值
        double specNum = hxpChemicalVo.getSpecNum();
        addActivity.binding.chemicalSpecET.setText("" + specNum);
        addActivity.hxpChemicalVo.setSpecNum(specNum);
        // 规格单位 ml/g
        String specUnit = hxpChemicalVo.getSpecUnit();
        if ("ml".equals(specUnit)) {
            addActivity.binding.chemicalSpecRG.check(addActivity.binding.chemicalSpecMlRB.getId());
            addActivity.binding.netWtTV.setText("ml");
        } else {
            addActivity.binding.chemicalSpecRG.check(addActivity.binding.chemicalSpecGRB.getId());
            addActivity.binding.netWtTV.setText("g");
        }
        addActivity.hxpChemicalVo.setSpecUnit(specUnit);
        // 化学品类别
        String chemicalCategory = hxpChemicalVo.getChemicalCategory();
        String chemicalCategoryName = hxpChemicalVo.getChemicalCategoryName();
        addActivity.binding.chemicalCategoryTV.setText(TextUtils.isEmpty(chemicalCategoryName) ? "" : chemicalCategoryName);
        addActivity.binding.chemicalCategoryTV.setTag(chemicalCategory);
        addActivity.hxpChemicalVo.setChemicalCategory(chemicalCategory);

        // 管控
        if (hxpChemicalVo.getChemicalLevel() == 1) {
            addActivity.binding.cmRG.check(addActivity.binding.controlledRB.getId());
        }
        // 非管控
        else {
            addActivity.binding.cmRG.check(addActivity.binding.uncontrolledRB.getId());
        }
        addActivity.hxpChemicalVo.setChemicalLevel(hxpChemicalVo.getChemicalLevel());
        // 化学品id
        addActivity.hxpChemicalVo.setChemicalId(hxpChemicalVo.getChemicalId());
    }

    // 存储
    public void weighSave() {
        // 化学品名
        Editable chemicalSearchETText = addActivity.binding.chemicalSearchET.getText();
        if (null == chemicalSearchETText || TextUtils.isEmpty(chemicalSearchETText)) {
            addActivity.binding.chemicalSearchET.setError("请输入化学品名称");
            return;
        }
        addActivity.hxpChemicalVo.setChemicalName(chemicalSearchETText.toString());

        // CAS
        Editable casETText = addActivity.binding.casET.getText();
        if (null == casETText || TextUtils.isEmpty(casETText)) {
            addActivity.binding.casET.setError("请输入CAS码");
            return;
        }
        addActivity.hxpChemicalVo.setCasNum(casETText.toString());

        // 类别
        String categoryTVTag = (String) addActivity.binding.chemicalCategoryTV.getTag();
        if (null == categoryTVTag || TextUtils.isEmpty(categoryTVTag)) {
            addActivity.binding.chemicalCategoryTV.setError("请选择化学品类别");
            return;
        }
        addActivity.hxpChemicalVo.setChemicalCategory(categoryTVTag);

        CharSequence chemicalCategoryTVText = addActivity.binding.chemicalCategoryTV.getText();
        if (null == chemicalCategoryTVText || TextUtils.isEmpty(chemicalCategoryTVText)) {
            addActivity.binding.chemicalCategoryTV.setError("请选择化学品类别");
            return;
        }
        addActivity.hxpChemicalVo.setChemicalCategoryName(chemicalCategoryTVText.toString());

        // 规格
        Editable chemicalSpecETText = addActivity.binding.chemicalSpecET.getText();
        if (null == chemicalSpecETText || TextUtils.isEmpty(chemicalSpecETText)) {
            addActivity.binding.chemicalSpecET.setError("请输入规格");
            return;
        }
        double specNum = -1.0;
        try {
            specNum = Double.parseDouble(chemicalSpecETText.toString());
        } catch (Exception e) {
            addActivity.binding.chemicalSpecET.setError("请检查规格内容正确");
            return;
        }
        if (specNum < 0) {
            addActivity.binding.chemicalSpecET.setError("请检查规格内容正确");
            return;
        }
        addActivity.hxpChemicalVo.setSpecNum(specNum);

        // 规格单位
        if (addActivity.binding.chemicalSpecMlRB.getId() == addActivity.binding.chemicalSpecRG.getCheckedRadioButtonId()) {
            addActivity.hxpChemicalVo.setSpecUnit("ml");
        } else {
            addActivity.hxpChemicalVo.setSpecUnit("g");
        }

        // 密度
        Editable chemicalDensityETText = addActivity.binding.chemicalDensityET.getText();
        if (null == chemicalDensityETText || TextUtils.isEmpty(chemicalDensityETText)) {
            addActivity.binding.chemicalDensityET.setError("请输入密度");
            return;
        }
        double density = -1.0;
        try {
            density = Double.parseDouble(chemicalDensityETText.toString());
        } catch (Exception e) {
            addActivity.binding.chemicalDensityET.setError("请检查密度内容正确");
            return;
        }
        if (density <= 0) {
            addActivity.binding.chemicalDensityET.setError("请检查密度内容正确");
            return;
        }
        addActivity.hxpChemicalVo.setChemicalDensity(density);

        // 净含量
        Editable netWtETText = addActivity.binding.netWtET.getText();
        if (null == netWtETText || TextUtils.isEmpty(netWtETText)) {
            addActivity.binding.netWtET.setError("请输入净含量");
            return;
        }
        double netWt = -1.0;
        try {
            netWt = Double.parseDouble(netWtETText.toString());
        } catch (Exception e) {
            addActivity.binding.netWtET.setError("请检查净含量内容正确");
            return;
        }
        if (netWt <= 0) {
            addActivity.binding.netWtET.setError("请检查净含量内容正确");
            return;
        }
        addActivity.hxpChemicalVo.setNetWt(netWt);

        // 数量
        Editable sizeETText = addActivity.binding.sizeET.getText();
        if (null == sizeETText || TextUtils.isEmpty(sizeETText)) {
            addActivity.binding.sizeET.setError("请输入数量");
            return;
        }
        int size = -1;
        try {
            size = Integer.parseInt(sizeETText.toString());
        } catch (Exception e) {
            addActivity.binding.sizeET.setError("请检查数量内容正确");
            return;
        }
        if (size <= 0) {
            addActivity.binding.sizeET.setError("请检查数量内容正确");
            return;
        }
        addActivity.inventoryItemBean.setSize(size);

        // 归属人
        String userId = (String) addActivity.binding.belongET.getTag();
        if (addActivity.belongingPerson == null || addActivity.belongingPerson.getUserId().isEmpty() || null == userId || TextUtils.isEmpty(userId) || !addActivity.belongingPerson.getUserId().equals(userId)) {
            addActivity.binding.belongET.setError("请先搜索并选择归属人");
            return;
        }

        /*-- 非必填 --*/
        // 纯度
        Editable purityETText = addActivity.binding.purityET.getText();
        if (null != purityETText && !TextUtils.isEmpty(purityETText)) {
            addActivity.hxpChemicalVo.setChemicalPurity(purityETText.toString());
        }
        // 厂家
        Editable factoryETText = addActivity.binding.factoryET.getText();
        if (null != factoryETText && !TextUtils.isEmpty(factoryETText)) {
            addActivity.hxpChemicalVo.setFactory(factoryETText.toString());
        }
        // 课题组
        Editable topicETText = addActivity.binding.topicET.getText();
        if (null != topicETText && !TextUtils.isEmpty(topicETText)) {
            // SQL课题组
            addActivity.inventoryItemBean.setTopicDataBean(addActivity.topicDataBean);
        }

        // SQL化学品信息
        addActivity.inventoryItemBean.setHxpChemicalVo(addActivity.hxpChemicalVo);
        // SQL归属人信息
        addActivity.inventoryItemBean.setBelongingPersonBean(addActivity.belongingPerson);

        // 化学品基础信息配置
        addActivity.addDisposable(ApiRepository.INSTANCE.getControlConfigs(addActivity.hxpChemicalVo.getChemicalLevel()).subscribe(hxpControlConfig -> {
            addActivity.hxpControlConfig = hxpControlConfig;
            // 化学品新增确定
            addActivity.addDisposable(ApiRepository.INSTANCE.certitude(addActivity.hxpChemicalVo).subscribe(hxpChemicalVo -> {
                addActivity.hxpChemicalVo.setChemicalId(hxpChemicalVo.getChemicalId());
                CharSequence charSequence = addActivity.binding.cabinetLayerSelectTV.getText();
                new PrintLabelDialog(addActivity, addActivity.inventoryItemBean,
                        TextUtils.isEmpty(charSequence) ? "" : charSequence.toString(),
                        addActivity.hxpControlConfig.isQrCodePrint(),
                        new PrintLabelDialog.PrintLabelCallBack() {
                            @Override
                            public void confirm() {
                                BluetoothWeighDialog bluetoothWeighDialog = new BluetoothWeighDialog(addActivity, addActivity.hxpChemicalVo);
                                bluetoothWeighDialog.setOnDismissListener(dialog -> {
                                    addActivity.hxpInventoryDAO.insert(addActivity.inventoryItemBean);
                                    addActivity.setResult(Activity.RESULT_OK);
                                    addActivity.finish();
                                });
                                bluetoothWeighDialog.show();
                            }

                            @Override
                            public void close() {
                                ToastUtils.showLong("取消存储");
                            }
                        }
                ).show();
            }, throwable -> {
                LogUtils.e(Log.getStackTraceString(throwable));
                addActivity.showNetError(throwable);
            }));
        }, throwable -> {
            LogUtils.e(Log.getStackTraceString(throwable));
            addActivity.showNetError(throwable);
        }));
    }
}
