<template>
  <PageWrapper dense fixedHeight contentFullHeight contentClass="flex">
    <ClassTree class="w-1/3 xl:w-1/4" @select="handleChange" />
    <BasicTable
      class="w-3/4 xl:w-4/5"
      @register="registerTable"
      :row-selection="{ selectedRowKeys: selectedKeys, onChange: onSelectChange }"
      :searchInfo="searchInfo"
    >
      <template #toolbar>
        <a-button type="primary" v-auth="'student:add'" @click="handleAdd">新增</a-button>
        <Dropdown.Button v-auth="'student:import'">
          数据导入
          <template #icon>
            <Icon icon="carbon:document-import" :size="16" />
          </template>
          <template #overlay>
            <Menu>
              <Menu.Item>
                <a-button block type="link" @click="handelDownloadTemplate"> 下载模板 </a-button>
              </Menu.Item>
              <Menu.Item>
                <Upload :showUploadList="false" :before-upload="beforeUpload">
                  <a-button block type="link"> 导入 </a-button>
                </Upload>
              </Menu.Item>
            </Menu>
          </template>
        </Dropdown.Button>
        <Upload
          v-auth="'student:upload'"
          :showUploadList="false"
          :before-upload="handelBeforeUpload"
          accept=".rar,.zip"
        >
          <a-button block type="primary"> 导入学籍照 </a-button>
        </Upload>
        <ExportTool
          v-auth="'student:export'"
          ref="exportToolRef"
          type="student"
          @click="handelExportClick"
        />
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'action'">
          <TableAction
            :actions="[
              {
                label: '查看',
                auth: 'student:view',
                onClick: handleView.bind(null, record),
              },
              {
                label: '编辑',
                auth: 'student:edit',
                onClick: handleEdit.bind(null, record),
              },
              {
                label: '删除',
                color: 'error',
                auth: 'student:delete',
                onClick: handleDelete.bind(null, record),
              },
            ]"
          />
        </template>
        <template v-if="column.dataIndex === 'avatar'">
          <TableImg
            v-if="record.avatar"
            :size="40"
            :simpleShow="true"
            :showBadge="false"
            :imgList="[record.avatar]"
          />
          <div v-else></div>
        </template>
      </template>
    </BasicTable>

    <stdudentBaseManagerDrawer @register="registerDrawer" @success="handleSuccess" />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { computed, createVNode, onMounted, reactive, ref } from 'vue';

  import { Modal, Upload, Dropdown, Menu } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { BasicTable, TableAction, useTable, TableImg } from '/@/components/Table';
  import { deleteXjrUser, getXjrUserPage } from '/@/api/dev/studentbasemanager';
  import { PageWrapper } from '/@/components/Page';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useRouter } from 'vue-router';
  import { PrintButton } from '/@/enums/printEnum';
  import stdudentBaseManagerDrawer from './components/stdudentBaseManagerDrawer.vue';
  import { useDrawer } from '/@/components/Drawer';
  import { columns, searchFormSchema } from './components/config';

  import Icon from '/@/components/Icon/index';
  import ClassTree from '/@/views/educational/class/components/ClassGroup.vue';
  import {
    postStudentmanagerAvatarImport,
    postStudentmanagerImport,
  } from '/@/services/apis/StudentManagerController';
  import { downloadByUrl } from '/@/utils/file/download';

  import ExportTool from '/@/views/export/template/components/tool.vue';
  import { useLoading } from '/@/components/Loading';

  const exportToolRef = ref<ElRef>(null);
  const searchInfo = reactive<Recordable>({});

  const handelExportClick = (type) => {
    // if (searchInfo.treeType !== 4) {
    //   createMessage.warning('请选择班级');
    //   return;
    // }
    const data: Recordable = {
      conditions: [],
      ids: [],
    };
    if (type === 'all') {
      const formData = getForm().getFieldsValue();
      for (const key in formData) {
        data.conditions.push({ keyName: key, keyValue: formData[key], keyType: '1' });
      }
      if (searchInfo.treeId) {
        let keyName = '';
        switch (searchInfo.treeType) {
          case 1:
            keyName = 'deptId';
            break;
          case 2:
            keyName = 'majorId';
            break;
          case 3:
            keyName = 'gradeId';
            break;
          case 4:
            keyName = 'classId';
            break;
          default:
            keyName = 'deptId';
            break;
        }
        data.conditions.push({
          keyName: keyName,
          keyValue: searchInfo.treeId,
          keyType: '1',
        });
      }
    } else {
      const selectKeys = getSelectRowKeys();
      if (selectKeys.length === 0) {
        createMessage.warning('请选择需要导入的数据');
        return;
      }
      data.ids = selectKeys;
    }

    exportToolRef.value?.open(data);
  };

  onMounted(async () => {});
  const { notification, createMessage } = useMessage();
  const { t } = useI18n();
  defineEmits(['register']);

  const { currentRoute } = useRouter();

  const formIdComputedRef = computed(() => currentRoute.value.meta.formId as string);

  const selectedKeys = ref<string[]>([]);
  const selectedRowsData = ref<any[]>([]);

  const [registerDrawer, { openDrawer }] = useDrawer();

  const [registerTable, { reload, getForm, getSelectRowKeys }] = useTable({
    title: '学生信息列表',
    api: getXjrUserPage,
    rowKey: 'id',
    columns: columns,
    formConfig: {
      rowProps: {
        gutter: 16,
      },
      schemas: searchFormSchema,
      fieldMapToTime: [],
    },
    beforeFetch: (params) => {
      return { ...params, FormId: formIdComputedRef.value, PK: 'id' };
    },
    useSearchForm: true,
    showTableSetting: true,
    striped: true,
    bordered: true,
    immediate: true,
    actionColumn: {
      width: 150,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
    customRow,
  });

  function handleAdd() {
    openDrawer(true, {
      isUpdate: false,
    });
  }

  function handleEdit(record: Recordable) {
    openDrawer(true, {
      id: record.id,
      isUpdate: true,
    });
  }

  function handleDelete(record: Recordable) {
    deleteList([record.id]);
  }
  const handleChange = (data) => {
    searchInfo.treeId = data.id;
    searchInfo.treeType = data.type;
    reload();
  };
  function deleteList(ids) {
    Modal.confirm({
      title: '提示信息',
      icon: createVNode(ExclamationCircleOutlined),
      content: '是否确认删除？',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        deleteXjrUser(ids).then((_) => {
          reload();
          notification.success({
            message: 'Tip',
            description: t('删除成功！'),
          });
        });
      },
      onCancel() {},
    });
  }

  function onSelectChange(selectedRowKeys: [], selectedRows) {
    selectedKeys.value = selectedRowKeys;
    selectedRowsData.value = selectedRows;
  }

  function customRow(record: Recordable) {
    return {
      onClick: () => {
        let selectedRowKeys = [...selectedKeys.value];
        if (selectedRowKeys.indexOf(record.id) >= 0) {
          let index = selectedRowKeys.indexOf(record.id);
          selectedRowKeys.splice(index, 1);
        } else {
          selectedRowKeys.push(record.id);
        }
        selectedKeys.value = selectedRowKeys;
      },
    };
  }

  function handleSuccess() {
    reload();
  }

  function handleView(record: Recordable) {
    openDrawer(true, {
      isView: true,
      id: record.id,
    });
  }

  function handelDownloadTemplate() {
    downloadByUrl({
      url: 'https://zhxy.cqtlzjzx.com/minio/static/resources/%E5%AD%A6%E7%94%9F%E6%A8%A1%E6%9D%BF.xlsx',
      fileName: '学生信息模板',
    });
  }

  const [openFullLoading, closeFullLoading] = useLoading({
    tip: '处理中...',
  });

  const handelBeforeUpload = async (e) => {
    try {
      openFullLoading();
      await postStudentmanagerAvatarImport({ file: e });
      closeFullLoading();
      createMessage.success('导入成功');
      reload();
    } catch {
      closeFullLoading();
    }
    return false;
  };

  const beforeUpload = async (e) => {
    try {
      openFullLoading();
      await postStudentmanagerImport({ file: e });
      closeFullLoading();
      createMessage.success('导入成功');
      reload();
    } catch {
      closeFullLoading();
    }
    return false;
  };
</script>
<style lang="less" scoped>
  :deep(.ant-table-selection-col) {
    width: 50px;
  }
</style>
