<template>
  <a-page-header :title="getPageTitle()" @back="() => $router.go(-1)">
    <a-card :bordered="false" :body-style="{ padding: '16px' }">
      <ele-pro-table
        ref="tableRef"
        row-key="rowKey"
        :columns="columns"
        :datasource="datasource"
        :customRow="customRow"
        v-model:selection="selection"
        tool-class="ele-toolbar-form"
        class="sys-org-table"
      >
        <template #toolbar>
          <a-space class="flex">
            <search
              @search="reload"
              :selection="selection"
              @add="openEdit"
              @remove="removeBatch"
              @batchMove="openMove"
              @importData="openImport"
              @exportData="exportData"
            />
            <a-button type="dashed" class="ele-btn-icon" @click="openImport2">
              <template #icon>
                <CloudUploadOutlined />
              </template>
              <span class="text-red-500">导入历史被执行人</span>
            </a-button>
          </a-space>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'image'">
            <a-image :src="record.image" :width="50" />
          </template>
          <template v-if="column.key === 'caseNumber'">
            <template v-if="record.historyId">
              <span class="text-red-500 font-bold">{{
                record.caseNumber
              }}</span>
            </template>
            <template v-else>
              {{ record.caseNumber }}
            </template>
          </template>
          <template v-if="column.key === 'name'">
            <template v-if="record.url">
              <a :href="record.url" target="_blank">{{ record.name }}</a>
            </template>
            <template v-else>
              {{ record.name }}
            </template>
          </template>
          <template v-if="column.key === 'dataStatus'">
            <div :class="record.historyId ? 'text-red-500 font-bold' : ''">
              {{ record.dataStatus || (record.historyId ? '有效' : '') }}
            </div>
          </template>
          <template v-if="column.key === 'status'">
            <a-tag v-if="record.status === 0" color="green">显示</a-tag>
            <a-tag v-if="record.status === 1" color="red">隐藏</a-tag>
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a
                @click="
                  record.__source === 'B' ? openEdit2(record) : openEdit(record)
                "
                >修改</a
              >
              <a-divider type="vertical" />
              <a-popconfirm
                title="确定要删除此记录吗？"
                @confirm="remove(record)"
              >
                <a class="ele-text-danger">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </ele-pro-table>
    </a-card>

    <!-- 编辑弹窗 -->
    <CreditJudgmentDebtorEdit
      v-model:visible="showEdit"
      :data="current"
      @done="reload"
    />
    <!-- 导入弹窗 -->
    <CreditJudgmentDebtorImport v-model:visible="showImport" @done="reload" />
    <!-- 历史被执行人导入弹窗 -->
    <CreditJudgmentDebtorHistoryImport
      v-model:visible="showImport2"
      @done="reload"
    />
    <!-- 编辑弹窗 -->
    <CreditJudgmentDebtorHistoryEdit
      v-model:visible="showEdit2"
      :data="current"
      @done="reload"
    />
  </a-page-header>
</template>

