<template>
  <div class="table-box">
    <ProTable ref="proTable" :columns="columns" :request-api="getTableList" :data-callback="dataCallback">
      <template #tableHeader>
        <el-button type="primary" :icon="CirclePlus" @click="openDialog()"> 新增专业领域 </el-button>
      </template>
      <template #operation="scope">
        <el-button type="primary" link :icon="EditPen" @click="openDialog(scope.row)"> 编辑 </el-button>
        <el-button type="danger" link :icon="Delete" @click="handleDelete(scope.row)"> 删除 </el-button>
      </template>
    </ProTable>
    <ProfessionalDialog ref="dialogRef" @success="refreshTable" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import type { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen } from "@element-plus/icons-vue";
import { getExpertiseAreaPage, addExpertiseArea, editExpertiseArea, deleteExpertiseArea } from "@/api/modules/lawyer";
import ProfessionalDialog from "./components/ProfessionalDialog.vue";

const proTable = ref<ProTableInstance>();
const dialogRef = ref<InstanceType<typeof ProfessionalDialog>>();

const columns = reactive<ColumnProps<any>[]>([
  { label: "序号", type: "index", width: 60, align: "center" },
  { label: "专业领域", prop: "expertiseAreaInfo", search: { el: "input", props: { placeholder: "请输入专业领域" } } },
  { label: "创建时间", prop: "createdTime", width: 300 },
  { label: "操作", prop: "operation", width: 200, fixed: "right" }
]);

const getTableList = async (params: any) => {
  const newParams = { ...params, page: params.pageNum, size: params.pageSize };
  delete newParams.pageNum;
  delete newParams.pageSize;
  return getExpertiseAreaPage(newParams);
};

const dataCallback = (data: any) => ({
  list: data.records || data.list || [],
  total: data.total || data.count || 0
});

const refreshTable = () => {
  proTable.value?.getTableList();
};

const openDialog = (row?: any) => {
  dialogRef.value?.open({
    title: row ? "编辑专业领域" : "新增专业领域",
    row,
    onSubmit: async payload => {
      if (row?.id) {
        await editExpertiseArea(payload);
        ElMessage.success("编辑成功");
      } else {
        await addExpertiseArea(payload);
        ElMessage.success("新增成功");
      }
      refreshTable();
    }
  });
};

const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确认删除专业领域【${row.expertiseAreaInfo}】吗？`, "提示", {
    type: "warning"
  })
    .then(async () => {
      await deleteExpertiseArea({ id: row.id });
      ElMessage.success("删除成功");
      refreshTable();
    })
    .catch(() => {});
};

onMounted(() => {
  refreshTable();
});
</script>

<style scoped lang="scss"></style>
