package xn.hxp.ui.plan.unlock;

import android.content.Intent;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.kongzue.dialogx.dialogs.PopTip;
import com.rc.httpcore.bean.BelongingPersonBean;
import com.rc.httpcore.bean.HxpChemicalVo;
import com.rc.httpcore.bean.TopicDataBean;
import com.rc.httpcore.bean.UserValidationBean;
import com.rc.httpcore.client.ApiRepository;
import com.rc.httpcore.client.HttpTool;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import io.reactivex.rxjava3.disposables.Disposable;
import kotlin.Triple;
import okhttp3.Response;
import xn.hxp.app.ChemicalApp;
import xn.hxp.ui.plan.PlanAddData;
import xn.hxp.ui.plan.room.RoomTool;
import xn.hxp.ui.plan.room.bean.input_add.InventoryItemBean;
import xn.hxp.ui.plan.room.bean.locker.HxpCabinetAdminVo;
import xn.hxp.ui.plan.room.bean.locker.HxpCabinetDoorVo;
import xn.hxp.ui.plan.room.bean.locker.HxpCabinetLockVo;
import xn.hxp.ui.plan.room.bean.locker.HxpCabinetVo;
import xn.hxp.ui.plan.room.bean.locker.HxpLabDirector;
import xn.hxp.ui.plan.room.bean.locker.HxpLabSafe;
import xn.hxp.ui.plan.room.dao.HxpCabinetDAO;
import xn.hxp.ui.plan.room.dao.HxpDoorDAO;
import xn.hxp.ui.plan.room.dao.HxpInventoryDAO;
import xn.hxp.ui.plan.save_list.SaveListActivity;

public class UnlockActivityHelp {
    private UnlockActivity activity;
    Map<String, Object> map = new HashMap<>();
    // 柜子集合
    List<HxpCabinetVo> cabinetList;
    // 柜门集合
    List<HxpCabinetDoorVo> doorList;
    // 智能锁集合
    List<HxpCabinetLockVo> unlockList = new ArrayList<>();

    private UserValidationBean userValidation1, userValidation2;
    private Disposable unlockDisposable, unlockStatusDisposable;

    /**
     * 当前正在操作的锁
     */
    private HxpCabinetLockVo nowLockVo;

    public void onDestroy() {
        if (null != unlockStatusCDTimer) {
            unlockStatusCDTimer.cancel();
        }
    }

    public UnlockActivityHelp(UnlockActivity activity, PlanAddData planAddData) {
        this.activity = activity;
        this.cabinetList = planAddData.getCabinetList();
        this.doorList = planAddData.getDoorList();
        // 需要开锁的智能锁
        for (int i = 0; i < doorList.size(); i++) {
            HxpCabinetDoorVo doorVo = doorList.get(i);
            unlockList.add(doorVo.getCabinetLockVoList().get(0));
        }
        init();
    }

