<template>
  <div>
    <BasicTable
      ref="tableRef"
      @register="registerTable"
      rowKey="id"
      @selectionChange="selectionChange"
      @rowClick="selectionChange"
      @rowDbClick="handleEdit"
      showTableSetting
      :canResize="true"
      :pagination="{
        pageSize: 10,
        defaultPageSize: 10,
        showSizeChanger: false,
      }"
    >
      <template #toolbar>
        <a-button type="primary" @click="addRole"> 添加 </a-button>
        <a-button type="danger" :disabled="disable_btn" @click="deleteBatches"> 删除 </a-button>
        <a-button @click="openModal"> 导出 </a-button>
      </template>
      <template #form-custom> custom-slot </template>
      <template #action="{ record }">
        <TableAction :actions="createActions(record)" stopButtonPropagation />
      </template>
    </BasicTable>
    <ExpExcelModel @register="register" @success="defaultHeader" />
    <Popup @register="addRegister" :popupData="popupData" @saveData="saveData" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, onMounted, reactive, ref, toRefs, unref } from 'vue';
  import Popup from './popup.vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';
  import { jsonToSheetXlsx, ExpExcelModel, ExportModalResult } from '/@/components/Excel';
  import { getFormConfig, columns } from './data';
  import {
    getUserList,
    addUser,
    editUser,
    deleteUser,
    getGroupTree,
    deleteBatchesUser,
  } from '/@/api/sys/user';
  import { useUserStore } from '/@/store/modules/user';
  import {
    BasicTable,
    useTable,
    TableAction,
    ActionItem,
    EditRecordRow,
    TableActionType,
  } from '/@/components/Table';

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

  export default defineComponent({
    components: { BasicTable, TableAction, Popup, ExpExcelModel },
    setup() {
      init();
      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>({
        disable_btn: true,
      });
      const [registerTable] = useTable({
        title: '管理员管理',
        titleHelpMessage: '一个管理员可以有多个角色组,左侧的菜单根据管理员所拥有的权限进行生成',
        rowSelection: { type: 'checkbox' },
        columns: columns,
        // clickToRowSelect: false, // 点击行不勾选
        api: getUserList,
        useSearchForm: true,
        beforeFetch: beforeFetch,
        afterFetch: afterFetch,
        formConfig: getFormConfig(),
        actionColumn: {
          width: 160,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: undefined,
        },
        showIndexColumn: false,
        bordered: true,
      });
      const userStore = useUserStore();
      const [register, { openModal }] = useModal();
      const [addRegister, { openModal: openPopup }] = useModal();
      const id = userStore.getUserInfo?.id;
      function getTableAction() {
        // 获取组件
        const tableAction = unref(tableRef);
        if (!tableAction) {
          throw new Error('tableAction is null');
        }
        return tableAction;
      }

      // 请求之前处理参数
      function beforeFetch(params) {
        console.log(params);
        console.log('==========before========');
        // params['op'] = {};
        for (let k in params) {
          if (!params[k]) {
            delete params[k];
          }
        }

        if (params.logintime) {
          params.logintime[0] = params.logintime[0].replace(
            /([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])/g,
            '00:00:00'
          );
          params.logintime[1] = params.logintime[1].replace(
            /([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])/g,
            '23:59:59'
          );
        }

        params.offset = params.page;
        params.limit = params.pageSize;
        delete params.page;
        delete params.pageSize;
      }
      function afterFetch(result) {
        result.map((item) => {
          if (item.groups) {
            item.groups_value = [];
            item.groups.map((item_group) => {
              item.groups_value.push({ lable: item_group.name, value: item_group.id });
            });
          } else {
            item.groups = []; //null
            item.groups_text = [];
          }
        });
        console.log(`result`, result);
      }

      async function init() {
        const GroupTree = await getGroupTree();
        popupData.treeData = GroupTree.list;
      }

      function addRole() {
        if (!popupData.treeData.length) {
          error('没有访问权限!');
          return;
        }
        popupData.title = '添加';
        openPopup(true, {
          id: null,
          username: '',
          nickname: '',
          email: '',
          groups_value: [],
          status: 'normal',
        });
      }

      function handleEdit(record: EditRecordRow) {
        if (!popupData.treeData.length) {
          error('没有修改权限!');
          return;
        }
        currentEditKeyRef.value = record.id; // record.key
        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);
        await deleteUser({ id: record.id }).then((res) => {
          console.log(res);
          getTableAction().reload();
          success('删除成功!');
        });
      }

      function selectionChange() {
        const keys = getTableAction().getSelectRowKeys();
        if (keys.length) {
          btn.disable_btn = false;
        } else {
          btn.disable_btn = true;
        }
      }

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

      async function saveData(params: any) {
        const data = params.data;
        data.groups = [];
        if (data.groups_value) {
          data.groups_value.map((item) => {
            data.groups.push(item.value);
          });
        }
        const closeModel = params.closeModal;
        if (data.groups) {
          data.groups = data.groups.toString();
        } else {
          data.groups = data.groups_text = '';
        }
        delete data.groups_value;
        console.log(`data`, data);
        if (!data.id) {
          await addUser(data).then((res) => {
            console.log(res);
            getTableAction().reload();
            closeModel();
            success('创建成功!');
          });
          console.log('----------add---');
        } else {
          await editUser(data).then((res) => {
            console.log(res);
            getTableAction().reload();
            closeModel();
            success('修改成功!');
          });
          console.log('----------edit---');
        }
      }

      // 导出
      function defaultHeader({ filename, bookType }: ExportModalResult) {
        // 默认Object.keys(data[0])作为header
        jsonToSheetXlsx({
          data: getTableAction().getDataSource(),
          filename,
          write2excelOpts: {
            bookType,
          },
        });
      }

      function createActions(record: EditRecordRow): ActionItem[] {
        if (id === record.id) {
          return [
            {
              label: '',
            },
          ];
        }
        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),
            },
          },
        ];
      }
      onMounted(() => {
        console.log(getTableAction());
      });
      return {
        popupData,
        tableRef,
        registerTable,
        addRole,
        handleEdit,
        deleteBatches,
        createActions,
        getTableAction,
        selectionChange,
        addRegister,
        saveData,
        getUserList,
        defaultHeader,
        openModal,
        register,
        ...toRefs(btn),
      };
    },
  });
</script>
<style>
  .ant-calendar-picker {
    width: 100%;
  }
</style>
