<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="id"
        :columns="columns"
        :datasource="datasource"
        :customRow="customRow"
        tool-class="ele-toolbar-form"
        class="sys-org-table"
      >
        <template #toolbar>
          <search
            @search="reload"
            :selection="selection"
            @viewTree="viewRefereeTree"
            @export="exportData"
          />
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'dealerInfo'">
            <div class="user-info">
              <div class="user-id"
                >{{ record.dealerName }}({{ record.dealerId }})</div
              >
              <div class="user-id"></div>
              <div class="user-role">
                <a-tag color="blue">推荐人</a-tag>
              </div>
            </div>
          </template>

          <template v-if="column.key === 'relationship'">
            <ArrowRightOutlined />
          </template>

          <template v-if="column.key === 'userInfo'">
            <div class="user-info">
              <div class="user-id"
                >{{ record.nickname }}({{ record.userId }})</div
              >
              <div class="user-role">
                <a-tag color="green">被推荐人</a-tag>
              </div>
            </div>
          </template>

          <template v-if="column.key === 'level'">
            <a-tag :color="getLevelColor(record.level || 0)" class="level-tag">
              {{ getLevelText(record.level || 0) }}
            </a-tag>
          </template>

          <template v-if="column.key === 'relationChain'">
            <a-button
              type="link"
              size="small"
              @click="viewRelationChain(record)"
              class="chain-btn"
            >
              <TeamOutlined /> 查看关系链
            </a-button>
          </template>

          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="openEdit(record)" class="ele-text-primary">
                <EditOutlined /> 编辑
              </a>
              <!--                <a-divider type="vertical" />-->
              <!--                <a-popconfirm-->
              <!--                  title="确定要解除此推荐关系吗？"-->
              <!--                  @confirm="remove(record)"-->
              <!--                  placement="topRight"-->
              <!--                >-->
              <!--                  <a class="ele-text-danger">-->
              <!--                    <DisconnectOutlined /> 解除-->
              <!--                  </a>-->
              <!--                </a-popconfirm>-->
            </a-space>
          </template>
        </template>
      </ele-pro-table>
    </a-card>

    <!-- 编辑弹窗 -->
    <ShopDealerRefereeEdit
      v-model:visible="showEdit"
      :data="current"
      @done="reload"
    />

    <!-- 树状图弹窗 -->
    <RefereeTree
      v-model:visible="showTree"
      :data="treeData"
      :title="'推荐关系树'"
      @cancel="showTree = false"
    />
  </a-page-header>
</template>

