<template>
  <div class="app-container backclause-page">
    <div v-if="!showForm" class="flex gap-4 h-full">
      <!-- 左侧分类侧边栏 -->
      <div class="category-sidebar p-4 flex flex-col modern-card">
        <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
            :class="['category-item font-bold', activeCategoryId === 'all' ? 'active' : '']"
            @click="activeCategoryId = 'all'"
          >
            <div class="flex items-center gap-2 overflow-hidden">
              <el-icon><i-ep-management /></el-icon>
              <span class="truncate">条款清单</span>
            </div>
          </div>
          
          <div
            v-for="item in categoryList"
            :key="item.id"
            :class="['category-item ml-4', 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 p-4 flex flex-col modern-card">
        <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">
            <template #default="scope">
              <el-tag v-if="scope.row.typeName" :type="getTypeTagType(scope.row.type)">
                {{ scope.row.typeName }}
              </el-tag>
              <span v-else>{{ scope.row.type }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="条款描述" min-width="200" show-overflow-tooltip>
            <template #default="scope">
              <div v-html="scope.row.description"></div>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="价格" width="100" />
          <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
          <el-table-column label="状态" width="100">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                active-value="1"
                inactive-value="0"
                @change="handleStatusChange(scope.row)"
              />
            </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, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import ClauseForm from './ClauseForm.vue';
import { listBackCategory, addBackCategory, updateBackCategory, delBackCategory } from '@/api/system/backCategory';
import { BackCategoryVO } from '@/api/system/backCategory/types';
import { listBackClause, delBackClause, addBackClause, updateBackClause, changeBackClauseStatus } from '@/api/system/backClause';
import { BackClauseVO } from '@/api/system/backClause/types';
import { watch } from 'vue';
import { useDict } from '@/utils/dict';

const { sys_clause_type } = useDict('sys_clause_type');

const loading = ref(false);
const total = ref(0);
const showForm = ref(false);
const activeCategoryId = ref<string | number>('all');
const currentClause = ref(null);

const categoryList = ref<BackCategoryVO[]>([]);

/** 查询分类列表 */
const getTypeTagType = (type: string) => {
  switch (type) {
    case '1': return 'primary';
    case '2': return 'warning';
    case '3': return 'success';
    default: return 'info';
  }
};

const getCategoryList = async () => {
  const res = await listBackCategory();
  categoryList.value = res.data;
  if (!activeCategoryId.value) {
    activeCategoryId.value = 'all';
  }
};

onMounted(() => {
  getCategoryList();
  getClauseList();
});

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

const tableData = ref<BackClauseVO[]>([]);

/** 查询条款列表 */
const getClauseList = async () => {
  if (!activeCategoryId.value) return;
  loading.value = true;
  try {
    const res = await listBackClause({
      categoryId: activeCategoryId.value === 'all' ? undefined : activeCategoryId.value,
      name: queryParams.keyword,
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize
    });
    tableData.value = res.rows;
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};

/** 监听分类切换 */
watch(activeCategoryId, () => {
  queryParams.pageNum = 1;
  getClauseList();
});

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

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

const getList = () => {
  getClauseList();
};

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 = async () => {
  if (categoryDialog.type === 'add') {
    await addBackCategory(categoryDialog.form);
    ElMessage.success('创建成功');
  } else {
    await updateBackCategory(categoryDialog.form);
    ElMessage.success('修改成功');
  }
  categoryDialog.visible = false;
  getCategoryList();
};

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

const handleStatusChange = async (row: BackClauseVO) => {
  let text = row.status === '1' ? '启用' : '停用';
  try {
    await ElMessageBox.confirm('确认要"' + text + '""' + row.name + '"条款吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    await changeBackClauseStatus(row.id, row.status);
    ElMessage.success(text + '成功');
  } catch (err) {
    row.status = row.status === '1' ? '0' : '1';
  }
};

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(async () => {
    await delBackClause(row.id);
    ElMessage.success('删除成功');
    getClauseList();
  });
};

const handleFormSubmit = async (formData: any) => {
  try {
    if (formData.id) {
      await updateBackClause(formData);
      ElMessage.success('修改成功');
    } else {
      await addBackClause({
        ...formData,
        categoryId: activeCategoryId.value
      });
      ElMessage.success('创建成功');
    }
    showForm.value = false;
    getClauseList();
  } catch (error) {
    console.error(error);
  }
};
</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>
