<template>
  <div class="app-container backclause-page">
    <div v-if="!showForm" class="flex gap-4 h-full">
      <!-- 左侧分类侧边栏 -->
      <div class="category-sidebar bg-white rounded p-4 flex flex-col">
        <div class="sidebar-header flex justify-between items-center mb-4">
          <span class="font-bold text-base">背调分类</span>
          <el-button link class="add-btn" @click="handleCategoryAdd">
            <el-icon :size="14"><i-ep-plus /></el-icon>
          </el-button>
        </div>
        <div class="category-list flex-1 overflow-y-auto">
          <div
            v-for="item in categoryList"
            :key="item.id"
            :class="['category-item', activeCategoryId === item.id ? 'active' : '']"
            @click="activeCategoryId = item.id"
          >
            <div class="flex items-center gap-2 overflow-hidden">
              <el-icon><i-ep-fold /></el-icon>
              <span class="truncate">{{ item.name }}</span>
              <span v-if="item.isDefault" class="text-xs text-gray-400 shrink-0">(不可删除)</span>
            </div>
            <div v-if="!item.isDefault" class="item-ops shrink-0">
              <el-button link type="primary" @click.stop="handleCategoryEdit(item)">
                <el-icon><i-ep-edit /></el-icon>
              </el-button>
              <el-button link type="danger" @click.stop="handleCategoryDelete(item)">
                <el-icon><i-ep-delete /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧列表内容 -->
      <div class="flex-1 bg-white rounded p-4 flex flex-col">
        <div class="header-bar flex justify-between items-center mb-4">
          <el-input
            v-model="queryParams.keyword"
            placeholder="请输入"
            style="width: 320px"
            clearable
            class="search-input"
            @keyup.enter="handleQuery"
          >
            <template #append>
              <el-button @click="handleQuery">
                <el-icon><i-ep-search /></el-icon>
              </el-button>
            </template>
          </el-input>

          <el-button type="primary" @click="handleAddClause">创建条款</el-button>
        </div>

        <el-table
          v-loading="loading"
          :data="tableData"
          style="width: 100%"
          header-cell-class-name="custom-header"
          class="custom-table flex-1"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="name" label="条款" min-width="250" show-overflow-tooltip />
          <el-table-column prop="type" label="条款类型" width="120" />
          <el-table-column prop="setting" label="条款设置" width="100" />
          <el-table-column prop="description" label="条款描述" min-width="200" show-overflow-tooltip />
          <el-table-column prop="price" label="价格" width="100" />
          <el-table-column label="状态" width="100">
            <template #default="scope">
              <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="scope">
              <div class="flex gap-2">
                <el-button link type="primary" @click="handleEditClause(scope.row)">编辑</el-button>
                <el-button link type="danger" @click="handleDeleteClause(scope.row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-wrapper mt-4 flex justify-end">
          <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :total="total"
            background
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 创建/编辑条款表单 -->
    <ClauseForm
      v-else
      :initial-data="currentClause"
      @cancel="showForm = false"
      @submit="handleFormSubmit"
    />

    <!-- 分类弹窗 -->
    <el-dialog
      v-model="categoryDialog.visible"
      :title="categoryDialog.type === 'add' ? '创建分类' : '编辑分类'"
      width="480px"
      class="custom-dialog"
    >
      <el-form :model="categoryDialog.form" label-width="100px" label-position="right">
        <el-form-item label="分类名称:" prop="name" required>
          <el-input v-model="categoryDialog.form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="价格:">
          <el-input v-model="categoryDialog.form.price" placeholder="45" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="categoryDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="confirmCategory">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import ClauseForm from './ClauseForm.vue';

const loading = ref(false);
const total = ref(243);
const showForm = ref(false);
const activeCategoryId = ref('1');
const currentClause = ref(null);

const categoryList = ref([
  { id: '1', name: '条款清单', isDefault: true, price: '' },
  { id: '2', name: '新人职场版', isDefault: false, price: '45' },
  { id: '3', name: '基层员工版', isDefault: false, price: '65' },
  { id: '4', name: '中层员工版', isDefault: false, price: '120' },
  { id: '5', name: '自定义条款', isDefault: false, price: '' },
]);

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  keyword: '',
});

const tableData = ref([
  {
    id: '1',
    name: '中国大陆工作履历及表现核实(1HR+1上级)*1段履历及表现',
    type: '身份风险',
    setting: '必选',
    description: '结合候选人提供的HR+...',
    price: '11',
    status: 1,
  },
  {
    id: '2',
    name: '中国大陆工作履历及表现核实(1HR+1上级)*1段履历及表现',
    type: '职业风险',
    setting: '可选',
    description: '结合候选人提供的HR+...',
    price: '22',
    status: 1,
  },
  {
    id: '3',
    name: '中国大陆工作履历及表现核实(1HR+1上级)*1段履历及表现',
    type: '职业风险',
    setting: '可选',
    description: '结合候选人提供的HR+...',
    price: '33',
    status: 1,
  },
]);