<script lang="ts" setup>
  import { createVNode, ref } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import {
    ExclamationCircleOutlined,
    TeamOutlined,
    EditOutlined,
    ArrowRightOutlined
  } 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 './components/search.vue';
  import { getPageTitle } from '@/utils/common';
  import ShopDealerRefereeEdit from './components/shopDealerRefereeEdit.vue';
  import RefereeTree from './components/RefereeTree.vue';
  import { utils, writeFile } from 'xlsx';
  import {
    pageShopDealerReferee,
    removeShopDealerReferee,
    removeBatchShopDealerReferee,
    listShopDealerReferee
  } from '@/api/shop/shopDealerReferee';
  import type {
    ShopDealerReferee,
    ShopDealerRefereeParam
  } from '@/api/shop/shopDealerReferee/model';

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

  // 表格选中数据
  const selection = ref<ShopDealerReferee[]>([]);
  // 当前编辑数据
  const current = ref<ShopDealerReferee | null>(null);
  // 是否显示编辑弹窗
  const showEdit = ref(false);
  // 是否显示树状图弹窗
  const showTree = ref(false);
  // 树状图数据
  const treeData = ref<ShopDealerReferee[]>([]);
  // 加载状态
  const loading = ref(true);

  // 表格数据源
  const datasource: DatasourceFunction = ({
    page,
    limit,
    where,
    orders,
    filters
  }) => {
    if (filters) {
      where.status = filters.status;
    }
    return pageShopDealerReferee({
      ...where,
      ...orders,
      page,
      limit
    });
  };

  // 表格列配置
  const columns = ref<ColumnItem[]>([
    {
      title: '推荐人信息',
      key: 'dealerInfo',
      align: 'left',
      width: 150
    },
    {
      title: '',
      key: 'relationship',
      align: 'center',
      width: 50
    },
    {
      title: '被推荐人信息',
      key: 'userInfo',
      align: 'left',
      width: 150
    },
    // {
    //   title: '推荐层级',
    //   key: 'level',
    //   align: 'center',
    //   width: 120,
    //   filters: [
    //     { text: '一级推荐', value: 1 },
    //     { text: '二级推荐', value: 2 },
    //     { text: '三级推荐', value: 3 }
    //   ]
    // },
    {
      title: '建立时间',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center',
      width: 120,
      sorter: true,
      customRender: ({ text }) => toDateString(text, 'yyyy-MM-dd HH:mm')
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      fixed: 'right',
      align: 'center',
      hideInSetting: true
    }
  ]);

  /* 获取层级颜色 */
  const getLevelColor = (level: number) => {
    const colors = {
      1: 'red',
      2: 'orange',
      3: 'gold'
    };
    return colors[level] || 'default';
  };

  /* 获取层级文本 */
  const getLevelText = (level: number) => {
    const texts = {
      1: '一级推荐',
      2: '二级推荐',
      3: '三级推荐'
    };
    return texts[level] || `${level}级推荐`;
  };

  /* 查看关系链 */
  const viewRelationChain = (record: ShopDealerReferee) => {
    // 这里可以调用API获取完整的推荐关系链
    Modal.info({
      title: '推荐关系链',
      width: 800,
      content: createVNode('div', { class: 'relation-chain' }, [
        createVNode('div', { class: 'chain-item' }, [
          createVNode('div', { class: 'chain-node dealer' }, [
            createVNode('div', { class: 'node-title' }, '推荐人'),
            createVNode(
              'div',
              { class: 'node-id' },
              `用户ID: ${record.dealerId}`
            ),
            createVNode('div', { class: 'node-level' }, '分销商')
          ]),
          createVNode('div', { class: 'chain-arrow' }, '→'),
          createVNode('div', { class: 'chain-node user' }, [
            createVNode('div', { class: 'node-title' }, '被推荐人'),
            createVNode(
              'div',
              { class: 'node-id' },
              `用户ID: ${record.userId}`
            ),
            createVNode(
              'div',
              { class: 'node-level' },
              getLevelText(record.level || 0)
            )
          ])
        ]),
        createVNode('div', { class: 'chain-info' }, [
          createVNode(
            'p',
            null,
            `推荐关系建立于: ${toDateString(
              record.createTime,
              'yyyy-MM-dd HH:mm:ss'
            )}`
          ),
          createVNode('p', null, '点击可查看更多上下级关系')
        ])
      ]),
      okText: '关闭'
    });
  };

  /* 查看推荐树 */
  const viewRefereeTree = () => {
    // 加载所有数据用于树状图展示
    loading.value = true;
    pageShopDealerReferee({ page: 1, limit: 10000 }) // 获取所有数据
      .then((result) => {
        treeData.value = result?.list || [];
        showTree.value = true;
        loading.value = false;
      })
      .catch((e) => {
        loading.value = false;
        message.error('加载数据失败: ' + e.message);
      });
  };

  /* 导出数据 */
  const exportData = async () => {
    try {
      // 定义表头
      const array: (string | number)[][] = [
        [
          '推荐人',
          '推荐人ID',
          '推荐人电话',
          '被推荐人',
          '被推荐人ID',
          '被推荐人电话',
          '创建时间'
        ]
      ];

      // 获取用户列表数据
      const list = await listShopDealerReferee({});

      if (!list || list.length === 0) {
        message.warning('没有数据可以导出');
        return;
      }

      // 将数据转换为Excel行
      list.forEach((user: ShopDealerReferee) => {
        array.push([
          `${user.dealerName}`,
          `${user.dealerId}`,
          `${user.dealerPhone}`,
          `${user.nickname}`,
          `${user.userId}`,
          `${user.phone}`,
          `${user.createTime}`
        ]);
      });

      // 生成Excel文件
      const sheetName = `shop_dealer_referee`;
      const workbook = {
        SheetNames: [sheetName],
        Sheets: {}
      };
      const sheet = utils.aoa_to_sheet(array);
      workbook.Sheets[sheetName] = sheet;

      // 设置列宽
      sheet['!cols'] = [
        { wch: 10 }, // 用户ID
        { wch: 15 } // 账号
      ];

      message.loading('正在生成Excel文件...', 0);

      setTimeout(() => {
        writeFile(workbook, `${sheetName}.xlsx`);
        message.destroy();
        message.success(`成功导出 ${list.length} 条记录`);
      }, 1000);
    } catch (error: any) {
      message.error(error.message || '导出失败');
    }
  };

  /* 搜索 */
  const reload = (where?: ShopDealerRefereeParam) => {
    selection.value = [];
    tableRef?.value?.reload({ where: where });
  };

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

  /* 删除单个 */
  const remove = (row: ShopDealerReferee) => {
    const hide = message.loading('请求中..', 0);
    removeShopDealerReferee(row.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);
        removeBatchShopDealerReferee(selection.value.map((d) => d.id))
          .then((msg) => {
            hide();
            message.success(msg);
            reload();
          })
          .catch((e) => {
            hide();
            message.error(e.message);
          });
      }
    });
  };

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

  /* 自定义行属性 */
  const customRow = (record: ShopDealerReferee) => {
    return {
      // 行点击事件
      onClick: () => {
        // console.log(record);
      },
      // 行双击事件
      onDblclick: () => {
        openEdit(record);
      }
    };
  };
  query();
