<template>
  <div class="app-container">
    <div class="type-container">
      <!-- Tab栏 -->
      <div class="tabs-container">
        <el-tabs
          v-model="editableTabsValue"
          class="demo-tabs"
          @tab-click="handleTabClick"
        >
          <el-tab-pane
            v-for="item in editableTabs"
            :key="item.name"
            :name="item.name"
          >
            <template #label>
              <span class="tab-label-text">{{ item.label }}</span>
              <span
               
                class="tab-delete-icon"
                @click.stop="deleteCustomTab(item.name)"
                >
                <img
                  src="../../../assets/images/del.png"
                  alt="删除"
                  class="delete-icon-img"
              />
            </span>
            </template>
            {{ item.content }}
          </el-tab-pane>
        </el-tabs>
        <!-- 添加按钮 -->
        <img
          src="../../../assets/images/add.png"
          class="add-tab-btn"
          @click="showAddTabDialog = true"
          alt="add"
        />
      </div>
      <!-- 新增Tab弹窗 -->
      <el-dialog
        v-model="showAddTabDialog"
        title="新增类型"
        width="320px"
        :close-on-click-modal="false"
      >
        <el-input
          v-model="newTabName"
          placeholder="请输入类型名称"
          maxlength="10"
        />
        <template #footer>
          <el-button class="export-btn" @click="showAddTabDialog = false"
            >取消</el-button
          >
          <el-button
            class="search-btn"
            type="primary"
            :disabled="!newTabName.trim() || isTabNameExist"
            @click="addTab"
            >确定</el-button
          >
        </template>
        <div
          v-if="isTabNameExist"
          style="color: #e74c3c; font-size: 13px; margin-top: 8px"
        >
          类型名称已存在
        </div>
      </el-dialog>
      <!-- 其余内容保持不变 -->
      <div class="search-action-bar">
        <div class="search-area">
          <el-input
            v-model="queryParams.typeName"
            placeholder="请输入关键字查询"
            class="search-input"
            clearable
          />
          <el-button type="primary" class="search-btn" @click="handleQuery"
            >搜索</el-button
          >
          <el-button class="reset-btn" @click="resetQuery">重置</el-button>
        </div>
        <div class="action-buttons">
          <el-button type="primary" class="add-btn" @click="handleAdd"
            >新增</el-button
          >
          <el-button
            class="delete-btn"
            @click="handleBatchDelete"
            :disabled="multiple"
            >删除</el-button
          >
        </div>
      </div>
      <!-- 表格 -->
      <el-table
        v-loading="loading"
        :data="vehicleTypeList"
        @selection-change="handleSelectionChange"
        class="custom-table"
        :header-cell-style="{ backgroundColor: '#343744', color: '#fff' }"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button link text @click="handleUpdate(scope.row)"
              >编辑</el-button
            >
            <el-button link text type="danger" @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>

        <el-table-column label="二级类型" prop="typeName">
          <template #default="scope">
            {{ scope.row.typeName }}
          </template>
        </el-table-column>
        <el-table-column label="创建人" prop="createBy" />
        <el-table-column label="创建时间" prop="createTime" />
      </el-table>
      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="open"
      :title="title"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="vehicleTypeRef"
        :model="form"
        :rules="rules"
        label-width="90px"
      >
        <el-form-item label="二级类型" prop="typeName">
          <el-input v-model="form.typeName" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from "vue";
import { Select } from "@element-plus/icons-vue";
import Pagination from "../../../components/Pagination/index.vue";
import { getCurrentInstance } from "vue";
import {
  listVehicle_type,
  getVehicle_type,
  addVehicle_type,
  updateVehicle_type,
  delVehicle_type,
} from "@/api/system/vehicle_type.js";

const { proxy } = getCurrentInstance();

// Tab相关
const editableTabsValue = ref("");
const editableTabs = ref([]);

const showAddTabDialog = ref(false);
const newTabName = ref("");

const isTabNameExist = computed(() => {
  return editableTabs.value.some(
    (tab) => tab.label === newTabName.value.trim()
  );
});

const addTab = () => {
  if (!newTabName.value.trim()) return;
  const name = newTabName.value.trim();

  // 检查类型是否已存在
  if (isTabNameExist.value) {
    proxy.$modal.msgError("该车辆类型已存在");
    return;
  }

  // 构造一级类型数据
  const typeCode = generateTypeCode(name);
  const submitData = {
    displayNameCn: name,
    displayNameEn: name, // 英文名称默认与中文相同
    typeCode: typeCode, // 生成唯一的typeCode
    typeName: name.toUpperCase().replace(/\s+/g, "_"), // 生成typeName
    pathLevel: 1,
    isLeaf: false,
    enabled: true,
    parentCode: null,
    fullPath: typeCode // 一级类型的fullPath就是其typeCode
  };

  // 调用接口添加一级类型
  addVehicle_type(submitData)
    .then((response) => {
      proxy.$modal.msgSuccess("新增类型成功");

      // 重新获取一级类型列表
      getFirstTypeList();

      // 切换到新添加的标签
      setTimeout(() => {
        editableTabsValue.value = submitData.typeCode;
      }, 100);

      // 清空输入框并关闭弹窗
      newTabName.value = "";
      showAddTabDialog.value = false;

      // 获取新标签下的数据
      setTimeout(() => {
        getList();
      }, 200);
    })
    .catch(() => {
      // 添加失败时不关闭弹窗，让用户可以修改后重试
    });
};