<script lang="ts" setup>
  import { createVNode, ref } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import { CloudUploadOutlined } from '@ant-design/icons-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import type { EleProTable } from 'ele-admin-pro';
  import { toDateString } from 'ele-admin-pro';
  import type {
    DatasourceFunction,
    ColumnItem
  } from 'ele-admin-pro/es/ele-pro-table/types';
  import Search from '@/views/credit/components/CreditSearchToolbar.vue';
  import { exportCreditData } from '../utils/export';
  import { getPageTitle } from '@/utils/common';
  import CreditJudgmentDebtorEdit from './components/creditJudgmentDebtorEdit.vue';
  import CreditJudgmentDebtorHistoryEdit from '@/views/credit/creditJudgmentDebtorHistory/components/creditJudgmentDebtorHistoryEdit.vue';
  import CreditJudgmentDebtorImport from './components/credit-judgment-debtor-import.vue';
  import CreditJudgmentDebtorHistoryImport from './components/credit-judgment-debtor-history-import.vue';
  import {
    listCreditJudgmentDebtor,
    removeCreditJudgmentDebtor,
    removeBatchCreditJudgmentDebtor
  } from '@/api/credit/creditJudgmentDebtor';
  import {
    listCreditJudgmentDebtorHistory,
    removeCreditJudgmentDebtorHistory,
    removeBatchCreditJudgmentDebtorHistory
  } from '@/api/credit/creditJudgmentDebtorHistory';
  import type {
    CreditJudgmentDebtor,
    CreditJudgmentDebtorParam
  } from '@/api/credit/creditJudgmentDebtor/model';
  import type { CreditJudgmentDebtorHistory } from '@/api/credit/creditJudgmentDebtorHistory/model';

  // 表格实例
  const tableRef = ref<InstanceType<typeof EleProTable> | null>(null);

  type CreditJudgmentDebtorTableRecord =
    | (CreditJudgmentDebtor & { rowKey: string; __source: 'A' })
    | (CreditJudgmentDebtorHistory & {
        rowKey: string;
        __source: 'B';
        // For red提示 + dblclick open history edit
        historyId: number;
      });

  // 表格选中数据
  const selection = ref<CreditJudgmentDebtorTableRecord[]>([]);
  // 当前编辑数据
  const current = ref<CreditJudgmentDebtorTableRecord | null>(null);
  // 是否显示编辑弹窗
  const showEdit = ref(false);
  // 是否显示编辑弹窗2
  const showEdit2 = ref(false);
  // 是否显示导入弹窗
  const showImport = ref(false);
  // 是否显示历史被执行人导入弹窗
  const showImport2 = ref(false);
  // 是否显示批量移动弹窗
  const showMove = ref(false);
  // 加载状态
  const loading = ref(true);
  // 搜索关键词
  const searchText = ref('');

  const normalizeCaseNumber = (caseNumber?: string) =>
    (caseNumber ?? '').trim();

  const mergeByCaseNumber = (
    aList: CreditJudgmentDebtor[],
    bList: CreditJudgmentDebtorHistory[]
  ): CreditJudgmentDebtorTableRecord[] => {
    const map = new Map<string, CreditJudgmentDebtorTableRecord>();

    aList.forEach((a, idx) => {
      const key = normalizeCaseNumber(a.caseNumber) || `__A__${a.id ?? idx}`;
      map.set(key, {
        ...(a as any),
        rowKey: `A-${a.id ?? key}`,
        __source: 'A'
      });
    });

    // B overrides A when caseNumber duplicates
    bList.forEach((b, idx) => {
      const key = normalizeCaseNumber(b.caseNumber) || `__B__${b.id ?? idx}`;
      map.set(key, {
        ...(b as any),
        rowKey: `B-${b.id ?? key}`,
        __source: 'B',
        historyId: b.id as number
      });
    });

    return Array.from(map.values());
  };

  const sortList = (
    list: CreditJudgmentDebtorTableRecord[],
    orders?: Record<string, any>
  ) => {
    const sortField = orders?.sort;
    const sortOrder: string | undefined = orders?.order;
    if (!sortField || !sortOrder) {
      return list;
    }
    const desc = String(sortOrder).toLowerCase().startsWith('desc');
    return [...list].sort((a: any, b: any) => {
      const av = a?.[sortField];
      const bv = b?.[sortField];
      if (av == null && bv == null) return 0;
      if (av == null) return desc ? 1 : -1;
      if (bv == null) return desc ? -1 : 1;
      if (typeof av === 'number' && typeof bv === 'number') {
        return desc ? bv - av : av - bv;
      }
      const as = String(av);
      const bs = String(bv);
      return desc ? bs.localeCompare(as) : as.localeCompare(bs);
    });
  };

  // 表格数据源
  const datasource: DatasourceFunction = ({
    page,
    limit,
    where = {},
    orders,
    filters
  }) => {
    const params: CreditJudgmentDebtorParam = { ...where };
    if (filters) {
      (params as any).status = filters.status;
    }
    if (!params.keywords && searchText.value) {
      params.keywords = searchText.value;
    }

    // Client-side merge A+B by caseNumber, with B override.
    return Promise.all([
      listCreditJudgmentDebtor(params),
      listCreditJudgmentDebtorHistory(params as any)
    ]).then(([aList, bList]) => {
      const merged = sortList(mergeByCaseNumber(aList, bList), orders as any);
      const currentPage = page ?? 1;
      const pageSize = limit ?? 20;
      const start = (currentPage - 1) * pageSize;
      return {
        list: merged.slice(start, start + pageSize),
        count: merged.length
      };
    });
  };

  // 关键信息列
  const columns = ref<ColumnItem[]>([
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80
    },
    {
      title: '案号',
      dataIndex: 'caseNumber',
      key: 'caseNumber',
      ellipsis: true
    },
    {
      title: '被执行人名称',
      dataIndex: 'name',
      key: 'name',
      ellipsis: true
    },
    // {
    //   title: '证件号/组织机构代码',
    //   dataIndex: 'code',
    //   key: 'code',
    //   ellipsis: true
    // },
    {
      title: '执行标的(元)',
      dataIndex: 'amount',
      key: 'amount',
      width: 120
    },
    {
      title: '执行法院',
      dataIndex: 'courtName',
      key: 'courtName',
      ellipsis: true
    },
    {
      title: '立案日期',
      dataIndex: 'occurrenceTime',
      key: 'occurrenceTime',
      width: 120
    },
    // {
    //   title: '状态',
    //   dataIndex: 'dataStatus',
    //   key: 'dataStatus',
    //   ellipsis: true,
    //   align: 'center',
    //   width: 90
    // },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 180,
      align: 'center',
      ellipsis: true,
      customRender: ({ text }) => toDateString(text, 'yyyy-MM-dd HH:mm:ss')
    },
    // {
    //   title: '操作',
    //   key: 'action',
    //   width: 160,
    //   fixed: 'right',
    //   align: 'center',
    //   hideInSetting: true
    // }
  ]);

  /* 搜索 */
  const reload = (where?: CreditJudgmentDebtorParam) => {
    if (where && Object.prototype.hasOwnProperty.call(where, 'keywords')) {
      searchText.value = where.keywords ?? '';
    }
    const targetWhere = where ?? { keywords: searchText.value || undefined };
    selection.value = [];
    tableRef?.value?.reload({ where: targetWhere });
  };

  /* 打开编辑弹窗 */
  const openEdit = (row?: CreditJudgmentDebtorTableRecord) => {
    current.value = row ?? null;
    showEdit.value = true;
  };

  /* 打开批量移动弹窗 */
  const openMove = () => {
    showMove.value = true;
  };

  /* 打开导入弹窗 */
  const openImport = () => {
    showImport.value = true;
  };

  /* 打开历史被执行人导入弹窗 */
  const openImport2 = () => {
    showImport2.value = true;
  };

  /* 打开编辑弹窗 */
  const openEdit2 = (row?: CreditJudgmentDebtorTableRecord) => {
    current.value = row ?? null;
    showEdit2.value = true;
  };

  /* 导出 */
  const exportData = () => {
    exportCreditData<CreditJudgmentDebtor>({
      filename: '被执行人',
      columns: [
        { title: 'ID', dataIndex: 'id' },
        { title: '案号', dataIndex: 'caseNumber' },
        { title: '被执行人名称', dataIndex: 'name' },
        { title: '证件号/组织机构代码', dataIndex: 'code' },
        { title: '立案日期', dataIndex: 'occurrenceTime' },
        { title: '执行标的(元)', dataIndex: 'amount' },
        { title: '法院', dataIndex: 'courtName' },
        { title: '数据状态', dataIndex: 'dataStatus' },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          formatter: (record: CreditJudgmentDebtor) =>
            record.createTime
              ? toDateString(record.createTime, 'yyyy-MM-dd HH:mm:ss')
              : ''
        }
      ],
      fetchData: () =>
        Promise.all([
          listCreditJudgmentDebtor({ keywords: searchText.value || undefined }),
          listCreditJudgmentDebtorHistory({
            keywords: searchText.value || undefined
          } as any)
        ]).then(([aList, bList]) => mergeByCaseNumber(aList, bList) as any)
    });
  };

  /* 删除单个 */
  const remove = (row: CreditJudgmentDebtorTableRecord) => {
    const hide = message.loading('请求中..', 0);
    const isHistory = (row as any).__source === 'B';
    const removeFn = isHistory
      ? removeCreditJudgmentDebtorHistory
      : removeCreditJudgmentDebtor;
    removeFn((row as any).id)
      .then((msg) => {
        hide();
        message.success(msg);
        reload();
      })
      .catch((e) => {
        hide();
        message.error(e.message);
      });
  };

  /* 批量删除 */
  const removeBatch = () => {
    if (!selection.value.length) {
      message.error('请至少选择一条数据');
      return;
    }
    Modal.confirm({
      title: '提示',
      content: '确定要删除选中的记录吗?',
      icon: createVNode(ExclamationCircleOutlined),
      maskClosable: true,
      onOk: () => {
        const hide = message.loading('请求中..', 0);
        const aIds: (number | undefined)[] = [];
        const bIds: (number | undefined)[] = [];
        selection.value.forEach((d: any) => {
          if (d.__source === 'B') {
            bIds.push(d.id);
          } else {
            aIds.push(d.id);
          }
        });
        return Promise.all([
          aIds.length
            ? removeBatchCreditJudgmentDebtor(aIds)
            : Promise.resolve(''),
          bIds.length
            ? removeBatchCreditJudgmentDebtorHistory(bIds)
            : Promise.resolve('')
        ])
          .then(() => {
            hide();
            message.success('删除成功');
            reload();
          })
          .catch((e) => {
            hide();
            message.error(e.message);
          });
      }
    });
  };

  /* 查询 */
  const query = () => {
    loading.value = true;
  };

  /* 自定义行属性 */
  const customRow = (record: CreditJudgmentDebtorTableRecord) => {
    return {
      // 行点击事件
      onClick: () => {
        // console.log(record);
      },
      // 行双击事件
      onDblclick: () => {
        if ((record as any).__source !== 'B') {
          openEdit(record);
        } else {
          openEdit2(record);
        }
      }
    };
  };
  query();
</script>

<script lang="ts">
  export default {
    name: 'CreditJudgmentDebtor'
  };
</script>

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