<template>
  <ResizePageWrapper>
    <template #resizeLeft>
      <DeptTree @select="handleSelect" />
    </template>

    <template #resizeRight>
      <BasicTable @register="registerTable">
        <template #toolbar>
          <a-button type="primary" v-auth="'member:sync'" @click="handleSync">同步</a-button>
        </template>
      </BasicTable>
    </template>
  </ResizePageWrapper>
</template>
<script lang="ts" setup>
  import { ref } from 'vue';
  import { BasicTable, useTable, FormSchema, BasicColumn } from '/@/components/Table';
  import { getMemberList, updateSyncUser } from '/@/api/system/wechat';
  import { ResizePageWrapper } from '/@/components/Page';
  import DeptTree from '/@/views/system/user/components/DeptTree.vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';

  const { t } = useI18n();
  const searchFormSchema: FormSchema[] = [
    {
      field: 'keyword',
      label: '',
      component: 'Input',
      componentProps: {
        placeholder: '请输入姓名/账号/电话',
      },
    },
  ];

  const columns: BasicColumn[] = [
    {
      title: t('姓名'),
      dataIndex: 'name',
      //sorter: true,
      align: 'center',
      resizable: true,
    },
    {
      title: t('账号'),
      dataIndex: 'userName',
      //sorter: true,
      align: 'center',
      resizable: true,
    },
    {
      title: '组织',
      dataIndex: 'departmentName',
      //sorter: true,
      align: 'center',
      resizable: true,
    },
  ];
  const { notification } = useMessage();

  const selectDeptId = ref('');
  const [registerTable, { reload }] = useTable({
    title: '企业成员列表',
    api: getMemberList,
    rowKey: 'id',
    columns,
    formConfig: {
      rowProps: {
        gutter: 16,
      },
      schemas: searchFormSchema,
      showResetButton: false,
    },
    beforeFetch: (params) => {
      //发送请求默认新增  左边树结构所选机构id
      return { ...params, departmentId: selectDeptId.value };
    },
    useSearchForm: true,
    showTableSetting: true,
    striped: false,
    tableSetting: {
      size: false,
    },
  });

  async function handleSync() {
    if (import.meta.env.VITE_GLOB_PRODUCTION === 'true') {
      notification.warning({
        message: '提示',
        description: '由于您当前处于体验状态，无法操作进行同步',
      });
      return false;
    }
    await updateSyncUser(selectDeptId.value);
    notification.success({
      message: '提示',
      description: '同步成功',
    });
    reload();
  }

  function handleSelect(deptId = '') {
    selectDeptId.value = deptId;
    reload();
  }
</script>
