<template>
  <div class="p-4">
    <BasicTable
      ref="tableRef"
      @register="registerTable"
      rowKey="key"
      isTreeTable
    >
      <template #action="{ record, column }">
        <TableAction :actions="createActions(record, column)" />
      </template>
      <template #form-custom > custom-slot </template>

      <template #toolbar>
        <a-button type="primary" @click="addMenu" >
          {{ '新增菜单' }}
        </a-button>
      </template>
    </BasicTable>
    <Model @register="addRegister"  @saveData="saveData" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, unref } from 'vue';
  import Model from './model.vue'
  import { useModal } from '/@/components/Modal';
  import { h } from 'vue';
  import { Tag } from 'ant-design-vue';
  import { Icon } from '/@/components/Icon';
  import { dataSource } from './data'
  import {
    BasicTable,
    useTable,
    TableAction,
    BasicColumn,
    ActionItem,
    EditRecordRow,
    TableActionType
  } from '/@/components/Table';


  const columns: BasicColumn[] = [
    {
      title: '菜单名称',
      dataIndex: 'menuName',
      width: 150,
      align: 'left',
    },
    {
      title: 'key',
      dataIndex: 'key',
      width: 70,
    },
    {
      title: '图标',
      dataIndex: 'icon',
      width: 50,
      customRender: ({ record }) => {
        return h(Icon, { icon: record.icon });
      },
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      width: 150,
    },
    {
      title: '详情',
      dataIndex: 'detail',
      width: 200,
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 80,
      customRender: ({ record }) => {
        const status = record.status;
        const enable = ~~status === 0;
        const color = enable ? 'green' : 'red';
        const text = enable ? '启用' : '停用';
        return h(Tag, { color: color }, () => text);
      },
    },
  ];

  export default defineComponent({
    components: { BasicTable, TableAction, Model,  },
    setup() {
      const tableRef = ref<Nullable<TableActionType>>(null);
      const currentEditKeyRef = ref('');


      const [registerTable] = useTable({
        title: "菜单列表",
        titleHelpMessage: "温馨提醒",
        columns: columns,
        dataSource: dataSource,
        bordered: true,
        showIndexColumn: false,
        actionColumn: {
          width: 160,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: undefined,
        },
      });
      const [addRegister, { openModal: openAdd }] = useModal();
      const rowClick = (e: any) => {
        console.log(e)
      }

      function getTableAction() { // 获取组件
        const tableAction = unref(tableRef);
        if (!tableAction) {
          throw new Error('tableAction is null');
        }
        return tableAction;
      }

       function getSelectRowList() { // 获取选中行
        console.log(getTableAction().getSelectRows());
      }
      function getSelectRowKeyList() { // 获取选中行的key --- id
        console.log(getTableAction().getSelectRowKeys());
      }

      function addMenu() {
        openAdd(true, {
          id: 0,
          menuName: '',
          detail: '',
        });
      }

      function handleEdit(record: EditRecordRow) {
        currentEditKeyRef.value = record.id;  // record.key
        console.log(record)

        // console.log(record.id)
        // const data = getTableAction().getDataSource()
        // data.map(item => {
        //   if (item.id === record.id) {
        //     record = item
        //   }
        // })
        openAdd(true, {
          // id: record.id,
          // name: record.name,
          // password: record.password,
          // detail: record.detail,
          ...record,
          isUpdate: true,
        });
      }

      function handleDelete(record: Recordable) {
        console.log('点击了删除', record.id);
        console.log(record)
        const data = getTableAction().getDataSource()
        console.log(data)
        getTableAction().setTableData(data.filter(item => item.id !== record.id))
      }

      function saveData(data: any) {
        console.log('saveDate--------')
        if (!data.key) {
          console.log('添加菜单')
          console.log(data)
          return
        }

        const mapTree = org => {
          const haveChildren = Array.isArray(org.children) && org.children.length > 0;
          if (org.key === data.key) {
            org.menuName = data.menuName
            org.icon = data.icon
            org.status = data.status
            org.detail = data.detail
            return
          }
          if (haveChildren) {
            org.children.map(item => mapTree(item))
          }
        }

        const dataSource = getTableAction().getDataSource()

        if (Array.isArray(dataSource)) {
          dataSource.map(item => mapTree(item))
        }
        getTableAction().setTableData(dataSource)
      }

      function createActions(record: EditRecordRow, column: BasicColumn): ActionItem[] {
        column
        return [
          {
            label: '编辑',
            icon: 'ant-design:edit-outlined',
            color: 'warning',
            onClick: handleEdit.bind(null, record),
          },
          {
            label: '删除',
            color: 'error',
            icon: 'ic:outline-delete-outline',
            popConfirm: {
              title: '是否确认删除',
              confirm: handleDelete.bind(null, record),
            },
          },
        ];
      }
      return {
        tableRef,
        registerTable,
        rowClick,
        addMenu,
        handleEdit,
        createActions,
        getTableAction,
        getSelectRowList,
        getSelectRowKeyList,
        addRegister,
        saveData,
      };
    },
  });
</script>
