<template>
  <div>
    <warning-bar title="注：本页面为二次认证用户管理，支持手动新增、Excel导入及系统用户同步" />
    <div class="gva-table-box">
      <!--按钮区域-->
      <div class="gva-btn-list">
        <el-button
          v-preReClick
          icon="plus"
          type="primary"
          @click="addUser"
        >
          新增用户
        </el-button>
        <el-button
          v-preReClick
          icon="upload"
          type="success"
          @click="triggerImport"
        >
          Excel导入
        </el-button>
        <el-button
          v-preReClick
          icon="download"
          type="info"
          @click="downloadTemplate"
        >
          下载模板
        </el-button>
        <el-button
          v-preReClick
          icon="refresh"
          type="warning"
          @click="syncSystemUsers"
        >
          同步系统用户
        </el-button>
      </div>

      <!--隐藏的文件导入input-->
      <input
        ref="fileInputRef"
        type="file"
        accept=".xlsx,.xls"
        style="display: none"
        @change="handleFileChange"
      >

      <!--筛选区域-->
      <div class="filter-area">
        <span class="filter-label">认证方式筛选：</span>
        <el-select
          v-model="filterAuthMethod"
          clearable
          placeholder="全部"
          style="width: 180px"
          @change="handleFilterChange"
        >
          <el-option
            label="全部"
            value=""
          />
          <el-option
            label="智能密码钥匙"
            value="ukey"
          />
          <el-option
            label="手机短信"
            value="sms"
          />
        </el-select>
        <el-input
          v-model="filterKeyword"
          clearable
          placeholder="搜索账号名/昵称"
          style="width: 220px; margin-left: 12px"
          @change="handleFilterChange"
          @clear="handleFilterChange"
        />
      </div>

      <!--用户表格-->
      <el-table
        :data="tableData"
        row-key="ID"
        style="margin-top: 12px"
      >
        <el-table-column
          align="left"
          label="ID"
          min-width="50"
          prop="ID"
        />
        <el-table-column
          align="left"
          label="账号名"
          min-width="130"
          prop="userName"
        />
        <el-table-column
          align="left"
          label="昵称"
          min-width="120"
          prop="nickName"
        />
        <el-table-column
          align="left"
          label="二次认证方式"
          min-width="140"
        >
          <template #default="scope">
            <el-tag
              :type="scope.row.authMethod === 'ukey' ? 'primary' : 'success'"
              effect="light"
              size="default"
            >
              {{ scope.row.authMethod === 'ukey' ? '智能密码钥匙' : '手机短信' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          align="left"
          label="绑定的二次认证标识"
          min-width="220"
        >
          <template #default="scope">
            <template v-if="scope.row.authMethod === 'ukey'">
              <el-tooltip
                :content="scope.row.authIdentifier"
                placement="top"
                :show-after="300"
              >
                <span class="cert-pubkey-text">
                  {{ truncateCertKey(scope.row.authIdentifier) }}
                </span>
              </el-tooltip>
              <el-button
                v-preReClick
                link
                type="primary"
                size="small"
                style="margin-left: 4px"
                @click="copyToClipboard(scope.row.authIdentifier)"
              >
                <el-icon><DocumentCopy /></el-icon>
              </el-button>
            </template>
            <template v-else>
              <span>{{ scope.row.authIdentifier || scope.row.phone || '-' }}</span>
            </template>
          </template>
        </el-table-column>
        <el-table-column
          align="left"
          label="上次登录时间"
          min-width="180"
          prop="lastLoginTime"
        >
          <template #default="scope">
            <span>{{ scope.row.lastLoginTime || '暂未登录' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="left"
          label="启用"
          min-width="90"
        >
          <template #default="scope">
            <el-switch
              v-model="scope.row.enable"
              :active-value="1"
              :inactive-value="2"
              inline-prompt
              @change="() => { switchEnable(scope.row) }"
            />
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          min-width="300"
        >
          <template #default="scope">
            <el-popover
              v-model:visible="scope.row.visible"
              placement="top"
              width="160"
            >
              <p>确定要删除此用户吗</p>
              <div style="text-align: right; margin-top: 8px">
                <el-button
                  v-preReClick
                  link
                  type="primary"
                  @click="scope.row.visible = false"
                >
                  取消
                </el-button>
                <el-button
                  v-preReClick
                  type="primary"
                  @click="deleteUserFunc(scope.row)"
                >
                  确定
                </el-button>
              </div>
              <template #reference>
                <el-button
                  v-preReClick
                  icon="delete"
                  link
                  type="primary"
                >
                  删除
                </el-button>
              </template>
            </el-popover>
            <el-button
              v-preReClick
              icon="edit"
              link
              type="primary"
              @click="openEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              v-preReClick
              icon="setting"
              link
              type="primary"
              @click="openAuthSetting(scope.row)"
            >
              认证设置
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--分页-->
      <div class="gva-pagination">
        <el-pagination
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>

    <!--新增/编辑用户弹窗-->
    <el-dialog
      v-model="addUserDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      :title="dialogFlag === 'add' ? '新增用户' : '编辑用户'"
    >
      <div style="height: 60vh; overflow: auto; padding: 0 12px">
        <el-form
          ref="userFormRef"
          :model="userInfo"
          :rules="rules"
          label-width="120px"
        >
          <el-form-item
            v-if="dialogFlag === 'add'"
            label="账号名"
            prop="userName"
          >
            <el-input
              v-model="userInfo.userName"
              placeholder="请输入账号名"
            />
          </el-form-item>
          <el-form-item
            label="昵称"
            prop="nickName"
          >
            <el-input
              v-model="userInfo.nickName"
              placeholder="请输入昵称"
            />
          </el-form-item>
          <el-form-item
            label="手机号"
            prop="phone"
          >
            <el-input
              v-model="userInfo.phone"
              placeholder="请输入手机号"
            />
          </el-form-item>
          <el-form-item
            label="邮箱"
            prop="email"
          >
            <el-input
              v-model="userInfo.email"
              placeholder="请输入邮箱"
            />
          </el-form-item>
          <el-form-item
            label="二次认证方式"
            prop="authMethod"
          >
            <el-radio-group v-model="userInfo.authMethod">
              <el-radio value="ukey">
                智能密码钥匙
              </el-radio>
              <el-radio value="sms">
                手机短信
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            v-if="userInfo.authMethod === 'ukey'"
            label="证书公钥"
            prop="authIdentifier"
          >
            <el-input
              v-model="userInfo.authIdentifier"
              placeholder="请输入或粘贴数字证书公钥"
              type="textarea"
              :rows="3"
            />
          </el-form-item>
          <el-form-item
            v-if="userInfo.authMethod === 'sms'"
            label="认证手机号"
            prop="authPhone"
          >
            <el-input
              v-model="userInfo.authPhone"
              placeholder="请输入用于接收验证码的手机号"
            />
            <span style="font-size: 12px; color: #909399">
              留空则使用上方手机号
            </span>
          </el-form-item>
          <el-form-item
            label="启用"
            prop="enable"
          >
            <el-switch
              v-model="userInfo.enable"
              :active-value="1"
              :inactive-value="2"
              inline-prompt
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-preReClick
            @click="closeAddUserDialog"
          >
            取 消
          </el-button>
          <el-button
            v-preReClick
            type="primary"
            @click="enterAddUserDialog"
          >
            确 定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!--认证设置弹窗-->
    <el-dialog
      v-model="authSettingDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      title="二次认证设置"
      width="500px"
    >
      <div style="padding: 0 12px">
        <el-form
          ref="authFormRef"
          :model="authSettingInfo"
          label-width="100px"
        >
          <el-divider content-position="left">
            用户信息
          </el-divider>
          <el-form-item label="账号名">
            <el-input
              :model-value="authSettingInfo.userName"
              readonly
            />
          </el-form-item>
          <el-form-item label="昵称">
            <el-input
              :model-value="authSettingInfo.nickName"
              readonly
            />
          </el-form-item>
          <el-divider content-position="left">
            认证配置
          </el-divider>
          <el-form-item
            label="认证方式"
            prop="authMethod"
          >
            <el-radio-group v-model="authSettingInfo.authMethod">
              <el-radio value="ukey">
                智能密码钥匙
              </el-radio>
              <el-radio value="sms">
                手机短信
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            v-if="authSettingInfo.authMethod === 'ukey'"
            label="证书公钥"
            prop="authIdentifier"
          >
            <el-input
              v-model="authSettingInfo.authIdentifier"
              placeholder="请输入数字证书公钥"
              type="textarea"
              :rows="3"
            />
            <el-button
              v-preReClick
              type="primary"
              size="small"
              style="margin-top: 8px"
              @click="mockReadCertFromKey"
            >
              模拟读取Key证书
            </el-button>
          </el-form-item>
          <el-form-item
            v-if="authSettingInfo.authMethod === 'sms'"
            label="认证手机号"
            prop="authPhone"
          >
            <el-input
              v-model="authSettingInfo.authPhone"
              placeholder="请输入接收验证码的手机号"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-preReClick
            @click="authSettingDialog = false"
          >
            取 消
          </el-button>
          <el-button
            v-preReClick
            type="primary"
            @click="saveAuthSetting"
          >
            保 存
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!--导入结果弹窗-->
    <el-dialog
      v-model="importResultDialog"
      title="导入结果"
      width="500px"
    >
      <div style="padding: 12px">
        <el-alert
          :type="importResult.successCount > 0 ? 'success' : 'error'"
          :closable="false"
        >
          <template #title>
            成功导入 {{ importResult.successCount }} 条，
            失败 {{ importResult.failCount }} 条
          </template>
        </el-alert>
        <div
          v-if="importResult.errors.length > 0"
          style="margin-top: 12px"
        >
          <p style="font-weight: bold; margin-bottom: 8px">
            失败详情：
          </p>
          <div
            v-for="(err, index) in importResult.errors"
            :key="index"
            style="font-size: 13px; color: #f56c6c; margin-bottom: 4px"
          >
            {{ err }}
          </div>
        </div>
      </div>
      <template #footer>
        <el-button
          v-preReClick
          type="primary"
          @click="importResultDialog = false"
        >
          知道了
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { nextTick, ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { DocumentCopy } from '@element-plus/icons-vue'
import CustomPic from '@/components/customPic/index.vue'
import ChooseImg from '@/components/chooseImg/index.vue'
import WarningBar from '@/components/warningBar/warningBar.vue'
// Excel导入功能利用xlsx依赖实现：npm install xlsx//后端删除
import * as XLSX from 'xlsx'//后端删除

/*import{

}from'@'//导入后端接口*/

defineOptions({
  name: 'SecondAuthUser'
})

const path = ref(import.meta.env.VITE_BASE_API + '/')

//
// mock数据生成
// 生成随机证书公钥（模拟Base64编码的证书）
const generateMockCertKey = () => {
  const chars = 'QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm0123456789+/='
  let result = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A'
  for (let i = 0; i < 200; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return result
}

// 初始mock用户数据
const mockUserList = ref([
  {
    ID: 1,
    uuid: 'uuid-001',
    userName: 'zhangsan',
    nickName: '张三',
    phone: '13800138001',
    email: 'zhangsan@example.com',
    headerImg: '',
    authMethod: 'ukey',
    authIdentifier: generateMockCertKey(),
    lastLoginTime: '2026-07-24 00:00:00',
    enable: 1,
    password: '123456',
    visible: false
  },
  {
    ID: 2,
    uuid: 'uuid-002',
    userName: 'lisi',
    nickName: '李四',
    phone: '13800138002',
    email: 'lisi@example.com',
    headerImg: '',
    authMethod: 'sms',
    authIdentifier: '13800138002',
    lastLoginTime: '2026-07-23 00:00:01',
    enable: 1,
    password: '123456',
    visible: false
  },
  {
    ID: 3,
    uuid: 'uuid-003',
    userName: 'wangwu',
    nickName: '王五',
    phone: '13800138003',
    email: 'wangwu@example.com',
    headerImg: '',
    authMethod: 'ukey',
    authIdentifier: generateMockCertKey(),
    lastLoginTime: '2026-07-22 00:00:02',
    enable: 1,
    password: '123456',
    visible: false
  },
  {
    ID: 4,
    uuid: 'uuid-004',
    userName: 'qwe',
    nickName: 'qwe',
    phone: '13800138004',
    email: 'qwe@qwe.com',
    headerImg: '',
    authMethod: 'sms',
    authIdentifier: '13800138004',
    lastLoginTime: null,
    enable: 2,
    password: '123456',
    visible: false
  },
  {
    ID: 5,
    uuid: 'uuid-005',
    userName: 'rty',
    nickName: 'rty',
    phone: '13800138005',
    email: 'rty@rty.com',
    headerImg: '',
    authMethod: 'ukey',
    authIdentifier: generateMockCertKey(),
    lastLoginTime: '2026-07-20 00:00:03',
    enable: 1,
    password: '123456',
    visible: false
  },
  {
    ID: 6,
    uuid: 'uuid-006',
    userName: 'uio',
    nickName: 'uio',
    phone: '13900139001',
    email: 'uio@uio.com',
    headerImg: '',
    authMethod: 'sms',
    authIdentifier: '13900139001',
    lastLoginTime: '2026-07-19 00:00:04',
    enable: 1,
    password: '123456',
    visible: false
  },
  {
    ID: 7,
    uuid: 'uuid-007',
    userName: 'asd',
    nickName: 'asd',
    phone: '13900139002',
    email: 'asd@asd.com',
    headerImg: '',
    authMethod: 'ukey',
    authIdentifier: generateMockCertKey(),
    lastLoginTime: null,
    enable: 1,
    password: '123456',
    visible: false
  },
  {
    ID: 8,
    uuid: 'uuid-008',
    userName: 'fgh',
    nickName: 'fgh',
    phone: '13900139003',
    email: 'fgh@fgh.com',
    headerImg: '',
    authMethod: 'sms',
    authIdentifier: '13900139003',
    lastLoginTime: '2026-07-18 00:00:05',
    enable: 1,
    password: '123456',
    visible: false
  }
])

// 模拟系统用户库
const mockSystemUserList = [
  {
    userName: 'sysuser1',
    nickName: '1',
    phone: '15000150001',
    email: '1@1.com',
    headerImg: '',
    authMethod: 'ukey',
    authIdentifier: generateMockCertKey(),
    lastLoginTime: null,
    enable: 1,
    password: '123456'
  },
  {
    userName: 'sysuser2',
    nickName: '2',
    phone: '15000150002',
    email: '2@2.com',
    headerImg: '',
    authMethod: 'sms',
    authIdentifier: '15000150002',
    lastLoginTime: '2026-07-20 00:00:06',
    enable: 1,
    password: '123456'
  },
  {
    userName: 'zhangsan',
    nickName: '张三(系统)',
    phone: '15000150003',
    email: 'zhangsan@example.com',
    headerImg: '',
    authMethod: 'ukey',
    authIdentifier: generateMockCertKey(),
    lastLoginTime: '2026-07-24 00:00:07',
    enable: 1,
    password: '123456'
  }
]

// 用于生成自增ID
let nextId = ref(9)

//
// 响应式状态
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const filterAuthMethod = ref('')
const filterKeyword = ref('')
const fileInputRef = ref(null)

// 弹窗相关
const addUserDialog = ref(false)
const authSettingDialog = ref(false)
const importResultDialog = ref(false)
const dialogFlag = ref('add')

const userInfo = ref({
  userName: '',
  password: '',
  nickName: '',
  phone: '',
  email: '',
  headerImg: '',
  authMethod: 'ukey',
  authIdentifier: '',
  authPhone: '',
  enable: 1
})

const authSettingInfo = ref({
  ID: null,
  uuid: '',
  userName: '',
  nickName: '',
  authMethod: 'ukey',
  authIdentifier: '',
  authPhone: ''
})

const importResult = ref({
  successCount: 0,
  failCount: 0,
  errors: []
})

const userFormRef = ref(null)
const authFormRef = ref(null)
const chooseImgRef = ref(null)

//
// 表单验证规则
const rules = ref({
  userName: [
    { required: true, message: '请输入账号名', trigger: 'blur' },
    { min: 3, message: '最低3位字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '最低6位字符', trigger: 'blur' }
  ],
  nickName: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  phone: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入合法手机号',
      trigger: 'blur'
    }
  ],
  email: [
    {
      pattern: /^([0-9A-Za-z\-_.]+)@([0-9a-z]+\.[a-z]{2,3}(\.[a-z]{2})?)$/,
      message: '请输入正确的邮箱',
      trigger: 'blur'
    }
  ],
  authMethod: [
    { required: true, message: '请选择二次认证方式', trigger: 'change' }
  ],
  authIdentifier: [
    { required: true, message: '请输入证书公钥', trigger: 'blur' }
  ],
  authPhone: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入合法手机号',
      trigger: 'blur'
    }
  ]
})

//
// 工具函数
// 截断证书公钥显示
const truncateCertKey = (key) => {
  if (!key) return '-'
  if (key.length <= 30) return key
  return key.substring(0, 20) + '...' + key.substring(key.length - 10)
}

// 复制功能
const copyToClipboard = async(text) => {
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success('已复制到剪贴板')
  } catch {
    ElMessage.error('复制失败，请手动复制')
  }
}

//
// 分页与筛选
const getFilteredList = () => {
  let list = [...mockUserList.value]
  if (filterAuthMethod.value) {
    list = list.filter(item => item.authMethod === filterAuthMethod.value)
  }
  if (filterKeyword.value) {
    const keyword = filterKeyword.value.toLowerCase()
    list = list.filter(item =>
      item.userName.toLowerCase().includes(keyword) ||
      item.nickName.toLowerCase().includes(keyword)
    )
  }
  return list
}

const getTableData = () => {
  const filteredList = getFilteredList()
  total.value = filteredList.length
  const start = (page.value - 1) * pageSize.value
  const end = start + pageSize.value
  tableData.value = filteredList.slice(start, end).map(item => ({
    ...item,
    visible: item.visible || false
  }))
}

const handleSizeChange = (val) => {
  pageSize.value = val
  page.value = 1
  getTableData()
}

const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

const handleFilterChange = () => {
  page.value = 1
  getTableData()
}

//
// 新增/编辑用户
const addUser = () => {
  dialogFlag.value = 'add'
  userInfo.value = {
    userName: '',
    password: '',
    nickName: '',
    phone: '',
    email: '',
    headerImg: '',
    authMethod: 'ukey',
    authIdentifier: '',
    authPhone: '',
    enable: 1
  }
  addUserDialog.value = true
  nextTick(() => {
    userFormRef.value?.resetFields()
  })
}

const openEdit = (row) => {
  dialogFlag.value = 'edit'
  const source = { ...row }
  userInfo.value = {
    ID: source.ID,
    uuid: source.uuid,
    userName: source.userName,
    password: '',
    nickName: source.nickName || '',
    phone: source.phone || '',
    email: source.email || '',
    headerImg: source.headerImg || '',
    authMethod: source.authMethod || 'ukey',
    authIdentifier: source.authIdentifier || '',
    authPhone: source.authMethod === 'sms' ? (source.authIdentifier || source.phone || '') : '',
    enable: source.enable ?? 1
  }
  addUserDialog.value = true
  nextTick(() => {
    userFormRef.value?.clearValidate()
  })
}

const closeAddUserDialog = () => {
  userFormRef.value?.resetFields()
  userInfo.value.headerImg = ''
  userInfo.value.authIdentifier = ''
  userInfo.value.authPhone = ''
  addUserDialog.value = false
}

const enterAddUserDialog = async() => {
  // 动态调整验证规则
  if (userInfo.value.authMethod === 'sms') {
    rules.value.authIdentifier = [{ required: false }]
  } else {
    rules.value.authIdentifier = [
      { required: true, message: '请输入证书公钥', trigger: 'blur' }
    ]
  }

  userFormRef.value?.validate(async(valid) => {
    if (valid) {
      const now = new Date()
      const timeStr = now.getFullYear() + '-' +
        String(now.getMonth() + 1).padStart(2, '0') + '-' +
        String(now.getDate()).padStart(2, '0') + ' ' +
        String(now.getHours()).padStart(2, '0') + ':' +
        String(now.getMinutes()).padStart(2, '0') + ':' +
        String(now.getSeconds()).padStart(2, '0')

      if (dialogFlag.value === 'add') {
        // 新增
        const newUser = {
          ID: nextId.value++,
          uuid: 'uuid-' + Date.now(),
          userName: userInfo.value.userName,
          nickName: userInfo.value.nickName,
          phone: userInfo.value.phone,
          email: userInfo.value.email,
          headerImg: userInfo.value.headerImg,
          authMethod: userInfo.value.authMethod,
          authIdentifier: userInfo.value.authMethod === 'ukey'
            ? userInfo.value.authIdentifier
            : (userInfo.value.authPhone || userInfo.value.phone),
          lastLoginTime: null,
          enable: userInfo.value.enable,
          password: userInfo.value.password,
          visible: false
        }
        mockUserList.value.unshift(newUser)
        ElMessage({ type: 'success', message: '新增用户成功' })
      } else {
        // 编辑
        const index = mockUserList.value.findIndex(
          item => item.ID === userInfo.value.ID || item.uuid === userInfo.value.uuid
        )
        if (index !== -1) {
          mockUserList.value[index] = {
            ...mockUserList.value[index],
            nickName: userInfo.value.nickName,
            phone: userInfo.value.phone,
            email: userInfo.value.email,
            headerImg: userInfo.value.headerImg,
            authMethod: userInfo.value.authMethod,
            authIdentifier: userInfo.value.authMethod === 'ukey'
              ? userInfo.value.authIdentifier
              : (userInfo.value.authPhone || userInfo.value.phone),
            enable: userInfo.value.enable
          }
          ElMessage({ type: 'success', message: '编辑用户成功' })
        }
      }
      closeAddUserDialog()
      getTableData()
    }
  })
}

//
// 删除用户
const deleteUserFunc = async(row) => {
  const index = mockUserList.value.findIndex(
    item => item.ID === row.ID || item.uuid === row.uuid
  )
  if (index !== -1) {
    mockUserList.value.splice(index, 1)
    row.visible = false
    ElMessage.success('删除成功')
    getTableData()
  }
}

//
// 启用/禁用
const switchEnable = async(row) => {
  const index = mockUserList.value.findIndex(
    item => item.ID === row.ID || item.uuid === row.uuid
  )
  if (index !== -1) {
    mockUserList.value[index].enable = row.enable
    const statusText = row.enable === 2 ? '禁用' : '启用'
    ElMessage({ type: 'success', message: `${statusText}成功` })
    getTableData()
  }
}

//
// 认证设置弹窗
const openAuthSetting = (row) => {
  authSettingInfo.value = {
    ID: row.ID,
    uuid: row.uuid,
    userName: row.userName,
    nickName: row.nickName,
    authMethod: row.authMethod || 'ukey',
    authIdentifier: row.authMethod === 'ukey' ? (row.authIdentifier || '') : '',
    authPhone: row.authMethod === 'sms' ? (row.authIdentifier || row.phone || '') : ''
  }
  authSettingDialog.value = true
  nextTick(() => {
    authFormRef.value?.clearValidate()
  })
}

const saveAuthSetting = () => {
  const index = mockUserList.value.findIndex(
    item => item.ID === authSettingInfo.value.ID || item.uuid === authSettingInfo.value.uuid
  )
  if (index !== -1) {
    mockUserList.value[index].authMethod = authSettingInfo.value.authMethod
    mockUserList.value[index].authIdentifier = authSettingInfo.value.authMethod === 'ukey'
      ? authSettingInfo.value.authIdentifier
      : (authSettingInfo.value.authPhone || mockUserList.value[index].phone)
    ElMessage({ type: 'success', message: '认证设置已保存' })
  }
  authSettingDialog.value = false
  getTableData()
}

// 模拟从Key读取证书
const mockReadCertFromKey = () => {
  authSettingInfo.value.authIdentifier = generateMockCertKey()
  ElMessage({ type: 'success', message: '已模拟读取Key证书公钥' })
}

//
// Excel导入
const triggerImport = () => {
  fileInputRef.value?.click()
}

const handleFileChange = async(event) => {
  const file = event.target.files?.[0]
  if (!file) return

  // 重置input以便可以重复选择同一文件
  event.target.value = ''

  try {
    // 导入xlsx库
    const XLSX = await import('xlsx').catch(() => {
      throw new Error('请先安装xlsx依赖：npm install xlsx')
    })

    const data = await readFileAsArrayBuffer(file)
    const workbook = XLSX.read(data, { type: 'array' })
    const firstSheet = workbook.Sheets[workbook.SheetNames[0]]
    const jsonData = XLSX.utils.sheet_to_json(firstSheet, { defval: '' })

    if (jsonData.length === 0) {
      ElMessage.warning('Excel文件中没有数据')
      return
    }

    processImportData(jsonData)
  } catch (error) {
    console.error('Excel导入失败:', error)
    if (error.message?.includes('xlsx')) {
      ElMessage.error('请先安装xlsx依赖：npm install xlsx')
    } else {
      ElMessage.error('Excel文件解析失败，请检查文件格式')
    }
  }
}

const readFileAsArrayBuffer = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = (e) => resolve(new Uint8Array(e.target.result))
    reader.onerror = reject
    reader.readAsArrayBuffer(file)
  })
}