    private void init() {
        if (!unlockList.isEmpty()) {
            ThreadUtils.executeByCached(new ThreadUtils.SimpleTask<Triple<String, String, String>>() {
                @Override
                public Triple<String, String, String> doInBackground() throws Throwable {
                    // 公共柜门管理员
                    String adminInfo = "", directorInfo = "", safeInfo = "";
                    List<HxpCabinetAdminVo> cabinetAdminVoList = getCommonAdminUserIds(doorList);
                    if (null != cabinetAdminVoList && !cabinetAdminVoList.isEmpty()) {
                        HxpCabinetAdminVo admin = cabinetAdminVoList.get(0);
                        adminInfo = admin.getUserName() + " " + admin.getPhone();
                        if (cabinetAdminVoList.size() > 1) {
                            StringBuilder sb = new StringBuilder();
                            for (int i = 0; i < cabinetAdminVoList.size(); i++) {
                                HxpCabinetAdminVo adminVo = cabinetAdminVoList.get(i);
                                sb.append(adminVo.getUserName());
                                sb.append(" ");
                                sb.append(adminVo.getPhone());
                                sb.append("\n");
                            }
                            sb.delete(sb.length() - 1, sb.length());
                            adminInfo = sb.toString();
                        }
                    }
                    // 实验室负责人
                    List<HxpLabDirector> hxpLabDirectorList = RoomTool.getInstance().hxpLabDirectorDAO().getAll();
                    if (null != hxpLabDirectorList && !hxpLabDirectorList.isEmpty()) {
                        HxpLabDirector labDirector = hxpLabDirectorList.get(0);
                        directorInfo = labDirector.getUserName() + " " + labDirector.getMobile();
                        if (hxpLabDirectorList.size() > 1) {
                            StringBuilder sb = new StringBuilder();
                            for (int i = 0; i < hxpLabDirectorList.size(); i++) {
                                HxpLabDirector director = hxpLabDirectorList.get(i);
                                sb.append(director.getUserName());
                                sb.append(" ");
                                sb.append(director.getMobile());
                                sb.append("\n");
                            }
                            sb.delete(sb.length() - 1, sb.length());
                            directorInfo = sb.toString();
                        }
                    }
                    // 实验室安全员
                    List<HxpLabSafe> labSafeList = RoomTool.getInstance().hxpLabSafeDAO().getAll();
                    if (null != labSafeList && !labSafeList.isEmpty()) {
                        HxpLabSafe safe = labSafeList.get(0);
                        safeInfo = safe.getUserName() + " " + safe.getMobile();
                        if (labSafeList.size() > 1) {
                            StringBuilder sb = new StringBuilder();
                            for (int i = 0; i < labSafeList.size(); i++) {
                                HxpLabSafe labSafe = labSafeList.get(i);
                                sb.append(labSafe.getUserName());
                                sb.append(" ");
                                sb.append(labSafe.getMobile());
                                sb.append("\n");
                            }
                            sb.delete(sb.length() - 1, sb.length());
                            safeInfo = sb.toString();
                        }
                    }

                    return new Triple<>(adminInfo, directorInfo, safeInfo);
                }

                @Override
                public void onSuccess(Triple<String, String, String> result) {
                    String adminInfo = result.getFirst();
                    String directorInfo = result.getSecond();
                    String safeInfo = result.getThird();
                    activity.binding.adminTV.setText(TextUtils.isEmpty(adminInfo) ? "" : adminInfo);
                    activity.binding.directorTV.setText(TextUtils.isEmpty(directorInfo) ? "" : directorInfo);
                    activity.binding.safetyTV.setText(TextUtils.isEmpty(safeInfo) ? "" : safeInfo);
                }
            });
        }

        activity.binding.cabinetTV.setText(cabinetList.size() + "个");
        activity.binding.doorTV.setText(doorList.size() + "个");
        activity.unlockAdapter = new UnlockAdapter(activity, cabinetList, doorList);
        activity.binding.unlockGV.setAdapter(activity.unlockAdapter);
    }

    /**
     * 批量重试
     */
    public void reTryUnlock() {
        boolean hasFailed = false;
        for (int i = 0; i < unlockList.size(); i++) {
            HxpCabinetLockVo hxpCabinetLockVo = unlockList.get(i);
            if (2 == hxpCabinetLockVo.getUnlockType()) {
                hxpCabinetLockVo.setUnlockType(0);
                hasFailed = true;
            }
        }
        if (!hasFailed) {
            PopTip.show("没有开锁失败的柜门!");
            return;
        }
        activity.binding.retryBT.setVisibility(View.GONE);
        activity.binding.unlockLL.setVisibility(View.VISIBLE);
        unlockTask();
    }

    /**
     * 批量开锁
     *
     * @param userValidation1 验证通过的人1
     * @param userValidation2 验证通过的人2
     */
    public void unlock(UserValidationBean userValidation1, UserValidationBean userValidation2) {
        this.userValidation1 = userValidation1;
        this.userValidation2 = userValidation2;
        unlockTask();
    }

    private CountDownTimer unlockStatusCDTimer;

