<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="shopDealerUserId"
        :columns="columns"
        :datasource="datasource"
        :customRow="customRow"
        tool-class="ele-toolbar-form"
        class="sys-org-table"
      >
        <template #toolbar>
          <search
            @search="reload"
            :selection="selection"
            @add="openEdit"
            @remove="removeBatch"
            @batchMove="openMove"
          />
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'userStatus'">
            <a-tag v-if="record.isDelete === 1" color="red">已删除</a-tag>
            <a-tag v-else color="green">正常</a-tag>
          </template>
          <template v-if="column.key === 'action'">
            <a @click="openEdit(record)" class="ele-text-primary">
              <EditOutlined/>
              编辑
            </a>
            <a-divider type="vertical"/>
            <a @click="viewDetail(record)" class="ele-text-info">
              <EyeOutlined/>
              详情
            </a>
            <a-divider type="vertical"/>
            <a-popconfirm
              title="确定要删除此分销商用户吗？"
              @confirm="remove(record)"
              placement="topRight"
            >
              <a class="ele-text-danger">
                <DeleteOutlined/>
                删除
              </a>
            </a-popconfirm>
          </template>
        </template>
      </ele-pro-table>
    </a-card>

    <!-- 编辑弹窗 -->
    <ShopDealerUserEdit v-model:visible="showEdit" :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 {
  ExclamationCircleOutlined,
  EditOutlined,
  EyeOutlined,
  DeleteOutlined
} 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 ShopDealerUserEdit from './components/shopDealerUserEdit.vue';
import {pageShopDealerUser, removeShopDealerUser, removeBatchShopDealerUser} from '@/api/shop/shopDealerUser';
import type {ShopDealerUser, ShopDealerUserParam} from '@/api/shop/shopDealerUser/model';

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

// 表格选中数据
const selection = ref<ShopDealerUser[]>([]);
// 当前编辑数据
const current = ref<ShopDealerUser | null>(null);
// 是否显示编辑弹窗
const showEdit = ref(false);
// 是否显示批量移动弹窗
const showMove = ref(false);
// 加载状态
const loading = ref(true);

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

// 表格列配置
const columns = ref<ColumnItem[]>([
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    align: 'center',
    width: 80,
    fixed: 'left'
  },
  {
    title: '用户信息',
    key: 'userInfo',
    align: 'left',
    width: 200,
    fixed: 'left',
    customRender: ({record}) => {
      return `${record.realName || '-'} (${record.mobile || '-'})`;
    }
  },
  {
    title: '佣金统计',
    key: 'commissionStats',
    align: 'center',
    width: 180,
    customRender: ({record}) => {
      const available = parseFloat(record.money || '0').toFixed(2);
      const frozen = parseFloat(record.freezeMoney || '0').toFixed(2);
      const total = parseFloat(record.totalMoney || '0').toFixed(2);
      return `可提现: ¥${available} | 冻结: ¥${frozen} | 累计: ¥${total}`;
    }
  },
  {
    title: '团队统计',
    key: 'teamStats',
    align: 'center',
    width: 150,
    customRender: ({record}) => {
      const first = record.firstNum || 0;
      const second = record.secondNum || 0;
      const third = record.thirdNum || 0;
      const total = first + second + third;
      return `总计: ${total} (${first}/${second}/${third})`;
    }
  },
  {
    title: '推荐人',
    dataIndex: 'refereeId',
    key: 'refereeId',
    align: 'center',
    width: 100,
    customRender: ({text}) => text ? `ID: ${text}` : '无'
  },
  {
    title: '专属二维码',
    dataIndex: 'qrcode',
    key: 'qrcode',
    align: 'center',
    width: 120,
    customRender: ({text}) => {
      return text ? '已生成' : '未生成';
    }
  },
  {
    title: '状态',
    key: 'userStatus',
    align: 'center',
    width: 100,
    customRender: ({record}) => {
      if (record.isDelete === 1) {
        return {type: 'tag', props: {color: 'red'}, children: '已删除'};
      }
      return {type: 'tag', props: {color: 'green'}, children: '正常'};
    }
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    align: 'center',
    width: 120,
    sorter: true,
    ellipsis: true,
    customRender: ({text}) => text ? toDateString(text, 'yyyy-MM-dd') : '-'
  },
  {
    title: '操作',
    key: 'action',
    width: 220,
    fixed: 'right',
    align: 'center',
    hideInSetting: true
  }
]);

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

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

