<template>
  <view class="container">
    <uni-forms ref="carDispatchByMineRef">
      <uni-forms-item label="站点" name="siteId">
        <uni-data-select
          v-model="customFormData.reginvalue"
          :localdata="regindata"
          @change="changeZT"
        ></uni-data-select>
      </uni-forms-item>
      <uni-forms-item label="车辆编号" name="deviceValues">
        <view style="display: flex; align-items: center">
          <uni-easyinput
            v-model="customFormData.deviceValues"
            placeholder="请扫描或输入中控编号"
            suffixIcon="scan"
            @iconClick="handleScan"
          >
          </uni-easyinput>
          <button class="btn-add" @click="addDevice">添加</button>
        </view>
      </uni-forms-item>
    </uni-forms>
    <uni-section title="车辆列表" type="line">
      <uni-table border stripe emptyText="暂无更多数据">
        <!-- 表头行 -->
        <uni-tr>
          <uni-th align="center">车辆编号</uni-th>
          <uni-th align="center">操作</uni-th>
        </uni-tr>
        <!-- 表格数据行 -->
        <uni-tr v-for="(item, index) in carList" :key="item.index">
          <uni-td align="center">{{ item.number }}</uni-td>
          <uni-td>
            <view class="uni-group">
              <button
                class="uni-button"
                size="mini"
                type="warn"
                @click="handleDel(item)"
              >
                删除
              </button>
            </view>
          </uni-td>
        </uni-tr>
      </uni-table>
    </uni-section>
  </view>
  <view class="nav-panel">
    <c-uni-goods-nav
      :fill="true"
      :options="[]"
      :buttonGroup="navButtonGroup"
      @buttonClick="navButtonClick"
    />
  </view>
</template>
<script setup>
import { ref, onMounted, reactive } from "vue";
import { onLoad, onShow } from "@dcloudio/uni-app";
import * as api from "@/utils/api.js";
import { useDispatchScanCodeStore } from "@/stores/scancodeByDispatch.js";
import { showMessage } from "@/utils/tools";

const carDispatchByMineRef = ref(null);
const scanCodeStore = useDispatchScanCodeStore();
const statusZT = ref(1); //0 批量下架 1 批量投放
const regindata = ref([]);
const customFormData = ref({
  reginvalue: "",
  deviceValues: "",
});
const carList = ref([]);
const navButtonGroup = reactive([
  {
    text: "创建调度工单",
    backgroundColor: "#0078D4",
    color: "#fff",
    disable: false,
  },
]);

onLoad((options) => {
  scanCodeStore.clearCode();

  if (options.bikeCode) {
    scanCodeStore.addCode(options.bikeCode);
    setCarList();
  }
});

onShow(() => {
  setCarList();
});

const navButtonClick = () => {
  if (!customFormData.value.reginvalue) {
    showMessage("请选择站点", "error", 1000);
    return;
  }
  if (carList.value.length == 0) {
    showMessage("请添加车辆编号", "error", 1000);
    return;
  }
  navButtonGroup[0].disable = true; // 禁用按钮，防止重复点击

  uni.showLoading({
    title: "正在创建调度工单...",
  });
  const params = {
    bikeCodes: scanCodeStore.getCode(),
    status: statusZT.value,
    siteId: customFormData.value.reginvalue,
    dispatchType: "仓库车调度",
  };

  api.callEbikeInfo("createWorkOrderDispatch", params).then((res) => {
    uni.hideLoading(); // 隐藏加载提示
    if (res.code == 200) {
      // 显示成功提示
      uni.showToast({
        title: "操作成功",
        icon: "success",
        duration: 1000,
      });
      // 延时跳转，确保提示完毕后再跳转
      setTimeout(() => {
        navButtonGroup[0].disable = false; // 恢复按钮状态
        uni.navigateTo({
          url: `/pages/warehouse/vehicledispatch/vehicledispatch?orderId=${
            res.data
          }&page=${3}`,
        });
      }, 1000); // 跳转延迟与提示时长一致
    } else {
      // 显示错误提示
      uni.showToast({
        title: res.message || "操作失败",
        icon: "none",
        duration: 1000,
      });
      navButtonGroup[0].disable = false; // 恢复按钮状态
    }
  });
};
const handleDel = (item) => {
  const { number } = item;
  scanCodeStore.delCode(number);
  setCarList();
};

const handleScan = () => {
  uni.navigateTo({
    url: `/pages/common/dispatchScancode`,
  });
};

function setCarList() {
  let list = scanCodeStore.getCode();
  if (list.length > 0) {
    carList.value = list.map((code, index) => ({
      number: code,
      index: index + "_" + code,
    }));
  } else {
    carList.value = [];
  }
}

const addDevice = () => {
  let carCode = customFormData.value.deviceValues;
  if (!carCode) {
    showMessage("请输入车辆编号", "error", 1000);
    return;
  }
  if (!scanCodeStore.checkCode(carCode)) {
    scanCodeStore.addCode(carCode);
    customFormData.value.deviceValues = "";
    setCarList();
  } else {
    showMessage("车辆已存在：" + carCode, "none", 1500);
    customFormData.value.deviceValues = "";
  }
};

onMounted(() => {
  let userDefultOperation = uni.getStorageSync("userDefultOperation");
  //获取站点信息
  api
    .callOperateApi(
      "ebikeRegion/getRegion?regionId=" + userDefultOperation.operationRegionId,
      {},
      "get"
    )
    .then((res) => {
      if (res.code == 200) {
        res.data.forEach((res) => {
          let quyuemap = {
            text: res.siteName,
            value: res.siteRegionId,
          };
          regindata.value.push(quyuemap);
        });
      }
    });
});

const changeZT = () => {};
</script>
<style>
.container {
  padding: 15px;
  background-color: #fff;
}

/* 全局样式 */
.uni-forms .uni-forms-item__label {
  /* 或者使用其他单位 */
}

.nav-panel {
  position: fixed;
  bottom: 0rpx;
  width: 100%;
  padding-bottom: 10px;
  z-index: 999;
  background-color: #fff;
}

.btn-add {
  margin-left: 30rpx;
  font-size: 26rpx;
  width: 120rpx;
}
.uni-group {
  display: flex;
  align-items: center;
}
</style>
