<template>
  <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" :show-close="false" :close-on-click-modal="false"
    :close-on-press-escape="false" center width="40%">
    <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: 300px; font-size: 1.1rem;" @keyup.enter.native="handleSubmit" @focus="handleInputFocus">
        <i slot="prefix" class="el-icon-lock"></i>
      </el-input>

      <!-- 错误提示 -->
      <div v-if="errorMessage" style="color: #F56C6C; margin-top: 10px; font-size: 0.9rem;">
        {{ errorMessage }}
      </div>
    </div>

    <!-- 底部按钮 -->
    <div slot="footer" class="dialog-footer" style="text-align: center;">
      <el-button @click="handleCancel" style="width: 200px;">取消权限确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { logAdd } from '@/utils/EventBus'

const PermissionVerify = {
  name: 'PermissionVerify',
  data() {
    return {
      dialogVisible: false,
      dialogTitle: '权限确认',
      promptText: '请输入密码进行权限验证',
      permissionLevel: 'INFO',
      password: '',
      loading: false,
      errorMessage: '',
      resolve: null,
      reject: null
    }
  },
  methods: {
    /**
     * 显示权限确认弹窗
     * @param {Object} options 配置项
     * @param {string} options.title 弹窗标题
     * @param {string} options.promptText 提示文本
     * @param {string} options.permissionLevel 权限级别
     * @returns {Promise} 返回Promise，成功时resolve，失败时reject
     */
    show(options = {}) {
      return new Promise((resolve, reject) => {
        this.dialogTitle = options.title || '权限确认'
        this.promptText = options.promptText || '请刷卡进行权限验证'
        this.permissionLevel = options.permissionLevel || ''
        this.password = ''
        this.errorMessage = ''
        this.loading = false
        this.resolve = resolve
        this.reject = reject
        this.dialogVisible = true

        // 等待DOM更新后聚焦输入框
        this.$nextTick(() => {
          if (this.$refs.passwordInput) {
            this.$refs.passwordInput.focus()
          }
        })
      })
    },

    /**
     * 处理输入框聚焦事件
     */
    handleInputFocus() {
      this.errorMessage = ''
    },

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

      this.loading = true
      this.errorMessage = ''

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

        if (result.success) {
          this.$message.success('权限验证成功')
          
          logAdd(this, {
            stationNumber: this.$store.state.station.stationNumber,
            msgType: 'INFO',
            operationType: 'StationOperate',
            Content: `${this.$store.state.user.name}【${this.$store.state.user.account}】 ${this.dialogTitle} 刷卡校验成功`
          })

          this.dialogVisible = false
          if (this.resolve) {
            this.resolve({
              success: true,
              data: result.data,
              message: result.message
            })
          }
        } else {
          this.errorMessage = result.message
          this.password = ''
          // 重新聚焦输入框
          this.$nextTick(() => {
            if (this.$refs.passwordInput) {
              this.$refs.passwordInput.focus()
            }
          })
        }
      } catch (error) {
        console.error('权限验证异常:', error)
        this.errorMessage = '权限验证异常，请重试'
        this.password = ''
        this.$nextTick(() => {
          if (this.$refs.passwordInput) {
            this.$refs.passwordInput.focus()
          }
        })
      } finally {
        this.loading = false
      }
    },

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

    /**
     * 权限验证方法
     * @param {string} password 密码
     * @returns {Promise} 验证结果
     */
    async verifyPermission(password) {
      try {
        const param = []
        param[0] = ['工位号', this.$store.state.station.stationNumber]
        param[1] = ['卡号', password]
        param[2] = ['操作人', this.$store.state.user.name || '']
        param[3] = ['权限级别', this.permissionLevel || '']

        const data = this.CreateData('11', '人员刷卡权限校验', param)
        const response = await this.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
      }
    }
  },

  // 组件销毁时清理
  beforeDestroy() {
    if (this.reject && this.dialogVisible) {
      this.reject({
        success: false,
        message: '组件已销毁'
      })
    }
  }
}

// 命名导出
export { PermissionVerify }

// 默认导出
export default PermissionVerify
</script>

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

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

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

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

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

::v-deep .el-input__prefix {
  display: flex;
  align-items: center;
  left: 5px;
}

::v-deep .el-input__icon {
  line-height: 1;
}

.dialog-footer {
  padding: 10px 20px 20px;

  .el-button {
    min-width: 80px;
  }
}
</style>