/* 查看详情 */
const viewDetail = (row: ShopDealerUser) => {
  Modal.info({
    title: '分销商用户详情',
    width: 600,
    content: createVNode('div', {style: 'max-height: 400px; overflow-y: auto;'}, [
      createVNode('div', {class: 'detail-item'}, [
        createVNode('strong', null, '基本信息'),
        createVNode('p', null, `姓名: ${row.realName || '-'}`),
        createVNode('p', null, `手机号: ${row.mobile || '-'}`),
        createVNode('p', null, `用户ID: ${row.userId || '-'}`),
        createVNode('p', null, `推荐人ID: ${row.refereeId || '无'}`),
      ]),
      createVNode('div', {class: 'detail-item', style: 'margin-top: 16px;'}, [
        createVNode('strong', null, '佣金信息'),
        createVNode('p', null, `可提现佣金: ¥${parseFloat(row.money || '0').toFixed(2)}`),
        createVNode('p', null, `冻结佣金: ¥${parseFloat(row.freezeMoney || '0').toFixed(2)}`),
        createVNode('p', null, `累计提现: ¥${parseFloat(row.totalMoney || '0').toFixed(2)}`),
      ]),
      createVNode('div', {class: 'detail-item', style: 'margin-top: 16px;'}, [
        createVNode('strong', null, '团队信息'),
        createVNode('p', null, `一级成员: ${row.firstNum || 0} 人`),
        createVNode('p', null, `二级成员: ${row.secondNum || 0} 人`),
        createVNode('p', null, `三级成员: ${row.thirdNum || 0} 人`),
        createVNode('p', null, `团队总数: ${(row.firstNum || 0) + (row.secondNum || 0) + (row.thirdNum || 0)} 人`),
      ]),
      createVNode('div', {class: 'detail-item', style: 'margin-top: 16px;'}, [
        createVNode('strong', null, '其他信息'),
        createVNode('p', null, `专属二维码: ${row.qrcode ? '已生成' : '未生成'}`),
        createVNode('p', null, `创建时间: ${row.createTime ? toDateString(row.createTime, 'yyyy-MM-dd HH:mm:ss') : '-'}`),
        createVNode('p', null, `更新时间: ${row.updateTime ? toDateString(row.updateTime, 'yyyy-MM-dd HH:mm:ss') : '-'}`),
      ])
    ]),
    okText: '关闭'
  });
};

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

/* 删除单个 */
const remove = (row: ShopDealerUser) => {
  if (!row.id) {
    message.error('删除失败：缺少必要参数');
    return;
  }

  const hide = message.loading('正在删除分销商用户...', 0);
  removeShopDealerUser(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;
  }

  const validIds = selection.value.filter(d => d.id).map(d => d.id);
  if (!validIds.length) {
    message.error('选中的数据中没有有效的ID');
    return;
  }

  Modal.confirm({
    title: '批量删除确认',
    content: `确定要删除选中的 ${validIds.length} 条分销商用户记录吗？此操作不可恢复。`,
    icon: createVNode(ExclamationCircleOutlined),
    maskClosable: true,
    okText: '确认删除',
    okType: 'danger',
    cancelText: '取消',
    onOk: () => {
      const hide = message.loading(`正在删除 ${validIds.length} 条记录...`, 0);
      removeBatchShopDealerUser(validIds)
        .then((msg) => {
          hide();
          message.success(msg || `成功删除 ${validIds.length} 条记录`);
          selection.value = [];
          reload();
        })
        .catch((e) => {
          hide();
          message.error(e.message || '批量删除失败');
        });
    }
  });
};

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

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

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

<style lang="less" scoped>
.sys-org-table {
  :deep(.ant-table-thead > tr > th) {
    background-color: #fafafa;
    font-weight: 600;
  }

  :deep(.ant-table-tbody > tr:hover > td) {
    background-color: #f8f9fa;
  }
}

.detail-item {
  p {
    margin: 4px 0;
    color: #666;
  }

  strong {
    color: #1890ff;
    font-size: 14px;
  }
}

.ele-text-primary {
  color: #1890ff;

  &:hover {
    color: #40a9ff;
  }
}

.ele-text-info {
  color: #13c2c2;

  &:hover {
    color: #36cfc9;
  }
}

.ele-text-danger {
  color: #ff4d4f;

  &:hover {
    color: #ff7875;
  }
}
</style>
