package xn.hxp.ui.plan;

import android.content.Intent;
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.HttpConfig;
import com.rc.httpcore.bean.BelongingPersonBean;
import com.rc.httpcore.bean.ChemicalInfoBean;
import com.rc.httpcore.bean.HxpChemicalVo;
import com.rc.httpcore.bean.StockDetailsModel;
import com.rc.httpcore.bean.TopicDataBean;
import com.rc.httpcore.client.ApiRepository;
import com.rc.httpcore.client.HttpTool;
import com.rc.httpcore.exception.NetException;

import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.Response;
import xn.hxp.app.ChemicalApp;
import xn.hxp.receiver.PortScanHelper;
import xn.hxp.ui.plan.add.AddActivity;
import xn.hxp.ui.plan.locker.LockerAdapter;
import xn.hxp.ui.plan.locker.LockerFragment;
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.CabinetLayerSelect;
import xn.hxp.ui.plan.room.bean.locker.HxpCabinetDoorVo;
import xn.hxp.ui.plan.room.bean.locker.HxpCabinetVo;
import xn.hxp.ui.plan.room.bean.locker.HxpLabCabinetListVo;
import xn.hxp.ui.plan.room.bean.locker.HxpLabCabinetVo;
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 PlanAddActivityHelp {

    private PlanAddActivity activity;

    public PlanAddActivityHelp(PlanAddActivity planAddActivity) {
        activity = planAddActivity;
    }

    public void getLabInfo() {
        activity.showLoading("加载中...");
        // 实验室基本信息
        activity.addDisposable(ApiRepository.INSTANCE.getRelList(ChemicalApp.subjectId).subscribe(new Consumer<ChemicalInfoBean>() {
            @Override
            public void accept(ChemicalInfoBean chemicalInfoBean) throws Exception {
                activity.chemicalInfo = chemicalInfoBean;
                getCabinetList(chemicalInfoBean);
            }
        }, throwable -> {
            LogUtils.e(Log.getStackTraceString(throwable));
            activity.dismissLoading();
            PopTip.show("实验室基本信息获取失败,请重试!");
            activity.finish();
        }));
    }

    private void getCabinetList(ChemicalInfoBean chemicalInfoBean) {
        // 获取实验室柜子信息
        ThreadUtils.executeByCached(new ThreadUtils.SimpleTask<List<HxpCabinetVo>>() {
            @Override
            public List<HxpCabinetVo> doInBackground() throws Throwable {
                Response response = HttpTool.getCabinetList(chemicalInfoBean.getSubId());
                if (response.isSuccessful()) {
                    String json = response.body().string();
                    HxpLabCabinetListVo hxpCabinetListVo = GsonUtils.fromJson(json, HxpLabCabinetListVo.class);
                    if (hxpCabinetListVo.getCode() == 200) {
                        HxpLabCabinetVo hxpLabCabinetVo = hxpCabinetListVo.getData();
                        try {
                            // 实验室负责人
                            RoomTool.getInstance().hxpLabDirectorDAO().insertAll(hxpLabCabinetVo.getAdminList());
                            // 实验室安全员
                            RoomTool.getInstance().hxpLabSafeDAO().insertAll(hxpLabCabinetVo.getSafeList());
                        } catch (Exception e) {
                            LogUtils.e(Log.getStackTraceString(e));
                        }
                        return hxpLabCabinetVo.getCabinetList();
                    } else {
                        throw new NetException("" + hxpCabinetListVo.getCode(), hxpCabinetListVo.getMessage());
                    }
                } else {
                    throw new NetException("" + response.code(), response.message());
                }
            }

            @Override
            public void onSuccess(List<HxpCabinetVo> hxpCabinetVoList) {
                activity.dismissLoading();
                if (null != hxpCabinetVoList && !hxpCabinetVoList.isEmpty()) {
                    activity.cabinetVoList = hxpCabinetVoList;
                    activity.hxpCabinetDAO.insertAll(activity.cabinetVoList);
                    // 录入柜子
                    for (int i = 0; i < activity.cabinetVoList.size(); i++) {
                        HxpCabinetVo hxpCabinetVo = activity.cabinetVoList.get(i);
                        List<HxpCabinetDoorVo> hxpCabinetDoorVoList = hxpCabinetVo.getCabinetDoorVoList();
                        if (null != hxpCabinetDoorVoList && !hxpCabinetDoorVoList.isEmpty()) {
                            // 录入柜门
                            activity.hxpDoorDAO.insertAll(hxpCabinetDoorVoList);
                        }
                    }

                    // 柜子初始化
                    for (int i = 0; i < activity.cabinetVoList.size(); i++) {
                        HxpCabinetVo hxpCabinetVo = activity.cabinetVoList.get(i);
                        activity.cabinetFragmentList.add(new LockerFragment(hxpCabinetVo.getCabinetId(), activity.fragmentCallBack));
                    }

                    activity.lockerAdapter = new LockerAdapter(activity, activity.cabinetFragmentList);
                    activity.binding.lockerVP2.setAdapter(activity.lockerAdapter);
                    activity.binding.lockerVP2.setOffscreenPageLimit(1);

                    updateInventoryUi();
                }
            }

            @Override
            public void onFail(Throwable t) {
                super.onFail(t);
                PopTip.show("化学品柜获取失败,请重试!");
                activity.dismissLoading();
                activity.finish();
            }
        });
    }

    /**
     * 选择柜层
     */
    public void selectCabinetLayer(CabinetLayerSelect lastSelectInfo) {
        // 选择柜层数据库更新
        activity.hxpLayerDAO.insert(lastSelectInfo);
        activity.hxpLayerDAO.change(lastSelectInfo.getCabinetId(), lastSelectInfo.getDoorId(), lastSelectInfo.getLayer());
        // 更新待存储列表
        updateInventoryUi();
    }


    /**
     * 更新待存储列表
     */
    public void updateInventoryUi() {
        // 待存储列表更新
        CabinetLayerSelect cabinetLayerSelect = activity.hxpLayerDAO.getChanged();
        if (null != cabinetLayerSelect) {
            List<InventoryItemBean> inventoryItemBeanList = activity.hxpInventoryDAO.getById(cabinetLayerSelect.getCabinetId(), cabinetLayerSelect.getDoorId(), cabinetLayerSelect.getLayer());
            // 展示待存储UI
            activity.binding.inputRL.setVisibility(View.VISIBLE);
            if (null != inventoryItemBeanList && !inventoryItemBeanList.isEmpty()) {
                activity.binding.scanLL.setVisibility(View.GONE);
                activity.binding.planLV.setVisibility(View.VISIBLE);
                activity.inventoryItemBeanList.clear();
                activity.inventoryItemBeanList.addAll(inventoryItemBeanList);
                activity.planAdapter.notifyDataSetChanged();
            } else {
                activity.binding.scanLL.setVisibility(View.VISIBLE);
                activity.binding.planLV.setVisibility(View.GONE);
            }
        }
    }

    public void chemicalSearchByCode(String code) {
        activity.showLoading("查询中...");
        ThreadUtils.executeByCached(new ThreadUtils.SimpleTask<HxpChemicalVo>() {
            @Override
            public HxpChemicalVo doInBackground() throws Throwable {
                String message = "";
                Response response = HttpTool.scanCodeChemical(code, ChemicalApp.subjectId);
                if (response.isSuccessful()) {
                    String json = response.body().string();
                    LogUtils.d(json);
                    JSONObject jsonObject = new JSONObject(json);
                    if (200 == jsonObject.getInt("code")) {
                        return GsonUtils.fromJson(jsonObject.getJSONObject("data").toString(), HxpChemicalVo.class);
                    } else {
                        message = jsonObject.getString("message");
                    }
                } else {
                    message = response.message();
                }
                PopTip.show(message);
                return null;
            }

            @Override
            public void onSuccess(HxpChemicalVo result) {
                LogUtils.d(result);
                if (result != null) {
                    boolean isHasHxp = false;
                    for (int i = 0; i < activity.inventoryItemBeanList.size(); i++) {
                        InventoryItemBean inventoryItemBean = activity.inventoryItemBeanList.get(i);
                        HxpChemicalVo hxpChemicalVo = inventoryItemBean.getHxpChemicalVo();
                        if (null != hxpChemicalVo) {
                            List<StockDetailsModel> stockDetailsModelList = hxpChemicalVo.getStockDetailsModelList();
                            if (null != stockDetailsModelList && !stockDetailsModelList.isEmpty()) {
                                for (int j = 0; j < stockDetailsModelList.size(); j++) {
                                    StockDetailsModel stockDetailsModel = stockDetailsModelList.get(j);
                                    if (code.equals(stockDetailsModel.getTagCode())) {
                                        isHasHxp = true;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    if (!isHasHxp) {
                        List<StockDetailsModel> stockDetailsModelList = result.getStockDetailsModelList();
                        if (null == stockDetailsModelList) {
                            stockDetailsModelList = new ArrayList<>();
                        }
                        String wxCode = HttpConfig.Companion.getAPI_BASE_QC_URL() + "?code=" + code + "&type=9";
                        StockDetailsModel stockDetailsModel = new StockDetailsModel(null, null, code, 0, wxCode);
                        stockDetailsModelList.add(stockDetailsModel);
                        result.setStockDetailsModelList(stockDetailsModelList);
                        Intent intent = new Intent(activity, AddActivity.class);
                        intent.putExtra("data", "qr");
                        intent.putExtra("Chemical", GsonUtils.toJson(result));
                        activity.intentActivityResultLauncher.launch(intent);
                    } else {
                        PopTip.show("请勿重复录入化学品!");
                    }
                }
                activity.dismissLoading();
            }

            @Override
            public void onFail(Throwable t) {
                super.onFail(t);
                activity.showNetError(t);
                activity.dismissLoading();
            }
        });
    }

    public void startScanEventListener() {
        if (activity.portScanHelper == null) {
            activity.portScanHelper = new PortScanHelper(activity, (type, content) -> {
                // https://labcontrol.nwafu.edu.cn/api/?code=5020641&type=9
                Log.d("扫码", content);
                boolean isGR = isValidDateTimeString(content);
                Map<String, String> params = extractParameters(content);
                // 是否国瑞的码
                if (isGR) {
                    chemicalSearchByCode(content);
                    return;
                }
                // 是否忠江的码
                else if (params != null) {
                    String code = params.get("code");
                    String qrType = params.get("type");
                    if (!TextUtils.isEmpty(code) && !TextUtils.isEmpty(qrType)) {
                        chemicalSearchByCode(code);
                        return;
                    }
                }
                // 无法识别码
                PopTip.show("无效二维码/条形码，请手动录入或重试。");
            });
        }
    }

    private boolean isValidDateTimeString(String dateTimeString) {
        try {
            if (dateTimeString == null || dateTimeString.length() != 18) {
                return false;
            }
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSSS", Locale.getDefault());
            formatter.setLenient(false); // This is crucial for strict validation

            formatter.parse(dateTimeString);
            return true;
        } catch (ParseException e) {
            return false;
        }
    }

    private Map<String, String> extractParameters(String inputString) {
        try {
            Map<String, String> parameters = new HashMap<>();
            // Regular expression to match the parameters, ignoring the URL part
            String regex = "code=([a-zA-Z0-9]+)&type=(\\d+)";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(inputString);
            if (matcher.find()) {
                // Extract the values of code and type from the matched groups
                String codeValue = matcher.group(1); // Group 1 is the value of code
                String typeValue = matcher.group(2); // Group 2 is the value of type
                parameters.put("code", codeValue);
                parameters.put("type", typeValue);
            }
            return parameters;
        } catch (Exception e) {
            LogUtils.e(Log.getStackTraceString(e));
        }
        return null;
    }

    public void save() {
        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();
                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.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);
                }
                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) {
                        return "";
                    } else {
                        return jsonObject.getString("message");
                    }
                } else {
                    return response.message();
                }
            }

            @Override
            public void onSuccess(String result) {
                activity.dismissLoading();
                if (!TextUtils.isEmpty(result)) {
                    activity.binding.subAdd.setEnabled(true);
                    PopTip.show(result);
                } else {
                    activity.finish();
                    activity.startActivity(new Intent(activity, SaveListActivity.class));
                }
            }

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