<template>
  <div class="table-box">
    <ProTable ref="proTable" :columns="columns" :request-api="getTableList" :data-callback="dataCallback">
      <template #tableHeader>
        <el-button type="primary" :icon="CirclePlus" :disabled="!isAdmin" @click="handleCreate"> 新增律师 </el-button>
      </template>
      <template #operation="scope">
        <el-button type="primary" link :icon="EditPen" :disabled="!isAdmin" @click="handleEdit(scope.row)"> 编辑 </el-button>
        <el-button type="danger" link :icon="Delete" :disabled="!isAdmin" @click="handleDelete(scope.row)"> 删除 </el-button>
      </template>
    </ProTable>
    <LawyerDialog
      ref="lawyerDialogRef"
      :law-firm-options="lawFirmOptions"
      :scene-options="sceneOptions"
      :professional-options="professionalOptions"
      @success="refreshTable"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import type { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import {
  getLawyerPage,
  addLawyerUser,
  deleteLawyerUser,
  editLawyerUser,
  getLawFirmPage,
  getScenePage,
  getExpertiseAreaPage
} from "@/api/modules/lawyer";
import { CirclePlus, Delete, EditPen } from "@element-plus/icons-vue";
import LawyerDialog from "./components/LawyerDialog.vue";
import { useUserStore } from "@/stores/modules/user";

const proTable = ref<ProTableInstance>();
const lawyerDialogRef = ref<InstanceType<typeof LawyerDialog>>();
const lawFirmOptions = ref<{ label: string; value: string | number; paymentAccount?: string }[]>([]);
const sceneOptions = ref<any[]>([]);
const professionalOptions = ref<{ label: string; value: string | number }[]>([]);

const userStore = useUserStore();
const isAdmin = computed(() => userStore.userInfo?.name === "admin");
const loginFirmId = computed(() => userStore.userInfo?.roleId || "");

const ensureAdmin = () => {
  if (isAdmin.value) return true;
  ElMessage.warning("仅管理员可使用该功能");
  return false;
};

const columns = reactive<ColumnProps<any>[]>([
  { label: "序号", type: "index", width: 60, align: "center" },
  { label: "律师姓名", prop: "name", width: 110, search: { el: "input", props: { placeholder: "请输入律师姓名" } } },
  { label: "联系电话", prop: "phone", width: 140, search: { el: "input", props: { placeholder: "请输入联系电话" } } },
  {
    label: "从业时间",
    prop: "practiceStartDate",
    width: 140,
    search: {
      el: "date-picker",
      props: {
        type: "date",
        valueFormat: "YYYY-MM-DD",
        placeholder: "请选择从业时间"
      }
    }
  },
  // { label: "专业领域", prop: "expertiseAreaInfo" },
  { label: "法律场景", prop: "firstLevelScenario" },
  {
    label: "接单状态",
    prop: "status",
    width: 120,
    tag: true,
    enum: [
      { label: "接单中", value: 1, tagType: "success" },
      { label: "暂停接单", value: 0, tagType: "info" }
    ],
    fieldNames: { label: "label", value: "value" }
  },
  { label: "收款账号", prop: "paymentNum" },
  { label: "所属律所", prop: "firmName" },
  { label: "操作", prop: "operation", width: 200, fixed: "right" }
]);

const getTableList = async (params: any) => {
  const newParams: Record<string, any> = { ...params, page: params.pageNum, size: params.pageSize };
  delete newParams.pageNum;
  delete newParams.pageSize;
  if (!isAdmin.value && loginFirmId.value) {
    newParams.firmId = loginFirmId.value;
  }
  return getLawyerPage(newParams);
};

const dataCallback = (data: any) => ({
  list: data.records,
  total: data.total
});

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

const handleCreate = () => {
  if (!ensureAdmin()) return;
  lawyerDialogRef.value?.open({
    title: "新增律师",
    onSubmit: async payload => {
      let params = {
        name: payload.name,
        phone: payload.phone,
        practiceStartDate: payload.practiceStartDate,
        firstLevelScenario: payload.firstLevelScenario,
        status: payload.status,
        paymentNum: payload.paymentNum,
        lawFirmId: payload.lawFirmId
      };
      await addLawyerUser(params);
      ElMessage.success("新增成功");
      refreshTable();
    }
  });
};

const handleEdit = (row: any) => {
  if (!ensureAdmin()) return;
  lawyerDialogRef.value?.open({
    title: "编辑律师",
    row,
    onSubmit: async payload => {
      let params = {
        id: payload.id,
        name: payload.name,
        phone: payload.phone,
        practiceStartDate: payload.practiceStartDate,
        firstLevelScenario: payload.firstLevelScenario,
        status: payload.status,
        paymentNum: payload.paymentNum,
        lawFirmId: payload.lawFirmId
      };
      await editLawyerUser(params);
      ElMessage.success("编辑成功");
      refreshTable();
    }
  });
};

const handleDelete = (row: any) => {
  if (!ensureAdmin()) return;
  ElMessageBox.confirm(`确定删除律师【${row.userName}】吗？`, "提示", {
    type: "warning"
  })
    .then(async () => {
      await deleteLawyerUser({ id: row.id });
      ElMessage.success("删除成功");
      refreshTable();
    })
    .catch(() => {});
};

const fetchLawFirmOptions = async () => {
  try {
    const res: any = await getLawFirmPage({ page: 1, size: 999 });
    const listSource = res.data.records || [];
    lawFirmOptions.value = listSource.map((item: any) => ({
      label: item.firmName,
      value: item.id,
      paymentAccount: item.paymentAccount
    }));
  } catch (error) {
    console.error("获取律所列表失败", error);
    lawFirmOptions.value = [];
  }
};

const buildSceneTree = (list: any[] = []) => {
  const map = new Map<string | number, any>();
  const roots: any[] = [];
  list.forEach(item => {
    map.set(item.id, { ...item, children: [] });
  });
  list.forEach(item => {
    const current = map.get(item.id);
    if (item.parentId && map.has(item.parentId)) {
      map.get(item.parentId).children.push(current);
    } else {
      roots.push(current);
    }
  });
  return roots;
};

const fetchSceneOptions = async () => {
  try {
    const res: any = await getScenePage({ page: 1, size: 999 });
    const list = res?.records || res?.data?.records || [];
    sceneOptions.value = buildSceneTree(list);
  } catch (error) {
    console.error("获取法律场景失败", error);
    sceneOptions.value = [];
  }
};

const fetchProfessionalOptions = async () => {
  try {
    const res: any = await getExpertiseAreaPage({ page: 1, size: 999 });
    const list = res?.records || res?.data?.records || [];
    professionalOptions.value = list.map((item: any) => ({
      label: item.expertiseAreaInfo,
      value: item.id
    }));
  } catch (error) {
    console.error("获取专业领域失败", error);
    professionalOptions.value = [];
  }
};

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

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