    /**
     * 批量开锁
     */
    private void unlockTask() {
        if (null != unlockStatusCDTimer) {
            unlockStatusCDTimer.cancel();
            unlockStatusCDTimer = null;
        }
        if (null != unlockDisposable) {
            activity.delDisposable(unlockDisposable);
        }
        nowLockVo = getNextNotUnlocked();
        if (null == nowLockVo) {
            activity.binding.retryBT.setVisibility(View.VISIBLE);
            activity.binding.saveBT.setVisibility(View.VISIBLE);
            activity.binding.unlockLL.setVisibility(View.GONE);
            activity.unlockAdapter.setUnlockEnd(true);
            unlockEnd();
            activity.unlockAdapter.notifyDataSetChanged();
            PopTip.show("批量开锁结束!");
            return;
        } else {
            activity.unlockAdapter.notifyDataSetChanged();
            activity.unlockAdapter.setUnlockEnd(false);
        }

        map.clear();
        map.put("subId", ChemicalApp.subjectId);
        map.put("subName", ChemicalApp.subjectName);

        HxpCabinetVo hxpCabinetVo = findCabinetByDoorId(nowLockVo.getDoorId());
        if (null != hxpCabinetVo) {
            map.put("cabinetId", hxpCabinetVo.getCabinetId());
            map.put("cabinetName", hxpCabinetVo.getCabinetName());
        }

        HxpCabinetDoorVo hxpDoorVo = findDoorByDoorId(nowLockVo.getDoorId());
        if (null != hxpDoorVo) {
            map.put("doorId", hxpDoorVo.getDoorId());
            map.put("doorName", hxpDoorVo.getDoorName());
        }
        List<String> lockNumList = new ArrayList<>();
        lockNumList.add(nowLockVo.getLockNum());
        map.put("lockNumList", lockNumList);
        map.put("operationType", 3);
        if (ChemicalApp.subRoom != null) {
            map.put("subRoom", ChemicalApp.subRoom);
        }
        map.put("type", true);
        if (userValidation1 != null) {
            map.put("oneUserId", userValidation1.getUserId());
            map.put("oneUserName", userValidation1.getUserName());
        }
        if (null != userValidation2) {
            map.put("twoUserId", userValidation2.getUserId());
            map.put("twoUserName", userValidation2.getUserName());
        }

        unlockDisposable = ApiRepository.INSTANCE.lockOperate(map).subscribe(aBoolean -> {
            if (aBoolean) {
                nowLockVo.setUnlockType(3);
                activity.unlockAdapter.notifyDataSetChanged();

                unlockStatusCDTimer = new CountDownTimer(30 * 1000, 3000) {
                    @Override
                    public void onTick(long millisUntilFinished) {
                        if (null != unlockStatusDisposable) {
                            activity.delDisposable(unlockStatusDisposable);
                        }
                        unlockStatusDisposable = ApiRepository.INSTANCE.getLocks(ChemicalApp.subjectId, nowLockVo.getLockNum()).subscribe(aBoolean -> {
                            if (aBoolean) {
                                nowLockVo.setUnlockType(1);
                                unlockTask();
                            }
                        }, throwable -> LogUtils.e(Log.getStackTraceString(throwable)));
                        activity.addDisposable(unlockStatusDisposable);
                    }

                    @Override
                    public void onFinish() {
                        nowLockVo.setUnlockType(2);
                        unlockTask();
                    }
                };
                unlockStatusCDTimer.start();
            } else {
                nowLockVo.setUnlockType(2);
                unlockTask();
            }
        }, throwable -> LogUtils.e(Log.getStackTraceString(throwable)));
        activity.addDisposable(unlockDisposable);
    }