</script>

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

<style lang="less" scoped>
  .user-info {
    .user-id {
      font-weight: 500;
      color: #333;
      margin-bottom: 4px;
    }

    .user-role {
      font-size: 12px;
    }
  }

  .level-tag {
    font-weight: 600;
    font-size: 12px;
  }

  .chain-btn {
    padding: 0;
    height: auto;
    font-size: 12px;
  }

  :deep(.referee-detail) {
    .detail-section {
      h4 {
        color: #1890ff;
        margin-bottom: 12px;
        border-bottom: 1px solid #f0f0f0;
        padding-bottom: 8px;
      }

      p {
        margin: 8px 0;
        line-height: 1.6;
      }

      .level-badge {
        font-size: 14px;
      }
    }
  }

  :deep(.relation-chain) {
    .chain-item {
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 20px 0;
    }

    .chain-node {
      padding: 16px;
      border-radius: 8px;
      text-align: center;
      min-width: 120px;

      &.dealer {
        background: #e6f7ff;
        border: 2px solid #1890ff;
      }

      &.user {
        background: #f6ffed;
        border: 2px solid #52c41a;
      }

      .node-title {
        font-weight: 600;
        color: #333;
        margin-bottom: 8px;
      }

      .node-id {
        color: #666;
        font-size: 12px;
        margin-bottom: 4px;
      }

      .node-level {
        font-size: 12px;
        color: #999;
      }
    }

    .chain-arrow {
      font-size: 24px;
      color: #1890ff;
      margin: 0 20px;
      font-weight: bold;
    }

    .chain-info {
      background: #fafafa;
      padding: 12px;
      border-radius: 6px;
      margin-top: 16px;

      p {
        margin: 4px 0;
        color: #666;
        font-size: 12px;
      }
    }
  }

  :deep(.ant-table-tbody > tr > td) {
    vertical-align: top;
  }

  :deep(.ant-tag) {
    margin: 2px 4px 2px 0;
  }
</style>
