<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="tableRef"
        :actionColumn="actionColumn"
        @selection-change="onSelectionChange"
        scroll-x="1200"
        virtual-scroll
      >
        <template #tableTitle>
          <el-space>
            <el-button type="primary" @click="addUser" v-perm="['sys:user:add']">
              <template #icon>
                <el-icon style="vertical-align: middle">
                  <plus />
                </el-icon>
              </template>
              新建
            </el-button>

            <el-button type="danger" @click="handleDelete()" :disabled="!selectionData.length" v-perm="['sys:user:batchDelete']">
              <template #icon>
                <el-icon class="el-input__icon">
                  <Delete />
                </el-icon>
              </template>
              删除
            </el-button>
            <el-button type="primary" @click="importVisible=true"  v-perm="['sys:user:import']">
              <template #icon>
                <el-icon class="el-input__icon">
                  <Upload />
                </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"
            v-perm="['sys:user:import']"
          >
            <el-button type="primary">
              <template #icon>
                <el-icon class="el-input__icon">
                  <Upload />
                </el-icon>
              </template>
              导入
            </el-button>
          </el-upload> -->
            <el-button type="primary" @click="handleExport" :loading="exportLoading" :disabled="exportLoading" v-perm="['sys:user:export']">
              <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('noRefresh')"
    >
    </editDialog>
    <userUpload v-if="importVisible" v-model:visible="importVisible" @success="reloadTable()"/>
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { h, nextTick, reactive, ref ,defineAsyncComponent} from 'vue';
  import { ColProps } from 'element-plus';
  import { TableAction } from '@/components/Table';
  import { useForm } from '@/components/Form/index';
  import { getUserList,userDelete,userBatchDelete,userExport,resetPwd,getUserDocument } from '@/api/system/user';
  import {message,confirm} from "@/utils/auth";
  import { columns } from './columns';
  import { schemas } from './querySchemas';
  import {downloadByData} from '@/utils/file/download';
  import printJS from 'print-js';
  const userId =  ref(0);
  const tableRef = ref();
  const editVisible = ref(false)
  const importVisible = ref(false)
  const selectionData = ref([])
  const exportLoading=ref(false)
  const editDialog = defineAsyncComponent(() =>
    import('./edit.vue'))
    const userUpload = defineAsyncComponent(() =>
    import('./userUpload.vue'))
  const formParams = reactive({
    realname: '',
    role:'',
    status:'',
  });


  const actionColumn = reactive({
    width:370,
    label: '操作',
    prop: 'action',
    fixed: 'right',
    align: 'center',
    render(record) {
      return h(TableAction as any, {
        style: 'text',
        actions: [
          {
            label: '编辑',
            icon:'Edit',
            type: 'warning',
            onClick: handleEdit.bind(null, record),
            auth:['sys:user:update']
          },
          {
            label: '删除',
            icon:'Delete',
            type: 'danger',
            onClick: handleDelete.bind(null, record),
            auth:['sys:user:delete']
          },
          {
            label: '重置密码',
            type: 'warning',
            onClick: handleResetPassWord.bind(null, record),
            auth:['sys:user:resetPwd']
          },
          {
            label: '打印',
            type: 'primary',
            icon:'Printer',
            onClick: handlePrint.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(noRefresh='') {
    tableRef.value.reload(noRefresh?{}:{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()
  }
  const handlePrint = async(record: Recordable)=>{
    const res = await getUserDocument(record.row.id)
    printJS({
      printable:res.fileUrl,
      type: 'pdf',
      showModal:true
      
    });
  }
  
  function handleSubmit(values: Recordable) {
    handleReset()
    for (const key in values) {
      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 handleExport = async()=>{
  exportLoading.value=true
  const data=await userExport()
  downloadByData(data, '用户信息.xlsx');
  exportLoading.value=false
  message("导出成功");
}

</script>

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