    /**
     * 单独开锁
     */
    public void unlock(HxpCabinetLockVo nowLockVo) {
        activity.showLoading("开锁中...");
        map.clear();
        map.put("subId", ChemicalApp.subjectId);
        map.put("subName", ChemicalApp.subjectName);

        HxpCabinetVo hxpCabinetVo = findCabinetByDoorId(nowLockVo.getDoorId());
        if (null != hxpCabinetVo) {
            map.put("cabinetId", hxpCabinetVo.getCabinetId());
            map.put("cabinetName", hxpCabinetVo.getCabinetName());
        }

        HxpCabinetDoorVo hxpDoorVo = findDoorByDoorId(nowLockVo.getDoorId());
        if (null != hxpDoorVo) {
            map.put("doorId", hxpDoorVo.getDoorId());
            map.put("doorName", hxpDoorVo.getDoorName());
        }
        List<String> lockNumList = new ArrayList<>();
        lockNumList.add(nowLockVo.getLockNum());
        map.put("lockNumList", lockNumList);
        map.put("operationType", 3);
        if (ChemicalApp.subRoom != null) {
            map.put("subRoom", ChemicalApp.subRoom);
        }
        map.put("type", true);
        if (userValidation1 != null) {
            map.put("oneUserId", userValidation1.getUserId());
            map.put("oneUserName", userValidation1.getUserName());
        }
        if (null != userValidation2) {
            map.put("twoUserId", userValidation2.getUserId());
            map.put("twoUserName", userValidation2.getUserName());
        }
        LogUtils.json("手动开锁", map);
        unlockDisposable = ApiRepository.INSTANCE.lockOperate(map).subscribe(aBoolean -> {
            LogUtils.d("手动开锁", nowLockVo.getLockNum(), nowLockVo.getLockName(), aBoolean);
            if (aBoolean) {
                nowLockVo.setUnlockType(3);
                activity.unlockAdapter.notifyDataSetChanged();

                unlockStatusCDTimer = new CountDownTimer(30 * 1000, 3000) {
                    @Override
                    public void onTick(long millisUntilFinished) {
                        if (null != unlockStatusDisposable) {
                            activity.delDisposable(unlockStatusDisposable);
                        }
                        unlockStatusDisposable = ApiRepository.INSTANCE.getLocks(ChemicalApp.subjectId, nowLockVo.getLockNum()).subscribe(aBoolean -> {
                            LogUtils.d("手动开锁查询状态", nowLockVo.getLockNum(), nowLockVo.getLockName(), aBoolean);
                            if (aBoolean) {
                                unlockStatusCDTimer.cancel();
                                PopTip.show("开门成功!");
                                nowLockVo.setUnlockType(1);
                                activity.unlockAdapter.notifyDataSetChanged();
                                activity.dismissLoading();
                            }
                        }, throwable -> LogUtils.e(Log.getStackTraceString(throwable)));
                        activity.addDisposable(unlockStatusDisposable);
                    }

                    @Override
                    public void onFinish() {
                        LogUtils.d("手动开锁失败", nowLockVo.getLockNum(), nowLockVo.getLockName());
                        nowLockVo.setUnlockType(2);
                        unlockEnd();
                        activity.unlockAdapter.notifyDataSetChanged();
                        activity.dismissLoading();
                        HxpCabinetDoorVo doorVo = findDoorByLockId(nowLockVo.getLockId());
                        if (null != doorVo) {
                            PopTip.show(doorVo.getDoorName() + "开门失败!");
                        } else {
                            PopTip.show("开门失败!");
                        }
                    }
                };
                unlockStatusCDTimer.start();
            } else {
                nowLockVo.setUnlockType(2);
            }
        }, throwable -> LogUtils.e(Log.getStackTraceString(throwable)));
        activity.addDisposable(unlockDisposable);
    }

    private HxpCabinetDoorVo findDoorByLockId(long lockId) {
        for (int i = 0; i < doorList.size(); i++) {
            HxpCabinetDoorVo doorVo = doorList.get(i);
            List<HxpCabinetLockVo> lockVoList = doorVo.getCabinetLockVoList();
            if (null != lockVoList) {
                for (int j = 0; j < lockVoList.size(); j++) {
                    HxpCabinetLockVo lockVo = lockVoList.get(j);
                    if (lockVo.getLockId() == lockId) {
                        return doorVo;
                    }
                }
            }
        }
        return null;
    }

    /**
     * 获取一个没有执行过开锁操作的锁
     */
    private HxpCabinetLockVo getNextNotUnlocked() {
        for (int i = 0; i < unlockList.size(); i++) {
            HxpCabinetLockVo hxpCabinetLockVo = unlockList.get(i);
            // 获取一个未开过锁的锁
            if (0 == hxpCabinetLockVo.getUnlockType()) {
                return hxpCabinetLockVo;
            }
        }
        return null;
    }

