<template>
  <app-view class="home-cart">
    <template #header>
      <app-navbar title="订单" :show-back-button="false"></app-navbar>
    </template>
    <div class="home-cart__container">
      <Empty description="暂无数据" />
      <table ref="dragTable" class="app-table__body" cellspacing="0" cellpadding="0"
        style="width:100%;text-align:center;">
        <thead>
          <tr>
            <th v-for="(column, i) in columns" :key="i">
              <Button>{{ column.label }}</Button>
            </th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(row, i) in tableList" :key="i">
            <td v-for="(column, j) in columns" :key="j">
              <Button>{{ row[column.key] }}</Button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </app-view>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { Empty, Button } from 'vant'
import { queryGoodsList } from '@/services/api/goods'
import Sortable from 'sortablejs'

const dragTable = ref<HTMLElement>();
const tableList = ref<Model.ResQueryGoodsList[]>([]);

const columns = [
  {
    key: 'id',
    label: '序号',
  },
  {
    key: 'goodsCode',
    label: '合约',
  },
  {
    key: 'goodsName',
    label: '商品',
  },
  {
    key: 'lastPrice',
    label: '最新价',
  }
]

queryGoodsList().then((res) => {
  tableList.value = res.data;
})

onMounted(() => {
  const el = dragTable.value
  if (el) {
    const getHeader = () => el.querySelector('thead tr') as HTMLElement;
    const getRows = () => el.querySelectorAll('tbody tr');

    new Sortable(getHeader(), {
      animation: 150,
      draggable: 'th',
      onStart: (e) => {
        const columns: HTMLTableCellElement[] = [];
        const rows = getRows();

        rows.forEach((row) => {
          const cells = row.querySelectorAll('td');
          if (e.oldIndex !== undefined) {
            columns.push(cells[e.oldIndex]);
          }
        })

        console.log(e, columns.map((e) => e.innerText));
      },
    })
  }
})
</script>

<style lang="less">
@import './index.less';
</style>