<template>
  <div>
    <BasicTable
      ref="tableRef"
      @register="registerTable"
      @fetchSuccess="ExpandAllRows"
      defaultExpandAllRows
      rowKey="id"
    >
      <template #toolbar>
        <a-button type="primary" @click="toggleRowShow">{{ btn_text }}</a-button>
        <a-button type="primary" @click="addGroupFn"> 添加 </a-button>
        <a-button type="danger" @click="deleteBatches"> 删除 </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, toRefs, unref } from 'vue';
  import Popup from './popup.vue';
  import { useModal } from '/@/components/Modal';
  //   import { getAllMenuList } from '/@/api/sys/menu';
  import { columns } from './data';
  import { useUserStore } from '/@/store/modules/user';
  import { useMessage } from '/@/hooks/web/useMessage';
  import {
    getGroupTree,
    addGroup,
    editGroup,
    deleteGroup,
    deleteBatchesGroup,
  } from '/@/api/sys/user';
  import {
    BasicTable,
    useTable,
    TableAction,
    ActionItem,
    EditRecordRow,
    TableActionType,
  } from '/@/components/Table';

  interface PopupData {
    title: string;
    treeData: object[];
  }
  interface Btn {
    btn_text: string;
    btn_status: boolean;
  }
  interface Group {
    id: string;
    name: boolean;
  }

  export default defineComponent({
    components: { BasicTable, TableAction, Popup },
    setup() {
      const userStore = useUserStore();
      const { createMessage } = useMessage();
      const { success /*, error */ } = createMessage;
      const tableRef = ref<Nullable<TableActionType>>(null);
      const currentEditKeyRef = ref('');
      const groups = userStore.getUserInfo.groups as Group[];
      const popupData = reactive<PopupData>({
        title: '添加',
        treeData: [{}],
      });

      const btn = reactive<Btn>({
        btn_text: '展开全部',
        btn_status: true,
      });
      const [registerTable, { expandAll, collapseAll }] = useTable({
        title: '角色列表',
        titleHelpMessage:
          '角色组可以有多个,角色有上下级层级关系,如果子角色有角色组和管理员的权限则可以派生属于自己组别的下级角色组或管理员',
        rowSelection: { type: 'checkbox' },
        columns: columns,
        clickToRowSelect: false, // 点击行不勾选
        api: getGroupTree,
        isTreeTable: true,
        afterFetch: afterFetch,
        actionColumn: {
          width: 160,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: undefined,
        },
        showIndexColumn: false,
        bordered: true,
      });
      const [addRegister, { openModal: openPopup }] = useModal();

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

      function ExpandAllRows() {
        setTimeout(() => {
          toggleRowShow();
        }, 1);
      }

      function toggleRowShow() {
        if (btn.btn_status) {
          expandAll();
          btn.btn_text = '折叠全部';
          btn.btn_status = false;
        } else {
          collapseAll();
          btn.btn_text = '展开全部';
          btn.btn_status = 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;
          }
        });
        openPopup(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();
          ExpandAllRows();
          success('删除成功!');
        });
      }

      async function deleteBatches() {
        const id = getTableAction().getSelectRowKeys().toString();
        if (!id) {
          return;
        }
        await deleteBatchesGroup({ id }).then((res) => {
          console.log(res);
          getTableAction().reload();
          ExpandAllRows();
          success('删除成功!');
          getTableAction().setSelectedRowKeys([]);
        });
      }

      async function saveData(params: any) {
        console.log('------------save---------');
        params.data.rules = params.data.rules.toString();
        const data = params.data;
        const closeModel = params.closeModal;
        console.log(`data`, data);
        if (!data.id) {
          await addGroup(data).then((res) => {
            console.log(res);
            getTableAction().reload();
            closeModel();
            ExpandAllRows();
            success('创建成功!');
          });
          console.log('----------add---');
        } else {
          await editGroup(data).then((res) => {
            console.log(res);
            getTableAction().reload();
            closeModel();
            ExpandAllRows();
            success('修改成功!');
          });
          console.log('----------edit---');
        }
      }

      function createActions(record: EditRecordRow): ActionItem[] {
        if (record.pid === 0) {
          return [
            {
              label: '',
              icon: '',
            },
          ];
        }

        const permission = groups.some((item) => item.id > record.pid);

        if (permission) {
          return [
            {
              label: '',
              icon: '',
            },
          ];
        }
        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,
        addGroupFn,
        handleEdit,
        deleteBatches,
        createActions,
        getTableAction,
        getSelectRowList,
        getSelectRowKeyList,
        toggleRowShow,
        addRegister,
        saveData,
        ExpandAllRows,
        ...toRefs(btn),
      };
    },
  });
</script>
