<template>
  <div class="rate-table-container">
    <div class="serialization-section">
      <div
        class="section-header"
        @click="isJsonEditorCollapsed = !isJsonEditorCollapsed"
      >
        <a-typography-text type="secondary">
          批量编辑 (JSON格式) - 与表格实时同步
        </a-typography-text>
        <a-button size="mini" type="text">
          <template #icon>
            <icon-down v-if="isJsonEditorCollapsed" />
            <icon-up v-else />
          </template>
        </a-button>
      </div>

      <a-collapse-transition>
        <div v-show="!isJsonEditorCollapsed">
          <a-space
            direction="vertical"
            style="width: 100%; margin-bottom: 16px"
          >
            <a-textarea
              v-model="serializationData"
              placeholder="在此编辑JSON数据，表格会实时同步更新"
              auto-size
              allow-clear
            />
            <a-space>
              <a-button size="small" status="warning" @click="resetToDefault">
                <template #icon>
                  <icon-refresh />
                </template>
                还原默认
              </a-button>
            </a-space>
          </a-space>
        </div>
      </a-collapse-transition>
    </div>
    <a-table
      :data="tableData"
      :columns="columns"
      class="rate-table"
      :pagination="false"
      column-resizable
      :bordered="{ cell: true }"
    >
      <template #sort="{ rowIndex }">
        <a-input-number v-model="tableData[rowIndex].sort" required />
      </template>
      <template #factLabel="{ rowIndex }">
        <a-input-number
          v-model="tableData[rowIndex].factLabel"
          :precision="2"
          required
        />
      </template>
      <template #showLabel="{ rowIndex }">
        <a-input-number
          v-model="tableData[rowIndex].showLabel"
          :precision="2"
          required
        />
      </template>
      <template #value="{ rowIndex }">
        <a-input-number
          v-model="tableData[rowIndex].value"
          :precision="2"
          required
        />
      </template>
      <template #platformLabel="{ rowIndex }">
        <a-input v-model="tableData[rowIndex].platformLabel" required />
      </template>
      <template #isLinkSingle="{ rowIndex }">
        <a-select v-model="tableData[rowIndex].isLinkSingle" required>
          <a-option :value="true" label="是" />
          <a-option :value="false" label="否" />
        </a-select>
      </template>
      <template #platformFee="{ rowIndex }">
        <a-input-number
          v-model="tableData[rowIndex].platformFee"
          :precision="2"
          required
        />
      </template>
      <template #linkID="{ rowIndex }">
        <a-input v-model="tableData[rowIndex].linkID" required />
      </template>
      <template #action="{ rowIndex }">
        <a-space size="mini">
          <a-button size="small" status="warning" @click="addRecord(rowIndex)">
            <template #icon>
              <icon-plus />
            </template>
          </a-button>
          <a-tooltip content="复制链接">
            <a-button size="small" status="success" @click="openLink(rowIndex)">
              <template #icon>
                <icon-copy />
              </template>
            </a-button>
          </a-tooltip>
          <a-button
            size="small"
            status="danger"
            @click="deleteRecord(rowIndex)"
          >
            <template #icon>
              <icon-delete />
            </template>
          </a-button>
        </a-space>
      </template>
    </a-table>
  </div>
</template>

<script lang="ts" setup>
import { merchantDeployRate } from '@/api/merchant-deploy';
import { openExternalLink } from './data';
import { useClipboard } from '@vueuse/core';
import { TableColumnData } from '@arco-design/web-vue/es/table';
import { Message } from '@arco-design/web-vue';
import { watchEffect, ref, watch } from 'vue';
import { useDebounceFn } from '@vueuse/core';

const generateTableData = () => {
  return {
    factLabel: 0,
    showLabel: 0,
    platformLabel: '',
    isLinkSingle: true,
    value: 0,
    sort: 0,
    platformFee: 0,
    linkID: ''
  };
};
const tableData = defineModel<merchantDeployRate[]>();
const serializationData = ref('');
const isJsonEditorCollapsed = ref(true); // 默认折叠

const { copy } = useClipboard();