const processImportData = (jsonData) => {
  importResult.value = { successCount: 0, failCount: 0, errors: [] }
  const existingUserNames = new Set(mockUserList.value.map(u => u.userName))

  jsonData.forEach((row, index) => {
    const rowNum = index + 2 // Excel行号（从第2行开始，第1行是表头）
    const userName = String(row['账号名'] || row['userName'] || '').trim()
    const nickName = String(row['昵称'] || row['nickName'] || '').trim()
    const phone = String(row['手机号'] || row['phone'] || '').trim()
    const email = String(row['邮箱'] || row['email'] || '').trim()
    let authMethodRaw = String(row['二次认证方式'] || row['authMethod'] || '').trim()
    let authIdentifier = String(row['绑定标识'] || row['authIdentifier'] || '').trim()

    // 验证必填字段
    if (!userName) {
      importResult.value.errors.push(`第${rowNum}行：账号名不能为空`)
      importResult.value.failCount++
      return
    }
    if (!nickName) {
      importResult.value.errors.push(`第${rowNum}行：昵称不能为空`)
      importResult.value.failCount++
      return
    }

    // 转换认证方式
    let authMethod = 'ukey'
    if (authMethodRaw === '手机短信' || authMethodRaw === 'sms') {
      authMethod = 'sms'
    } else if (authMethodRaw === '智能密码钥匙' || authMethodRaw === 'ukey' || authMethodRaw === '') {
      authMethod = 'ukey'
    } else {
      importResult.value.errors.push(`第${rowNum}行：二次认证方式不合法，应为"智能密码钥匙"或"手机短信"`)
      importResult.value.failCount++
      return
    }

    // 检查账号名是否重复
    if (existingUserNames.has(userName)) {
      importResult.value.errors.push(`第${rowNum}行：账号名"${userName}"已存在，跳过`)
      importResult.value.failCount++
      return
    }

    // 添加用户
    const newUser = {
      ID: nextId.value++,
      uuid: 'uuid-import-' + Date.now() + '-' + index,
      userName,
      nickName,
      phone,
      email,
      headerImg: '',
      authMethod,
      authIdentifier: authIdentifier || (authMethod === 'sms' ? phone : ''),
      lastLoginTime: null,
      enable: 1,
      password,
      visible: false
    }
    mockUserList.value.unshift(newUser)
    existingUserNames.add(userName)
    importResult.value.successCount++
  })

  getTableData()
  importResultDialog.value = true

  if (importResult.value.successCount > 0 && importResult.value.failCount === 0) {
    ElMessage.success(`成功导入 ${importResult.value.successCount} 条用户数据`)
  }
}

