<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>
        <el-button type="primary" :icon="Upload" :disabled="!isAdmin" @click="handleImport"> 导入 </el-button>
        <el-button
          type="primary"
          :icon="Download"
          :loading="exportLoading"
          :disabled="!hasExportableData || !isAdmin"
          @click="handleExport"
        >
          导出
        </el-button>
        <el-button
          type="primary"
          :icon="Download"
          :loading="exportAllLoading"
          :disabled="!hasExportableData || !isAdmin"
          @click="handleExportAll"
        >
          全部导出
        </el-button>
      </template>
      <template #paymentAccount="scope">
        <div class="payment-tags">
          <el-tag v-for="card in splitPayment(scope.row.paymentAccount)" :key="card">
            {{ formatCard(card) }}
          </el-tag>
        </div>
      </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>
    <LawFirmDialog ref="lawFirmDialogRef" @success="refreshTable" />
    <ImportDialog
      v-model="importVisible"
      title="导入律所"
      :download-handler="handleDownloadTemplate"
      :import-handler="handleImportSubmit"
      @success="handleImportSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onActivated, 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 {
  getLawFirmPage,
  addLawFirm,
  deleteLawFirm,
  editLawFirm,
  importData,
  downloadLawFirmTemplate,
  exportLawFirm
} from "@/api/modules/lawyer";
import { useDownload } from "@/hooks/useDownload";
import { CirclePlus, Delete, EditPen, Upload, Download } from "@element-plus/icons-vue";
import LawFirmDialog from "./components/LawFirmDialog.vue";
import ImportDialog from "./components/ImportDialog.vue";
import { useUserStore } from "@/stores/modules/user";

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 proTable = ref<ProTableInstance>();
const lawFirmDialogRef = ref<InstanceType<typeof LawFirmDialog>>();
const importVisible = ref(false);
const exportLoading = ref(false);
const exportAllLoading = ref(false);
const tableTotal = ref(0);
const hasExportableData = computed(() => tableTotal.value > 0);

const columns = reactive<ColumnProps<any>[]>([
  { label: "序号", type: "index", width: 60, align: "center" },
  { label: "律所名称", prop: "firmName", search: { el: "input", props: { placeholder: "请输入律所名称" } } },
  {
    label: "负责人姓名",
    prop: "directorName",
    width: 160,
    search: { el: "input", props: { placeholder: "请输入负责人姓名" } }
  },
  { label: "位置", prop: "address" },
  { label: "统一社会信用代码", prop: "creditCode", width: 220 },
  {
    label: "信息服务费",
    prop: "platformCommissionRatio",
    width: 160,
    align: "center",
    render: scope => {
      return `${scope.row.platformCommissionRatio ?? "0"}%`;
    }
  },
  { label: "收款账号", prop: "paymentAccount", align: "center" },
  { 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 getLawFirmPage(newParams);
};

const dataCallback = (data: any) => {
  const total = Number(data.total) || 0;
  tableTotal.value = total;
  return {
    list: data.records,
    total
  };
};

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

const splitPayment = (value: string) => {
  if (!value) return [];
  return value
    .split(",")
    .map(card => card.trim())
    .filter(Boolean);
};

const formatCard = (card: string) => {
  return card
    .replace(/\s+/g, "")
    .replace(/(.{4})/g, "$1 ")
    .trim();
};

const handleCreate = () => {
  if (!ensureAdmin()) return;
  lawFirmDialogRef.value?.open({
    title: "新增律所",
    onSubmit: async payload => {
      // 防止的修改的参数混入
      let params = {
        creditCode: payload.creditCode,
        directorName: payload.directorName,
        firmName: payload.firmName,
        platformCommissionRatio: payload.platformCommissionRatio,
        paymentList: [
          {
            address: payload.address,
            paymentAccount: payload.paymentAccount
          }
        ]
      };
      await addLawFirm(params);
      ElMessage.success("新增成功");
    }
  });
};

const handleImport = () => {
  if (!ensureAdmin()) return;
  importVisible.value = true;
};

const handleEdit = (row: any) => {
  if (!ensureAdmin()) return;
  lawFirmDialogRef.value?.open({
    title: "编辑律所",
    row,
    onSubmit: async payload => {
      let params = {
        id: row.firmId,
        creditCode: payload.creditCode,
        directorName: payload.directorName,
        firmName: payload.firmName,
        platformCommissionRatio: payload.platformCommissionRatio,
        paymentList: [
          {
            id: row.id,
            address: payload.address,
            paymentAccount: payload.paymentAccount
          }
        ]
      };
      await editLawFirm(params);
      ElMessage.success("编辑成功");
    }
  });
};

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

const handleDownloadTemplate = () => useDownload(downloadLawFirmTemplate, "律所导入模板");

const handleImportSubmit = (formData: FormData) => importData(formData);

const handleImportSuccess = () => {
  refreshTable();
};

const buildExportParams = (override: Record<string, any> = {}) => {
  const searchParam = proTable.value?.searchParam ? { ...proTable.value.searchParam } : {};
  const pageable = proTable.value?.pageable
    ? { page: proTable.value.pageable.pageNum, size: proTable.value.pageable.pageSize }
    : { page: 1, size: 10 };
  const params: Record<string, any> = {
    ...searchParam,
    ...pageable,
    ...override
  };
  if (!isAdmin.value && loginFirmId.value) {
    params.firmId = loginFirmId.value;
  }
  return params;
};

const handleExport = async () => {
  if (!ensureAdmin()) {
    return;
  }
  if (!hasExportableData.value) {
    ElMessage.warning("暂无可导出的数据");
    return;
  }
  exportLoading.value = true;
  try {
    const params = buildExportParams();
    await useDownload(exportLawFirm, "律所列表", params);
  } finally {
    exportLoading.value = false;
  }
};

const handleExportAll = async () => {
  if (!ensureAdmin()) {
    return;
  }
  if (!hasExportableData.value) {
    ElMessage.warning("暂无可导出的数据");
    return;
  }
  exportAllLoading.value = true;
  try {
    const params = buildExportParams({
      page: 1,
      size: Math.max(tableTotal.value, 1)
    });
    await useDownload(exportLawFirm, "律所列表-全部", params);
  } finally {
    exportAllLoading.value = false;
  }
};

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

<style scoped lang="scss">
.payment-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  justify-content: center;
  width: 100%;
}
</style>
