<template>
  <el-dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    :show-close="false"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    center
    :width="dialogWidth"
  >
    <div style="text-align: center; padding: 20px;">
      <!-- 提示文本 -->
      <div style="font-size: 1.2rem; margin-bottom: 10px; color: #606266;">
        {{ promptText }}
      </div>
      
      <!-- 权限级别显示 -->
      <div v-if="permissionLevel" style="font-size: 1rem; margin-bottom: 20px; color: #E6A23C; font-weight: 600;">
        权限级别：{{ permissionLevel }}
      </div>
      
      <!-- 密码输入框 -->
      <el-input
        ref="passwordInput"
        v-model="password"
        type="password"
        placeholder="请输入密码"
        show-password
        clearable
        style="width: 100%; max-width: 360px; font-size: 1.1rem;"
        @keyup.enter="handleSubmit"
        @focus="handleInputFocus"
      >
        <template #prefix>
          <el-icon><Lock /></el-icon>
        </template>
      </el-input>
      
      <!-- 错误提示 -->
      <div v-if="errorMessage" style="color: #F56C6C; margin-top: 10px; font-size: 0.9rem;">
        {{ errorMessage }}
      </div>
    </div>
    
    <!-- 底部按钮 -->
    <template #footer>
      <div class="dialog-footer" style="text-align: center;">
        <el-button @click="handleCancel" style="width: 200px;">取消权限确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, nextTick, watch, defineExpose, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Lock } from '@element-plus/icons-vue'
import Cookie from 'js-cookie'

const dialogVisible = ref(false)
const dialogTitle = ref('权限确认')
const promptText = ref('请输入密码进行权限验证')
const permissionLevel = ref('INFO')
const password = ref('')
const loading = ref(false)
const errorMessage = ref('')
const passwordInput = ref(null)

// 自适应竖屏PAD的对话框宽度
const dialogWidth = computed(() => (window.innerWidth < 800 ? '92vw' : '520px'))

let resolve = null
let reject = null
let CreateData = null
let ExecDatabase = null
let $store = null

// 显示权限确认弹窗
const show = (options = {}) => {
  return new Promise((res, rej) => {
    dialogTitle.value = options.title || '权限确认'
    promptText.value = options.promptText || '请刷卡进行权限验证'
    permissionLevel.value = options.permissionLevel || ''
    password.value = ''
    errorMessage.value = ''
    loading.value = false
    resolve = res
    reject = rej
    dialogVisible.value = true
    // 等待DOM更新后聚焦输入框
    nextTick(() => {
      // 多次尝试聚焦，确保对话框完全渲染
      setTimeout(() => {
        if (passwordInput.value && passwordInput.value.$el) {
          // Element Plus 的 Input 组件需要访问 $el
          const inputElement = passwordInput.value.$el.querySelector('input')
          if (inputElement) {
            inputElement.focus()
          }
        }
      }, 100)
    })
  })
}

// 处理输入框聚焦事件
const handleInputFocus = () => {
  errorMessage.value = ''
}

// 权限验证方法
const verifyPermission = async (pwd) => {
  try {
    const param = []
    param[0] = ['工位号', $store?.state?.station?.stationNumber || '']
    param[1] = ['卡号', pwd]
    param[2] = ['操作人', $store?.state?.user?.name || '']
    param[3] = ['权限级别', permissionLevel.value || '']

    const data = CreateData('11', '人员刷卡权限校验', param)
    const response = await ExecDatabase(data)

    if (response.data.length > 0) {
      const result = response.data[0]

      // 根据存储过程返回结果判断
      if (result.result === 1) {
        return {
          success: true,
          data: result,
          message: result.msg
        }
      } else {
        return {
          success: false,
          message: result.msg || '权限验证失败'
        }
      }
    } else {
      return {
        success: false,
        message: '权限验证失败，验证执行失败'
      }
    }
  } catch (error) {
    console.error('权限验证接口调用失败:', error)
    throw error
  }
}

// 处理提交
const handleSubmit = async () => {
  if (!password.value.trim()) {
    errorMessage.value = '请输入密码'
    return
  }

  loading.value = true
  errorMessage.value = ''

  try {
    // 调用人员刷卡权限校验存储过程
    const result = await verifyPermission(password.value)

    if (result.success) {
      ElMessage.success('权限验证成功')
      dialogVisible.value = false
      // 写入 Cookie（有效期1天）
      try {
        if (result.data && result.data.userId) {
          Cookie.set('userId', String(result.data.userId), { expires: 1 })
        }
        if (result.data && result.data.userName) {
          Cookie.set('userName', result.data.userName, { expires: 1 })
        }
      } catch (e) {
        console.warn('写入Cookie失败:', e)
      }
      if (resolve) {
        resolve({
          success: true,
          data: result.data,
          message: result.message
        })
      }
    } else {
      errorMessage.value = result.message
      password.value = ''
      // 重新聚焦输入框
      nextTick(() => {
        if (passwordInput.value) {
          passwordInput.value.focus()
        }
      })
    }
  } catch (error) {
    console.error('权限验证异常:', error)
    errorMessage.value = '权限验证异常，请重试'
    password.value = ''
    nextTick(() => {
      if (passwordInput.value) {
        passwordInput.value.focus()
      }
    })
  } finally {
    loading.value = false
  }
}

// 处理取消
const handleCancel = () => {
  dialogVisible.value = false
  if (reject) {
    reject({
      success: false,
      message: '用户取消操作',
      cancelled: true
    })
  }
}

// 监听对话框显示状态，自动聚焦密码输入框
watch(dialogVisible, (newVal) => {
  if (newVal) {
    nextTick(() => {
      setTimeout(() => {
        if (passwordInput.value && passwordInput.value.$el) {
          const inputElement = passwordInput.value.$el.querySelector('input')
          if (inputElement) {
            inputElement.focus()
            inputElement.select() // 选中输入框内容
          }
        }
      }, 200) // 给对话框足够的渲染时间
    })
  }
})

// 暴露给父组件的方法和属性
defineExpose({
  show,
  handleInputFocus,
  handleSubmit,
  handleCancel,
  setCreateData(fn) {
    CreateData = fn
  },
  setExecDatabase(fn) {
    ExecDatabase = fn
  },
  setStore(store) {
    $store = store
  }
})
</script>

<style lang="scss" scoped>
:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  padding: 20px 20px 10px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-dialog__title) {
  font-weight: 600;
  color: #303133;
}

:deep(.el-dialog__body) {
  padding: 30px 20px;
}

:deep(.el-input__wrapper) {
  height: 40px;
}

:deep(.el-input__inner) {
  height: 40px;
  line-height: 40px;
}

:deep(.el-input__prefix) {
  display: flex;
  align-items: center;
}

.dialog-footer {
  padding: 10px 20px 20px;
  
  .el-button {
    min-width: 80px;
  }
}
</style>