const categoryDialog = reactive({
  visible: false,
  type: 'add',
  form: {
    id: '',
    name: '',
    price: '',
  },
});

const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

const getList = () => {
  loading.value = true;
  setTimeout(() => {
    loading.value = false;
  }, 300);
};

const handleSizeChange = () => getList();
const handleCurrentChange = () => getList();

const handleCategoryAdd = () => {
  categoryDialog.type = 'add';
  categoryDialog.form = { id: '', name: '', price: '' };
  categoryDialog.visible = true;
};

const handleCategoryEdit = (item: any) => {
  categoryDialog.type = 'edit';
  categoryDialog.form = { ...item };
  categoryDialog.visible = true;
};

const confirmCategory = () => {
  if (categoryDialog.type === 'add') {
    categoryList.value.push({
      id: Date.now().toString(),
      name: categoryDialog.form.name,
      isDefault: false,
      price: categoryDialog.form.price,
    });
    ElMessage.success('创建成功');
  } else {
    const index = categoryList.value.findIndex((i) => i.id === categoryDialog.form.id);
    if (index > -1) {
      categoryList.value[index] = { ...categoryList.value[index], ...categoryDialog.form };
    }
    ElMessage.success('修改成功');
  }
  categoryDialog.visible = false;
};

const handleCategoryDelete = (item: any) => {
  ElMessageBox.confirm('确定要删除该分类吗？', '提示', {
    type: 'warning',
  }).then(() => {
    categoryList.value = categoryList.value.filter((i) => i.id !== item.id);
    ElMessage.success('删除成功');
  });
};

const handleAddClause = () => {
  currentClause.value = null;
  showForm.value = true;
};

const handleEditClause = (row: any) => {
  currentClause.value = { ...row };
  showForm.value = true;
};

const handleDeleteClause = (row: any) => {
  ElMessageBox.confirm('确定要删除该条款吗？', '提示', {
    type: 'warning',
  }).then(() => {
    tableData.value = tableData.value.filter((i) => i.id !== row.id);
    ElMessage.success('删除成功');
  });
};

const handleFormSubmit = (formData: any) => {
  if (currentClause.value) {
    const index = tableData.value.findIndex((i) => i.id === formData.id);
    if (index > -1) {
      tableData.value[index] = { ...formData };
    }
    ElMessage.success('修改成功');
  } else {
    tableData.value.unshift({
      ...formData,
      id: Date.now().toString(),
    });
    ElMessage.success('创建成功');
  }
  showForm.value = false;
};
</script>

<style scoped lang="scss">
.backclause-page {
  height: calc(100vh - 84px);
  padding: 20px;
  background-color: #f0f2f5;

  .category-sidebar {
    width: 260px;
    height: 100%;

    .sidebar-header {
      .add-btn {
        width: 22px;
        height: 22px;
        background-color: #606266;
        color: #fff;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0;
        
        &:hover {
          background-color: #303133;
        }
        
        :deep(.el-icon) {
          font-weight: bold;
        }
      }
    }

    .category-list {
      .category-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px 12px;
        cursor: pointer;
        border-radius: 4px;
        margin-bottom: 4px;
        transition: all 0.3s;

        &:hover {
          background-color: #f5f7fa;
          .item-ops {
            display: flex;
          }
        }

        &.active {
          background-color: #ecf5ff;
          color: #409eff;
        }

        .item-ops {
          display: none;
          gap: 4px;
        }
      }
    }
  }

  :deep(.custom-header th) {
    background-color: #f7f8fa !important;
    color: #4e5969;
    font-weight: 500;
    padding: 12px 0;
    border-bottom: none !important;
  }

  .custom-table {
    :deep(.el-table__inner-wrapper::before) {
      display: none;
    }
  }

  .search-input {
    :deep(.el-input-group__append) {
      background-color: #007bff;
      border-color: #007bff;
      color: #fff;
      padding: 0;
      .el-button {
        border: none;
        margin: 0;
        padding: 0 15px;
        color: #fff;
        &:hover {
          background-color: #0069d9;
        }
      }
    }
  }
}

:deep(.custom-dialog) {
  .el-dialog__header {
    border-bottom: 1px solid #f0f2f5;
    margin-right: 0;
    padding: 15px 20px;
  }
  .el-dialog__body {
    padding: 30px 40px;
  }
}
</style>
