<template>
  <div>
    <BasicTable ref="tableRef" @register="registerTable" @fetchSuccess="ExpandAllRows" rowKey="id">
      <template #toolbar>
        <a-button type="primary" @click="toggleRowShow">{{ btn_text }}</a-button>
        <a-button type="primary" @click="addRuleFn"> 添加 </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 { useMessage } from '/@/hooks/web/useMessage';
  import { columns } from './data';
  import { getRuleTree, addRule, editRule, deleteRule, deleteBatchesRule } from '/@/api/sys/user';
  import {
    BasicTable,
    useTable,
    TableAction,
    BasicColumn,
    ActionItem,
    EditRecordRow,
    TableActionType,
  } from '/@/components/Table';

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

  interface Btn {
    btn_text: string;
    btn_status: boolean;
  }

  export default defineComponent({
    components: { BasicTable, TableAction, Popup },
    setup() {
      const { createMessage } = useMessage();
      const { success /*, error */ } = createMessage;
      const tableRef = ref<Nullable<TableActionType>>(null);
      const currentEditKeyRef = ref('');
      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, // 点击行不勾选
        isTreeTable: true,
        api: getRuleTree,
        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) {
        popupData.treeData = result;
        console.log(`result`, result);
      }

      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 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 addRuleFn() {
        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;
          }
        });
        openAdd(true, record);
      }

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

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

      async function saveData(params: any) {
        console.log('------------save---------');
        const data = params.data;
        const closeModel = params.closeModal;
        if (!data.id) {
          await addRule(data).then((res) => {
            console.log(res);
            getTableAction().reload();
            closeModel();
          });
          ExpandAllRows();
          success('创建成功!');
          console.log('----------add---');
        } else {
          await editRule(data).then((res) => {
            console.log(res);
            getTableAction().reload();
            closeModel();
          });
          ExpandAllRows();
          success('修改成功!');
          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,
        addRuleFn,
        handleEdit,
        deleteBatches,
        createActions,
        getTableAction,
        getSelectRowList,
        getSelectRowKeyList,
        addRegister,
        saveData,
        ExpandAllRows,
        toggleRowShow,
        ...toRefs(btn),
      };
    },
  });
</script>
