<template>
  <div class="system-user-container layout-pd">
    <el-card shadow="never">
      <el-form :model="queryParams" ref="ruleFormRef" :inline="true" v-show="showSearch">
        <el-form-item label="手机号" prop="PhoneNo">
          <el-input v-model="queryParams.PhoneNo" placeholder="请输入手机号" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="账号" prop="Name">
          <el-input v-model="queryParams.Name" placeholder="请输入用户名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="昵称" prop="NickName">
          <el-input v-model="queryParams.NickName" placeholder="请输入昵称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" :loading="loading" v-waves>查询</el-button>
          <el-button @click="resetQuery(ruleFormRef)" v-waves>重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card shadow="never">
      <div class="flex-center-between mb20">
        <p class="table-title">信息列表</p>
        <div v-auth="'100102'">
          <el-button type="primary" @click="onOpenAddUser" v-waves>
            <SvgIcon name="ele-Plus" class="mr5" />新增用户
          </el-button>
        </div>
      </div>
      <!-- 表格 -->
      <el-table :data="list" v-loading="loading" row-key="id" ref="multipleTableRef"
        @selection-change="handleSelectionChange" id="table">
        <!-- <el-table-column type="selection" width="55" :reserve-selection="true"/> -->
        <el-table-column prop="name" label="账号" show-overflow-tooltip></el-table-column>
        <el-table-column prop="phoneNo" label="手机号码" show-overflow-tooltip></el-table-column>
        <el-table-column prop="staffNo" label="工号" show-overflow-tooltip></el-table-column>
        <el-table-column prop="defaultTelNo" label="默认分机号" show-overflow-tooltip></el-table-column>
        <el-table-column prop="creationTime" label="创建时间" show-overflow-tooltip width="170"></el-table-column>
        <el-table-column label="操作" width="250" fixed="right" align="center">
          <template #default="scope">
            <el-button text type="primary" @click="onOpenEditUser(scope.row)" v-auth="'100103'">修改</el-button>
            <el-button text type="success" @click="onSetRole(scope.row)" v-auth="'100105'">设置角色</el-button>
            <el-button text type="warning" @click="onRestPwd(scope.row)">重置密码</el-button>
            <el-button text type="danger" @click="onRowDel(scope.row)" v-auth="'100104'">删除</el-button>
          </template>
        </el-table-column>
        <template #empty>
          <Empty />
        </template>
      </el-table>
      <!-- 分页 -->
      <pagination :total="total" v-model:page="queryParams.PageIndex" v-model:limit="queryParams.pageSize"
        @pagination="getList" />
    </el-card>
    <AddUer ref="addUserRef" @updateList="handleQuery" />
    <EditUser ref="editUserRef" @updateList="handleQuery" />
    <SetRole ref="setRoleRef" @updateList="handleQuery" />
  </div>
</template>

<script lang="ts" setup name="systemUser">
import { defineAsyncComponent, ref, reactive, toRefs, onMounted } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { throttle } from '/@/utils/tools';
import type { FormInstance } from 'element-plus';
import { formatDate } from '/@/utils/formatTime';
import { delUser, getUserListPaged, restPwd } from '/@/api/system/user';
// import FileSaver from 'file-saver';
// import * as XLSX from 'xlsx'//这是vue3导入XLSX的方法
interface queryState {
  queryParams: {
    PageIndex: number,
    pageSize: number,
    PhoneNo?: string,
    Name?: string,
    NickName?: string
  }
}
const data = reactive<queryState>({
  queryParams: {
    PageIndex: 1,
    pageSize: 10,
    PhoneNo: '',
    Name: '',
    NickName: '',
  },
});
const AddUer = defineAsyncComponent(() => import('/@/views/system/institutionalUsers/user/component/addUser.vue'))
const EditUser = defineAsyncComponent(() => import('/@/views/system/institutionalUsers/user/component/editUser.vue'))
const SetRole = defineAsyncComponent(() => import('/@/views/system/institutionalUsers/user/component/setRole.vue'))
const loading = ref(false);
const total = ref(0);
const list = ref<any>([]);
const showSearch = ref(true);
const ruleFormRef = ref<FormInstance>();
const addUserRef = ref();
const editUserRef = ref();
const setRoleRef = ref();
/** 搜索按钮操作 节流操作 */
const handleQuery = throttle(() => {
  data.queryParams.PageIndex = 1;
  getList();
}, 1000);
/** 获取用户列表 */
const getList = () => {
  loading.value = true;
  getUserListPaged(data.queryParams).then((response: any) => {
    list.value = response?.result.items ?? [];
    for (let i of list.value) {
      i.creationTime = formatDate(new Date(i.creationTime), 'YYYY-mm-dd HH:MM:SS');
    }
    total.value = response?.result.total;
    setTimeout(() => {
      loading.value = false;
    }, 300);
  }).catch(() => {
    loading.value = false;
  });
};
// 打开新增用户弹窗
const onOpenAddUser = () => {
  addUserRef.value.openDialog();
};
// 打开设置用户角色弹窗
const onSetRole = (row: any) => {
  setRoleRef.value.openDialog(row);
};
const multipleSelection = ref<any>([]) //多选
const handleSelectionChange = (val: any) => {
  multipleSelection.value = val;
}
/** 重置按钮操作 */
const resetQuery = throttle((formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  handleQuery();
}, 1000);
// 打开修改用户弹窗
const onOpenEditUser = (row: any) => {
  editUserRef.value.openDialog(row);
};
// 重置密码
const onRestPwd = (row: any) => {
  ElMessageBox.confirm(`此操作将：“${row.name}的密码重置为 Fwkj@789 ”，是否继续?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    restPwd(row.id).then(() => {
      ElMessage.success('操作成功');
      handleQuery();
    });
  }).catch(() => { });
}
// 删除用户
const onRowDel = (row: any) => {
  ElMessageBox.confirm(`此操作将永久删除账户名称：“${row.name}”，是否继续?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    delUser(row.id).then(() => {
      ElMessage.success('删除成功');
      handleQuery();
    });
  }).catch(() => { });
};
const { queryParams } = toRefs(data);
onMounted(() => {
  getList();
});

// // 全部導出
// const allExport = async (name:string, id:string) => {
//   ElMessageBox.confirm('確定導出所有會計報表?', '導出提示', {
//     confirmButtonText: '確定',
//     cancelButtonText: '取消',
//     type: 'warning'
//   }).then(() => {
//       var wb = XLSX.utils.table_to_book(document.querySelector('#' + id),{ raw: true })
//       var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
//       try {
//         FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), name + '.xlsx')
//       } catch (e) { if (typeof console !== 'undefined') console.log(e, wbout) }
//       return wbout
//     })
//     .catch(() => {})
// }
</script>
