import React, { useState } from "react";
import { Table } from "@tencent/tea-component";

const { sortable } = Table.addons;

const records = [
  {
    name: "Link",
    age: 20,
    contact: { phone: "88886666", mail: "link@qq.com" },
  },
  {
    name: "Zelda",
    age: 18,
    contact: { phone: "66668888", mail: "zelda@qq.com" },
  },
  {
    name: "Mario",
    age: 38,
    contact: { phone: "88881111", mail: "mario@qq.com" },
  },
  {
    name: "Luigi",
    age: 48,
    contact: { phone: "8123456", mail: "luigi@qq.com" },
  },
];

export default function TableAddonExample() {
  // 当前排序列
  const [sorts, setSorts] = useState([]);
  return (
    <Table
      // 如果要在前端排序，可以用 sortable.comparer 生成默认的排序方法
      records={[...records].sort(sortable.comparer(sorts))}
      recordKey="name"
      columns={[
        { key: "name", header: "姓名" },
        { key: "age", header: "年龄" },
        { key: "contact.mail", header: "邮箱" },
        { key: "contact.phone", header: "电话" },
      ]}
      addons={[
        sortable({
          // 这两列支持排序，其中 age 列优先倒序，mail 采用自定义排序方法
          columns: [
            "name",
            {
              key: "age",
              prefer: "desc",
            },
            "contact.mail",
            {
              key: "contact.phone",
              prefer: "desc",
              sorter: (first, second) => {
                if (+first.contact.phone > +second.contact.phone) return 1;
                if (+first.contact.phone < +second.contact.phone) return -1;
                return 0;
              },
            },
          ],
          value: sorts,
          onChange: value => setSorts(value),
        }),
      ]}
    />
  );
}