    private HxpCabinetVo findCabinetByDoorId(long doorId) {
        HxpCabinetDoorVo hxpCabinetDoorVo = findDoorByDoorId(doorId);
        if (null != hxpCabinetDoorVo) {
            for (int j = 0; j < cabinetList.size(); j++) {
                HxpCabinetVo cabinetVo = cabinetList.get(j);
                if (hxpCabinetDoorVo.getCabinetId() == cabinetVo.getCabinetId()) {
                    return cabinetVo;
                }
            }
        }
        return null;
    }

    private HxpCabinetDoorVo findDoorByDoorId(long doorId) {
        for (int i = 0; i < doorList.size(); i++) {
            HxpCabinetDoorVo hxpCabinetDoorVo = doorList.get(i);
            if (doorId == hxpCabinetDoorVo.getDoorId()) {
                return hxpCabinetDoorVo;
            }
        }
        return null;
    }

    private void unlockEnd() {
        int successful = 0;
        int failures = 0;
        for (int i = 0; i < unlockList.size(); i++) {
            HxpCabinetLockVo cabinetLockVo = unlockList.get(i);
            int unlockType = cabinetLockVo.getUnlockType();
            if (1 == unlockType) {
                successful++;
            } else {
                failures++;
            }
            if (null != nowLockVo) {
                cabinetLockVo.setUnlockType(nowLockVo.getUnlockType());
            }
        }
        activity.binding.unlockedTV.setText(successful + "个");
        activity.binding.unlockFailedTV.setText(failures + "个");
    }

    /**
     * 找出所有柜门的共同管理员,没有共同管理员则返回Null
     */
    private List<HxpCabinetAdminVo> getCommonAdminUserIds(List<HxpCabinetDoorVo> doorList) {
        try {
            Map<Long, Integer> userIdCount = new HashMap<>();
            int totalDoors = doorList.size();

            // 统计所有 UserId 的出现次数
            for (HxpCabinetDoorVo door : doorList) {
                Set<Long> uniqueIds = new HashSet<>(); // 记录当前 Door 的唯一 UserId，防止重复计数
                for (HxpCabinetAdminVo admin : door.getCabinetAdminVoList()) {
                    uniqueIds.add(admin.getUserId());
                }
                for (Long userId : uniqueIds) {
                    userIdCount.put(userId, userIdCount.containsKey(userId) ? userIdCount.get(userId) + 1 : 1);
                }
            }

            // 过滤出出现在所有 Door 中的 UserId
            Set<Long> commonUserIds = new HashSet<Long>();
            for (Map.Entry<Long, Integer> entry : userIdCount.entrySet()) {
                if (entry.getValue() == totalDoors) {
                    commonUserIds.add(entry.getKey());
                }
            }

            if (commonUserIds.isEmpty()) {
                return null;
            }

            // 仅返回第一个 Door 中符合的 Admin
            List<HxpCabinetAdminVo> commonAdmins = new ArrayList<>();
            for (HxpCabinetAdminVo admin : doorList.get(0).getCabinetAdminVoList()) {
                if (commonUserIds.contains(admin.getUserId())) {
                    commonAdmins.add(admin);
                }
            }
            return commonAdmins;
        } catch (Exception e) {
            LogUtils.e(Log.getStackTraceString(e));
        }
        return null;
    }

