<template>
  <div>
    <BasicTable ref="tableRef" @register="registerTable" rowKey="id">
      <template #toolbar>
        <a-button type="primary" @click="addRole"> 添加 </a-button>
        <a-button type="danger"> 删除 </a-button>
      </template>
      <template #action="{ record, column }">
        <TableAction :actions="createActions(record, column)" />
      </template>
    </BasicTable>
    <Popup @register="addRegister" :popupData="popupData" @saveData="saveData" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, reactive, ref, unref } from 'vue';
  import Popup from './popup.vue';
  import { useModal } from '/@/components/Modal';
  //   import { getAllMenuList } from '/@/api/sys/menu';
  import { columns } from './data';
  import { getGroupTree, addGroup, editGroup, deleteGroup } from '/@/api/sys/user';
  import {
    BasicTable,
    useTable,
    TableAction,
    BasicColumn,
    ActionItem,
    EditRecordRow,
    TableActionType,
  } from '/@/components/Table';

  interface PopupData {
    title: string;
    treeData: object[];
  }

  export default defineComponent({
    components: { BasicTable, TableAction, Popup },
    setup() {
      const tableRef = ref<Nullable<TableActionType>>(null);
      const currentEditKeyRef = ref('');
      const popupData = reactive<PopupData>({
        title: '添加',
        treeData: [{}],
      });
      const [registerTable] = useTable({
        title: '角色列表',
        titleHelpMessage:
          '角色组可以有多个,角色有上下级层级关系,如果子角色有角色组和管理员的权限则可以派生属于自己组别的下级角色组或管理员',
        rowSelection: { type: 'checkbox' },
        columns: columns,
        clickToRowSelect: false, // 点击行不勾选
        api: getGroupTree,
        afterFetch: afterFetch,
        // dataSource: formData,
        actionColumn: {
          width: 160,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: undefined,
        },
        showIndexColumn: false,
        bordered: true,
      });
      const [addRegister, { openModal: openAdd }] = useModal();

      function afterFetch(result) {
        console.log(`result`, result);
        popupData.treeData = result;
      }

      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 addRole() {
        console.log('添加');
        popupData.title = '添加';
        openAdd(true, {});
      }

      function handleEdit(record: EditRecordRow) {
        currentEditKeyRef.value = record.id; // record.key
        console.log(record);
        popupData.title = '编辑';

        const data = getTableAction().getDataSource();
        data.map((item) => {
          if (item.id === record.id) {
            record = item;
          }
          if (record.pid === item.id) {
            record.pname = item.name;
          } else {
            record.pname = null;
          }
        });
        openAdd(true, record);
      }

      async function handleDelete(record: Recordable) {
        console.log('点击了删除', record.id);
        console.log(record);
        await deleteGroup({ id: record.id }).then((res) => {
          console.log(res);
          getTableAction().reload();
        });
      }

      async function saveData(params: any) {
        console.log('------------save---------');
        const data = params.data;
        const closeModel = params.closeModal;
        if (!data.id) {
          await addGroup(data).then((res) => {
            console.log(res);
            getTableAction().reload();
            closeModel();
          });
          console.log('----------add---');
        } else {
          await editGroup(data).then((res) => {
            console.log(res);
            getTableAction().reload();
            closeModel();
          });
          console.log('----------edit---');
        }
      }

      function createActions(record: EditRecordRow, column: BasicColumn): ActionItem[] {
        if (false) {
          console.log(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 {
        popupData,
        tableRef,
        registerTable,
        addRole,
        handleEdit,
        createActions,
        getTableAction,
        getSelectRowList,
        getSelectRowKeyList,
        addRegister,
        saveData,
      };
    },
  });
</script>