// 生成typeCode的辅助函数
function generateTypeCode(name) {
  // 生成基于名称的简短代码，例如"无人车" -> "WRC"
  const pinyin = name.split('').map(char => {
    // 这里简化处理，实际可能需要更复杂的拼音转换
    const pinyinMap = {
      '无': 'W', '人': 'R', '车': 'C',
      '特': 'T', '勤': 'Q', '普': 'P',
      '通': 'T', '航': 'H', '空': 'K',
      '接': 'J', '驳': 'B', '清': 'Q',
      '洁': 'J', '消': 'X', '防': 'F',
      '警': 'J', '巡': 'X', '逻': 'L',
      '配': 'P', '送': 'S', '运': 'Y',
      '输': 'S', '餐': 'C', '行': 'X',
      '李': 'L'
    };
    return pinyinMap[char] || char.charAt(0).toUpperCase();
  });
  
  // 取前2-3个字母作为代码
  let code = pinyin.slice(0, Math.min(3, pinyin.length)).join('');
  
  // 确保唯一性，添加随机数
  const randomNum = Math.floor(Math.random() * 100);
  return code + randomNum;
}

const deleteCustomTab = (tabName) => {
  // 查找要删除的标签对应的typeId
  const firstType = firstTypeList.value.find((item) => item.value === tabName);
  if (!firstType || !firstType.typeId) return;

  // 先检查该一级类型下是否有二级类型
  listVehicle_type({ topLevelCode: tabName }).then((res) => {
    if (res.rows && Array.isArray(res.rows)) {
      // 过滤出当前选中tab对应的二级类型数据
      const currentTabData = res.rows.filter(
        (item) =>
          item.parentCode === tabName ||
          (typeof item.fullPath === 'string' && item.fullPath.startsWith(tabName + '/'))
      );

      if (currentTabData.length > 0) {
        // 如果有二级类型，提示不能删除
        proxy.$modal.msgError("该类型下有二级类型，不可删除");
        return;
      }

      // 如果没有二级类型，则可以删除
      proxy.$modal
        .confirm(`确定删除 ${firstType.label} 类型吗?`, "删除")
        .then(function () {
          return delVehicle_type(firstType.typeId);
        })
        .then(() => {
          proxy.$modal.msgSuccess("删除成功");

          // 重新获取一级类型列表
          getFirstTypeList();

          // 如果删除的是当前选中的标签，切换到第一个标签
          if (editableTabsValue.value === tabName) {
            // 这里不需要手动设置editableTabsValue，因为getFirstTypeList会处理
          }
        })
        .catch(() => {
          // 删除失败时不做处理
        });
    }
  });
};

const handleTabClick = (tab) => {
  editableTabsValue.value = tab.paneName;
  queryParams.parentCode = tab.paneName;
  // 不需要在这里调用getList，因为watch会触发调用
  // getList();
};

// 列表相关
const loading = ref(false);
const vehicleTypeList = ref([]);
const total = ref(0);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const title = ref("");
const open = ref(false);

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  parentCode: "",
  typeName: undefined,
});

// 表单参数
const form = ref({});
const rules = ref({
  firstType: [
    { required: true, message: "一级类型不能为空", trigger: "change" },
  ],
  typeName: [{ required: true, message: "二级类型不能为空", trigger: "blur" }],
});

// 车辆类型选项
const firstTypeList = ref([]);

/** 查询车辆类型列表 */
function getList() {
  loading.value = true;
  queryParams.value.parentCode = editableTabsValue.value;
  listVehicle_type(queryParams.value)
    .then((res) => {
      loading.value = false;
      // 根据接口返回的数据结构进行过滤，只显示当前选中tab对应的二级类型数据
      if (res.rows && Array.isArray(res.rows)) {
        // 过滤出当前选中tab对应的二级类型数据
        const currentTabData = res.rows.filter(
          (item) =>
            item.parentCode === editableTabsValue.value ||
            (typeof item.fullPath === 'string' && item.fullPath.startsWith(editableTabsValue.value + '/'))
        );

        // 转换数据结构以适应表格显示
        vehicleTypeList.value = currentTabData.map((item) => ({
          typeId: item.typeId,
          firstType: editableTabsValue.value,
          typeName: item.displayNameCn,
          createBy: item.createBy,
          createTime: item.createTime,
        }));

        total.value = vehicleTypeList.value.length;
      } else {
        vehicleTypeList.value = [];
        total.value = 0;
      }
    })
    .catch(() => {
      loading.value = false;
      vehicleTypeList.value = [];
      total.value = 0;
    });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.value.typeName = undefined;
  queryParams.value.pageNum = 1;
  handleQuery();
}