    public void save(boolean isAuto) {
        activity.binding.saveBT.setEnabled(false);
        activity.showLoading("入库中...");
        if (isAuto) {
            ThreadUtils.executeByCached(new ThreadUtils.SimpleTask<String>() {
                @Override
                public String doInBackground() throws Throwable {
                    List<HxpChemicalVo> autoChemicalList = activity.planAddData.getAutoChemicalList();
                    List<HxpCabinetVo> cabinetVoList = activity.planAddData.getCabinetList();
                    List<HxpCabinetDoorVo> doorVoList = activity.planAddData.getDoorList();

                    for (int i = 0; i < unlockList.size(); i++) {
                        HxpCabinetLockVo hxpCabinetLockVo = unlockList.get(i);
                        // 开锁失败
                        if (hxpCabinetLockVo.getUnlockType() == 2) {
                            long doorId = hxpCabinetLockVo.getDoorId();
                            for (int j = 0; j < autoChemicalList.size(); j++) {
                                HxpChemicalVo hxpChemicalVo = autoChemicalList.get(j);
                                if (hxpChemicalVo.getDoorId() == doorId) {
                                    autoChemicalList.remove(j);
                                    j--;
                                }
                            }
                        }
                    }
                    LogUtils.d("清单", autoChemicalList.size(), cabinetVoList.size(), doorVoList.size());
                    JSONArray jsonArray = new JSONArray();
                    for (int i = 0; i < autoChemicalList.size(); i++) {
                        String waitId = autoChemicalList.get(i).getWaitId();
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("waitId", waitId);
                        jsonObject.put("oneUserId", userValidation1.getUserId());
                        jsonObject.put("twoUserId", userValidation2.getUserId());
                        jsonArray.put(jsonObject);
                    }
                    if (jsonArray.length() == 0) {
                        return "没有可入库的化学品,请检查柜门是否已开!";
                    }
                    Response response = HttpTool.autoChemicals(jsonArray.toString());
                    if (response.isSuccessful()) {
                        String json = response.body().string();
                        JSONObject jsonObject = new JSONObject(json);
                        int code = jsonObject.getInt("code");
                        if (code == 200) {
                            HxpInventoryDAO hxpInventoryDAO = RoomTool.getInstance().hxpInventoryDAO();
                            // 删除未开锁成功的柜门
                            for (int j = 0; j < unlockList.size(); j++) {
                                HxpCabinetLockVo hxpCabinetLockVo = unlockList.get(j);
                                if (2 == hxpCabinetLockVo.getUnlockType()) {
                                    hxpInventoryDAO.delete(hxpCabinetLockVo.getDoorId());
                                }
                            }
                            return "";
                        } else {
                            return jsonObject.getString("message");
                        }
                    } else {
                        return response.message();
                    }
                }

                @Override
                public void onSuccess(String result) {
                    activity.dismissLoading();
                    if (!TextUtils.isEmpty(result)) {
                        PopTip.show(result);
                        activity.binding.saveBT.setEnabled(true);
                    } else {
                        activity.finish();
                        Intent intent = new Intent(activity, SaveListActivity.class);
                        intent.putExtra("data", GsonUtils.toJson(activity.planAddData));
                        intent.putExtra("userValidation1", GsonUtils.toJson(userValidation1));
                        intent.putExtra("userValidation2", GsonUtils.toJson(userValidation1));
                        activity.startActivity(intent);
                    }
                }
            });

        } else {
            ThreadUtils.executeByCached(new ThreadUtils.SimpleTask<String>() {
                @Override
                public String doInBackground() throws Throwable {
                    HxpInventoryDAO hxpInventoryDAO = RoomTool.getInstance().hxpInventoryDAO();
                    HxpCabinetDAO cabinetDAO = RoomTool.getInstance().hxpCabinetDAO();
                    HxpDoorDAO doorDAO = RoomTool.getInstance().hxpDoorDAO();
                    List<InventoryItemBean> inventoryItemBeanList = hxpInventoryDAO.getAll();
                    // 删除未开锁成功的柜门
                    for (int j = 0; j < unlockList.size(); j++) {
                        HxpCabinetLockVo hxpCabinetLockVo = unlockList.get(j);
                        if (2 == hxpCabinetLockVo.getUnlockType()) {
                            for (int i = 0; i < inventoryItemBeanList.size(); i++) {
                                InventoryItemBean inventoryItemBean = inventoryItemBeanList.get(i);
                                if (hxpCabinetLockVo.getDoorId() == inventoryItemBean.getDoorId()) {
                                    inventoryItemBeanList.remove(i);
                                    i--;
                                }
                            }
                        }
                    }

                    List<String> hxpIds = new ArrayList<>();
                    for (int i = 0; i < inventoryItemBeanList.size(); i++) {
                        InventoryItemBean inventoryItemBean = inventoryItemBeanList.get(i);
                        hxpIds.add(String.valueOf(inventoryItemBean.getHxpChemicalVo().getChemicalId()));
                    }
                    LogUtils.d("清单", inventoryItemBeanList.size(), hxpIds);

                    List<HxpChemicalVo> hxpChemicalVoList = new ArrayList<>();
                    for (int i = 0; i < inventoryItemBeanList.size(); i++) {
                        InventoryItemBean inventoryItemBean = inventoryItemBeanList.get(i);
                        BelongingPersonBean belongingPersonBean = inventoryItemBean.getBelongingPersonBean();
                        TopicDataBean topicDataBean = inventoryItemBean.getTopicDataBean();
                        HxpChemicalVo hxpChemicalVo = inventoryItemBean.getHxpChemicalVo();
                        if (null == belongingPersonBean) {
                            hxpChemicalVo.setBelongId(Long.parseLong(topicDataBean.getTopicId()));
                            hxpChemicalVo.setBelongName(topicDataBean.getTopicName());
                            hxpChemicalVo.setBelongType(1);
                        } else {
                            hxpChemicalVo.setBelongId(Long.parseLong(belongingPersonBean.getUserId()));
                            hxpChemicalVo.setBelongName(belongingPersonBean.getUserName());
                            hxpChemicalVo.setBelongType(2);
                        }
                        hxpChemicalVo.setOneUserId(Long.parseLong(userValidation1.getUserId()));
                        hxpChemicalVo.setOneUserName(userValidation1.getUserName());
                        hxpChemicalVo.setTwoUserId(Long.parseLong(userValidation2.getUserId()));
                        hxpChemicalVo.setTwoUserName(userValidation2.getUserName());
                        hxpChemicalVo.setSubId(Long.parseLong(ChemicalApp.subjectId));

                        hxpChemicalVo.setChemicalNumber(inventoryItemBean.getSize());
                        HxpCabinetVo cabinetVo = cabinetDAO.getById(inventoryItemBean.getCabinetId());
                        hxpChemicalVo.setCabinetId(cabinetVo.getCabinetId());
                        hxpChemicalVo.setCabinetName(cabinetVo.getCabinetName());

                        HxpCabinetDoorVo doorVo = doorDAO.getById(inventoryItemBean.getDoorId());
                        // 后台要求这么干
                        hxpChemicalVo.setDoorId(doorVo.getDoorUniqueId());
                        hxpChemicalVo.setDoorName(doorVo.getDoorName());

                        hxpChemicalVo.setLayers(String.valueOf(inventoryItemBean.getLayer()));
                        hxpChemicalVoList.add(hxpChemicalVo);
                    }
                    if (hxpChemicalVoList.isEmpty()) {
                        return "没有可入库的化学品,请检查柜门是否已开!";
                    }

                    Response response = HttpTool.addChemical(hxpChemicalVoList);
                    if (response.isSuccessful()) {
                        String json = response.body().string();
                        JSONObject jsonObject = new JSONObject(json);
                        int code = jsonObject.getInt("code");
                        if (code == 200) {
                            // 删除未开锁成功的柜门
                            for (int j = 0; j < unlockList.size(); j++) {
                                HxpCabinetLockVo hxpCabinetLockVo = unlockList.get(j);
                                if (2 == hxpCabinetLockVo.getUnlockType()) {
                                    hxpInventoryDAO.delete(hxpCabinetLockVo.getDoorId());
                                }
                            }
                            return "";
                        } else {
                            return jsonObject.getString("message");
                        }
                    } else {
                        return response.message();
                    }
                }

                @Override
                public void onSuccess(String result) {
                    activity.dismissLoading();
                    if (!TextUtils.isEmpty(result)) {
                        PopTip.show(result);
                        activity.binding.saveBT.setEnabled(true);
                    } else {
                        activity.finish();

                        Intent intent = new Intent(activity, SaveListActivity.class);
                        intent.putExtra("data", GsonUtils.toJson(activity.planAddData));
                        intent.putExtra("userValidation1", GsonUtils.toJson(userValidation1));
                        intent.putExtra("userValidation2", GsonUtils.toJson(userValidation1));
                        activity.startActivity(intent);
                    }
                }

                @Override
                public void onFail(Throwable t) {
                    super.onFail(t);
                    activity.dismissLoading();
                    activity.binding.saveBT.setEnabled(true);
                    PopTip.show(t.getMessage());
                }
            });
        }
    }

}
