<template>
  <div>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button v-auth="'AUTH_SYSTEM_USER:ADD'" type="primary" @click="handleCreate"> 新增</a-button>
      </template>
      <template #bodyCell="{ column, record, text }">
        <template v-if="column.dataIndex === 'id'">
          <a @click="handleView(record)"> {{ record.id }} </a>
        </template>
        <template v-if="[].includes(column.dataIndex)">
          <img :src="text" class="photo" alt="图片" v-if="!!text" />
        </template>
        <template v-if="column.dataIndex === 'action'">
          <TableAction
            :actions="[
              {
                tooltip: '编辑',
                icon: 'clarity:note-edit-line',
                onClick: handleEdit.bind(null, record),
                ifShow: hasPermission('AUTH_SYSTEM_USER:EDIT'),
              },
              {
                tooltip: '审核',
                icon: 'ant-design:highlight-outlined',
                popConfirm: {
                  title: '是否通过审核',
                  okText: '通过',
                  cancelText: '拒绝',
                  confirm: handleCheck.bind(null, record, 'PASSED'),
                  cancel: handleCheck.bind(null, record, 'FORBIDDEN'),
                },
                ifShow: hasPermission('AUTH_SYSTEM_USER:VERIFY') && record.status === 'PENDING_REVIEW',
              },
              {
                tooltip: '删除',
                icon: 'ant-design:delete-outlined',
                color: 'error',
                popConfirm: {
                  title: '是否确认删除',
                  confirm: handleDelete.bind(null, record),
                },
                ifShow: hasPermission('AUTH_SYSTEM_USER:DELETE'),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <UserDrawer @register="registerDrawer" @success="handleSuccess" />
  </div>
</template>
<script lang="ts" setup name="DeviceIndex">
  import { ref } from 'vue';
  import { useGo } from '/@/hooks/web/usePage';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { isObject } from '/@/utils/is';
  import moment from 'moment';
  import * as UserApi from '/@/api/system/userApi';
  import { useDrawer } from '/@/components/Drawer';
  import componentSetting from '/@/settings/componentSetting';
  import UserDrawer from './drawer.vue';
  import { columns, searchFormSchema } from './schema';
  import { message } from 'ant-design-vue';

  const { hasPermission } = usePermission();
  const go = useGo();
  const { formConfig, showTableSetting, bordered, showIndexColumn } = componentSetting.table;

  const checkedKeys = ref<Array<string | number>>([]);
  const onSelectChange = (selectedRowKeys: (string | number)[]) => {
    checkedKeys.value = selectedRowKeys;
  };

  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerTable, { reload }] = useTable({
    title: '用户表',
    api: (params) => UserApi.search(handleParams(params)),
    columns,
    formConfig: {
      labelWidth: formConfig.labelWidth,
      schemas: searchFormSchema,
      showAdvancedButton: false,
    },
    useSearchForm: true,
    showTableSetting,
    bordered,
    showIndexColumn,
    canResize: false,
    rowKey: (record: any) => record.id,
    actionColumn: {
      width: 120,
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
    },
  });

  const handleParams = (params) => {
    const { pageNum, pageSize } = params;
    const handledParams: any = { pageNum, pageSize };
    Object.keys(params).forEach((key) => {
      const schema = searchFormSchema.find((item) => item.field === key);
      const value = params[key];
      if (schema && value !== undefined && value !== '') {
        if (schema.component === 'Input') {
          handledParams[key] = `%${value.trim()}%`;
        } else if (['Select', 'ApiSelect'].includes(schema.component)) {
          handledParams[key] = isObject(value) ? value.value : value;
        } else if (schema.component === 'RangePicker') {
          handledParams[`${key}From`] = moment(value[0]).startOf('d').format('YYYY-MM-DD HH:mm:ss');
          handledParams[`${key}To`] = moment(value[1]).endOf('d').format('YYYY-MM-DD HH:mm:ss');
        } else if (schema.component === 'DatePicker') {
          handledParams[key] = moment(value).format((schema.componentProps as any).format || 'YYYY-MM-DD');
        } else {
          handledParams[key] = value;
        }
      }
    });
    return handledParams;
  };

  const handleCreate = () => {
    openDrawer(true, {
      isUpdate: false,
    });
  };

  const handleEdit = (record: Recordable) => {
    openDrawer(true, {
      record,
      isUpdate: true,
    });
  };

  const handleDelete = (record: Recordable) => {
    UserApi.remove(record.id).then((_) => {
      reload();
    });
  };

  const handleCheck = (record: any, status: string) => {
    UserApi.verify({ idList: [record.id], status: status }).then(() => {
      message.success('审核成功');
      reload();
    });
  };

  const handleBatchDelete = () => {
    UserApi.batchRemove(checkedKeys.value).then((_) => {
      reload();
    });
  };

  const handleSuccess = () => {
    reload();
  };

  const handleView = (record) => {
    go('/system/user/' + record.id);
  };
</script>
