<template>
  <PageWrapper>
    <el-card :bordered="false" class="pt-3 mb-3 proCard">
      <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
        <template #statusSlot="{ model, field }">
          <el-input v-model="model[field]" />
        </template>
      </BasicForm>
    </el-card>
    <el-card :bordered="false" class="proCard">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="basicTableRef"
        :actionColumn="actionColumn"
        @selection-change="onSelectionChange"
        scroll-x="1200"
        virtual-scroll
      >
        <template #tableTitle>
          <el-space>
            <el-button type="primary" @click="addUser">
              <template #icon>
                <el-icon style="vertical-align: middle">
                  <plus />
                </el-icon>
              </template>
              新建
            </el-button>

            <el-button type="danger" @click="handleDelete()" :disabled="!selectionData.length">
              <template #icon>
                <el-icon class="el-input__icon">
                  <Delete />
                </el-icon>
              </template>
              删除
            </el-button>
            <el-upload
            ref="upload"
            action="/api/user/import"
            :headers="uploadHeaders"
            :on-error="onError"
            :on-success="onSuccess"
            :before-upload="beforeUpload"
            :show-file-list="false"
            :limit="1"
          >
            <el-button type="danger">
              <template #icon>
                <el-icon class="el-input__icon">
                  <Upload />
                </el-icon>
              </template>
              导入
            </el-button>
          </el-upload>
            <el-button type="danger" @click="handleExport" :loading="exportLoading" :disabled="exportLoading">
              <template #icon>
                <el-icon class="el-input__icon">
                  <Download />
                </el-icon>
              </template>
              导出
            </el-button>
          </el-space>
        </template>
      </BasicTable>
    </el-card>
    <editDialog
        v-if="editVisible"
        :userId="userId"
        v-model:visible="editVisible"
        @success="reloadTable"
    >
    </editDialog>
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { h, nextTick, reactive, ref ,defineAsyncComponent} from 'vue';
  import { ColProps,  UploadInstance } from 'element-plus';
  import { TableAction } from '@/components/Table';
  import { useForm } from '@/components/Form/index';
  import { getUserList,userDelete,userBatchDelete,userExport,resetPwd } from '@/api/system/user';
  import {message,confirm,loading, closeLoading} from "@/utils/auth";
  import { columns } from './columns';
  import { schemas } from './querySchemas';
  import { useUserStore } from '@/store/modules/user';
  import {downloadByData} from '@/utils/file/download';
  const userId =  ref(0);
  const basicTableRef = ref();
  const editVisible = ref(false)
  const selectionData = ref([])
  const upload = ref<UploadInstance>();
  const exportLoading=ref(false)
  const editDialog = defineAsyncComponent(() =>
    import('./edit.vue'))
  const uploadHeaders = reactive({
    authorization:useUserStore().getToken
  });
  const formParams = reactive({
    realname: '',
    role:'',
    status:'',
  });


  const actionColumn = reactive({
    width: 250,
    label: '操作',
    prop: 'action',
    fixed: 'right',
    align: 'center',
    render(record) {
      return h(TableAction as any, {
        style: 'text',
        actions: [
          {
            label: '删除',
            type: 'danger',
            onClick: handleDelete.bind(null, record),
          },
          {
            label: '编辑',
            type: 'warning',
            onClick: handleEdit.bind(null, record),
          },
          {
            label: '重置密码',
            type: 'warning',
            onClick: handleResetPassWord.bind(null, record),
          },
        ],
        // dropDownActions: [
        //   {
        //     label: '启用',
        //     key: 'enabled',
        //   },
        //   {
        //     label: '禁用',
        //     key: 'disabled',
        //   },
        // ],
        // select: (key) => {
        //   ElMessage.info(`您点击了，${key} 按钮`);
        // },
      });
    },
  });

  const loadDataTable = async (res) => {
    const result = await getUserList({ ...formParams, ...res });
    return result;
  };

  function reloadTable() {
    basicTableRef.value.reload({pageNo:1});
  }

  async function handleEdit(record: Recordable) {
    userId.value=record.row.id
    await nextTick();
    editVisible.value=true
  }
  async function handleResetPassWord(record: Recordable) {
    await confirm('确定重置密码？');
    await resetPwd({userId:record.row.id})
    message("重置成功");
  }
  

  async function handleDelete(record: Recordable) {
    let ids = []
    if(!record){
      ids = selectionData.value.map(({id}) => id);
    }
    await confirm('确定要删除？');
    record? await userDelete(record.row.id):await userBatchDelete(ids);
    message("删除成功");
    reloadTable()
  }
  
  function handleSubmit(values: Recordable) {
    for (const key in formParams) {
      if (values[key] != null && values[key] != undefined) {
        formParams[key] = values[key];
      }
    }
    reloadTable();
  }

  function handleReset(values: Recordable) {
    for (const key in formParams) {
        formParams[key] ='';
    }
  }
  function onSelectionChange(value){
    selectionData.value = value
  }
  const [register, {}] = useForm({
    labelWidth: 80,
    layout: 'horizontal',
    colProps: { span: 6 } as ColProps,
    submitOnReset:true,
    schemas
  });
  //添加
  function addUser() {
    userId.value =0
    editVisible.value  = true
  }
const beforeUpload = (file: UploadFile) => {
  const isLt2M = file.size / 1024 / 1024 < 200;
  if (!isLt2M) {
    message("大小不能超过200MB!", "error");
    return false;
  }
  if (!/\.(xlsx|xls|XLSX|XLS)$/.test(file.name)) {
    message("请上传.xlsx .xls", "error");
    return false;
  }
  loading("上传中");
  return true;
};
const onSuccess = (file: UploadFile) => {
  upload.value!.clearFiles();
  closeLoading();
  if (file.code == 0) {
    message("导入成功");
    reloadTable()
  } else {
    message(file.msg ? file.msg : "导入失败", "error");
  }
};
const onError = () => {
  upload.value!.clearFiles();
  closeLoading();
  message("导入失败", "error");
};
//导出
const handleExport = async()=>{
  exportLoading.value=true
  const data=await userExport()
  downloadByData(data, '用户信息.xlsx');
  exportLoading.value=false
  message("导出成功");
}

</script>

<style lang="scss" scoped></style>