// 下载模板
const downloadTemplate = async() => {
  try {
    const XLSX = await import('xlsx').catch(() => {
      throw new Error('请先安装xlsx依赖：npm install xlsx')
    })

    // 模板数据
    const templateData = [
      {
        '账号名': 'example_user1',
        '昵称': '示例用户',
        '二次认证方式': '智能密码钥匙',
        '绑定标识': '证书公钥填写此处（ukey模式）',
        '手机号': '13xxxxxxxxx',
        '邮箱': 'example1@example.com'
      },
      {
        '账号名': 'example_user2',
        '昵称': '示例用户2',
        '二次认证方式': '手机短信',
        '绑定标识': '13xxxxxxxxx',
        '手机号': '13xxxxxxxxx',
        '邮箱': 'example2@example.com'
      }
    ]

    const worksheet = XLSX.utils.json_to_sheet(templateData)
    // 设置列宽
    worksheet['!cols'] = [
      { wch: 18 },
      { wch: 12 },
      { wch: 14 },
      { wch: 16 },
      { wch: 35 },
      { wch: 16 },
      { wch: 25 }
    ]
    const workbook = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(workbook, worksheet, '用户导入模板')
    XLSX.writeFile(workbook, '用户导入模板.xlsx')
    ElMessage.success('模板下载成功')
  } catch (error) {
    console.error('模板下载失败:', error)
    if (error.message?.includes('xlsx')) {
      ElMessage.error('请先安装xlsx依赖：npm install xlsx')
    } else {
      ElMessage.error('模板下载失败')
    }
  }
}