/** 选择条数 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.typeId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  form.value.firstType = editableTabsValue.value;
  open.value = true;
  title.value = "添加车辆类型";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const typeId = row.typeId || ids.value[0];
  getVehicle_type(typeId).then((response) => {
    // 确保使用displayNameCn作为typeName显示
    if (response.data) {
      form.value = {
        typeId: response.data.typeId,
        firstType: response.data.parentCode || editableTabsValue.value,
        typeName: response.data.displayNameCn || response.data.typeName
      };
    } else {
      form.value = {};
    }
    open.value = true;
    title.value = "修改车辆类型";
  });
}

/** 提交表单 */
function submitForm() {
  proxy.$refs["vehicleTypeRef"].validate((valid) => {
    if (valid) {
      // 根据接口要求调整提交的数据结构
      const typeCode = form.value.typeId ? undefined : generateTypeCode(form.value.typeName);
  const submitData = {
    typeId: form.value.typeId,
    displayNameCn: form.value.typeName,
    displayNameEn: form.value.typeName, // 英文名称默认与中文相同
    typeCode: typeCode, // 新增时生成typeCode，修改时不改变
    typeName: form.value.typeName.toUpperCase().replace(/\s+/g, "_"), // 生成typeName
    pathLevel: 2,
    level: 2,
    parentCode: form.value.firstType,
    isLeaf: true,
    enabled: true,
    fullPath: form.value.typeId ? undefined : `${form.value.firstType}/${typeCode}` // 二级类型的fullPath是父级/自己的typeCode
  };

      if (form.value.typeId != undefined) {
        updateVehicle_type(submitData).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addVehicle_type(submitData).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const typeIds = row.typeId || ids.value;
  proxy.$modal
    .confirm("确定删除此车辆类型吗?", "删除")
    .then(function () {
      return delVehicle_type(typeIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 批量删除按钮操作 */
function handleBatchDelete() {
  if (ids.value.length === 0) {
    proxy.$modal.msgError("请选择要删除的数据");
    return;
  }
  proxy.$modal
    .confirm("确认删除选中的数据项?")
    .then(function () {
      return delVehicle_type(ids.value);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 重置表单 */
function reset() {
  form.value = {
    typeId: undefined,
    firstType: editableTabsValue.value,
    typeName: undefined,
  };
  proxy.resetForm("vehicleTypeRef");
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

// 初始化时获取一级类型数据
function getFirstTypeList() {
  listVehicle_type({ level: 1, pathLevel: 1 }).then((res) => {
    if (res.rows && Array.isArray(res.rows)) {
      const firstTypes = res.rows.filter((item) => (item.pathLevel === 1 || item.level === 1) && (item.parentCode === null || item.parentCode === undefined || item.parentCode === ''));

      // 更新firstTypeList，保留typeId信息
      firstTypeList.value = firstTypes.map((item) => ({
        label: item.displayNameCn,
        value: item.typeCode,
        typeId: item.typeId,
      }));

      // 更新可编辑的tab列表
      editableTabs.value = firstTypes.map((item) => ({
        label: item.displayNameCn,
        name: item.typeCode,
        content: "",
      }));

      // 如果当前选中的tab不在列表中，则选择第一个
      if (
        !editableTabs.value.some(
          (tab) => tab.name === editableTabsValue.value
        ) &&
        editableTabs.value.length > 0
      ) {
        editableTabsValue.value = editableTabs.value[0].name;
      }
    }
  });
}

// 初始化
onMounted(() => {
  getFirstTypeList();
  getList();
});

watch(editableTabsValue, (newValue) => {
  if (newValue) {
    queryParams.value.parentCode = newValue;
    getList();
  }
});
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  background-color: #292c38;
  color: #ffffff;
  min-height: 100%;
  border-radius: 10px;
}
.type-container {
  background-color: #292c38;
  border-radius: 4px;
  height: calc(100vh - 180px);
  overflow-y: auto;
}

.tabs-container {
  position: relative;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.demo-tabs {
  margin-bottom: 0;
  flex: 1;
  :deep(.el-tabs__header) {
    margin-bottom: 0;
  }
  :deep(.el-tabs__item) {
    color: #fff !important;
  }
  :deep(.el-tabs__active-bar) {
    // background-color: #4C4F5F !important;
  }
  :deep(.el-tabs__nav-wrap::after) {
    height: 1px;
    background-color: #4c4f5f;
  }
  :deep(.el-tabs__item.is-active) {
    color: #347ae2 !important;
  }
  :deep(.el-tabs__item:hover) {
    color: #347ae2 !important;
  }
  :deep(.tab-label-text) {
    margin-right: 4px;
  }
  :deep(.tab-delete-icon) {
    opacity: 0;
    color: #fff;
    font-size: 14px;
    font-weight: bold;
    cursor: pointer;
    transition: opacity 0.3s ease;
    margin-left: 4px;
    display: inline-flex;
    align-items: center;
    justify-content: center;

    .delete-icon-img {
      width: 12px;
      height: 12px;
      vertical-align: middle;
    }

    &:hover {
      color: #fff;
    }
  }
  :deep(.el-tabs__item.is-active .tab-delete-icon) {
    opacity: 1;
  }
  :deep(.el-tabs__item:hover .tab-delete-icon) {
    opacity: 1;
  }
}

.add-tab-btn {
  position: absolute;
  right: 0;
  top: 10px;
  width: 20px;
  height: 20px;
  cursor: pointer;
  vertical-align: middle;
  transition: filter 0.2s;
  filter: brightness(1);
  &:hover {
    filter: brightness(1.3);
  }
}
.search-action-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  .search-area {
    display: flex;
    gap: 10px;
    .search-input {
      width: 250px;
    }
    .search-btn,
    .reset-btn {
      border-radius: 8px;
      font-size: 15px;
      height: 36px;
      min-width: 80px;
    }
    .search-btn {
      background: #347ae2;
      color: #fff;
      border: none;
    }
    .reset-btn {
      background: #343744;
      color: #96a0b5;
      border: none;
    }
  }
  .action-buttons {
    margin-left: auto;
    display: flex;
    gap: 10px;
    .add-btn,
    .delete-btn {
      border-radius: 8px;
      font-size: 15px;
      height: 36px;
      min-width: 80px;
    }
    .add-btn {
      background: #347ae2;
      color: #fff;
      border: none;
    }
    .delete-btn {
      background: #343744;
      color: #96a0b5;
      border: none;
    }
  }
}
.custom-table {
  background-color: #292c38 !important;
  color: #ffffff;
  margin-bottom: 20px;
  border-radius: 4px;
  overflow: hidden;
  :deep(.el-loading-mask) {
    background-color: rgba(41, 44, 56, 0.7) !important;
  }
  :deep(.el-table__empty-block) {
    background-color: #292c38 !important;
  }
  :deep(.el-table__empty-text) {
    color: #96a0b5 !important;
  }
  :deep(.el-table) {
    background-color: #292c38 !important;
  }
  :deep(.el-table__body) {
    background-color: #292c38 !important;
  }
  :deep(.el-table__inner-wrapper::before) {
    display: none;
  }
  :deep(.el-table__header) {
    border-top-left-radius: 4px;
    border-top-right-radius: 4px;
    overflow: hidden;
  }
  :deep(.el-table__header-wrapper) {
    th {
      background-color: #343744 !important;
      color: #96a0b5 !important;
      font-weight: normal;
      border-bottom: none;
    }
    tr th.el-table__cell:first-child {
      border-top-left-radius: 6px;
      .cell {
        border-top-left-radius: 6px;
      }
    }
    tr th.el-table__cell:last-child {
      border-top-right-radius: 4px;
      .cell {
        border-top-right-radius: 4px;
      }
    }
    .el-table__header th.el-table__cell {
      background-color: #343744 !important;
      color: #96a0b5;
    }
    tr {
      background-color: #343744 !important;
    }
  }
  :deep(.el-table__body-wrapper) {
    td {
      height: 68px !important;
      background-color: #292c38;
      color: #ffffff;
      border-bottom: 1px solid #4c4f5f;
    }
  }
  :deep(.el-table__body tr:hover > td) {
    background: #2b3b5a !important;
  }
  :deep(.el-button--link) {
    border: none;
    background: transparent;
    color: #347ae2;
    padding: 0;
    margin: 0 5px;
  }
  :deep(.el-button.is-text) {
    background-color: transparent !important;
    border-color: transparent;
    color: #347ae2;
    &:hover,
    &:focus,
    &:active {
      background-color: transparent !important;
      color: #347ae2;
    }
  }
  :deep(.el-button.el-button--primary.is-text) {
    background-color: transparent !important;
    color: #347ae2;
    &:hover {
      background-color: transparent !important;
      color: #347ae2;
    }
  }
  :deep(.el-table__body tr:hover .el-button--link.is-text) {
    background-color: transparent !important;
    color: #347ae2;
  }
}
</style>