const columns: TableColumnData[] = [
  {
    title: '排序',
    dataIndex: 'sort',
    slotName: 'sort'
  },
  {
    title: '面值',
    dataIndex: 'showLabel',
    slotName: 'showLabel'
  },
  {
    title: '售价',
    dataIndex: 'factLabel',
    slotName: 'factLabel'
  },
  {
    title: '平台',
    dataIndex: 'platformLabel',
    slotName: 'platformLabel'
  },
  {
    title: '链接是否单独',
    dataIndex: 'isLinkSingle',
    slotName: 'isLinkSingle'
  },
  {
    title: '折扣率',
    dataIndex: 'value',
    slotName: 'value'
  },
  {
    title: '商户加点',
    dataIndex: 'platformFee',
    slotName: 'platformFee'
  },
  {
    title: '商品链接',
    dataIndex: 'linkID',
    slotName: 'linkID'
  },
  {
    title: '操作',
    dataIndex: 'action',
    slotName: 'action'
  }
];

const addRecord = (rowIndex: number) => {
  tableData.value.splice(rowIndex + 1, 0, generateTableData());
};

watchEffect(() => {
  if (tableData.value?.length === 0) {
    tableData.value.push(generateTableData());
  }
});

// 实时同步：tableData 变化时更新 serializationData
watch(
  tableData,
  newData => {
    try {
      serializationData.value = JSON.stringify(newData, null, 2);
    } catch (error) {
      console.error('序列化失败:', error);
    }
  },
  { deep: true }
);

// 实时同步：serializationData 变化时更新 tableData
const updateTableFromSerialization = useDebounceFn((newData: string) => {
  try {
    if (!newData?.trim()) {
      return;
    }

    const parsedData = JSON.parse(newData);

    if (!Array.isArray(parsedData)) {
      throw new Error('数据格式必须是数组');
    }

    // 验证每个记录的字段
    const validData = parsedData.map((item, index) => {
      if (typeof item !== 'object' || item === null) {
        throw new Error(`第${index + 1}条记录格式不正确`);
      }

      return {
        factLabel: Number(item.factLabel) || 0,
        showLabel: Number(item.showLabel) || 0,
        platformLabel: String(item.platformLabel || ''),
        isLinkSingle: Boolean(item.isLinkSingle ?? true),
        value: Number(item.value) || 0,
        sort: Number(item.sort) || 0,
        platformFee: Number(item.platformFee) || 0,
        linkID: String(item.linkID || '')
      };
    });

    // 避免循环更新，检查数据是否真的发生了变化
    if (JSON.stringify(validData) !== JSON.stringify(tableData.value)) {
      tableData.value = validData;
    }
  } catch (error) {
    // JSON解析失败时静默处理，不影响用户输入
    console.error('反序列化失败:', error);
  }
}, 300);

watch(() => serializationData.value, updateTableFromSerialization);

const openLink = async (rowIndex: number) => {
  const { platformLabel, isLinkSingle, linkID } = tableData.value[rowIndex];
  const link = openExternalLink(platformLabel, isLinkSingle, linkID);
  await copy(link);
  Message.info(`复制链接成功，地址：${link}`);
};

const deleteRecord = (rowIndex: number) => {
  tableData.value.splice(rowIndex, 1);
};

// 还原默认功能
const resetToDefault = () => {
  const defaultData = [
    {
      factLabel: 95,
      showLabel: 100,
      platformLabel: '淘宝',
      isLinkSingle: true,
      value: 0.95,
      sort: 1,
      platformFee: 0,
      linkID: ''
    }
  ];

  tableData.value = defaultData;
  serializationData.value = '';
  Message.success('已还原为默认数据');
};
</script>

<style lang="less">
.rate-table-container {
  .serialization-section {
    background: #f7f8fa;
    padding: 16px;
    border-radius: 6px;
    border: 1px solid #e5e6eb;
    margin-bottom: 16px;

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      cursor: pointer;
      padding: 4px 0;
      transition: background-color 0.2s;

      &:hover {
        background-color: rgb(0 0 0 / 2%);
        border-radius: 4px;
        margin: 0 -4px;
        padding: 4px;
      }
    }

    // 折叠动画容器
    .arco-collapse-transition {
      margin-top: 8px;
    }
  }
}
</style>