//
// 同步系统用户
const syncSystemUsers = () => {
  const existingUserNames = new Set(mockUserList.value.map(u => u.userName))
  let syncCount = 0
  let skipCount = 0

  mockSystemUserList.forEach(sysUser => {
    if (existingUserNames.has(sysUser.userName)) {
      skipCount++
    } else {
      const newUser = {
        ID: nextId.value++,
        uuid: 'uuid-sync-' + Date.now() + '-' + syncCount,
        ...sysUser,
        visible: false
      }
      mockUserList.value.unshift(newUser)
      existingUserNames.add(sysUser.userName)
      syncCount++
    }
  })

  getTableData()
  ElMessage.success(
    `同步完成：新增 ${syncCount} 个用户，跳过 ${skipCount} 个已存在用户`
  )
}

//
// 初始化
onMounted(() => {
  getTableData()
})
</script>

<style lang="scss" scoped>
.filter-area {
  display: flex;
  align-items: center;
  margin-top: 16px;
  padding: 0 4px;

  .filter-label {
    font-size: 14px;
    color: #606266;
    margin-right: 8px;
    white-space: nowrap;
  }
}

.cert-pubkey-text {
  font-size: 13px;
  color: #606266;
  word-break: break-all;
  cursor: default;
}

.header-img-box {
  @apply w-52 h-52 border border-solid border-gray-300 rounded-xl flex justify-center items-center cursor-pointer;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.gva-btn-list {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}
</style>