<template>
  <el-dialog title="添加资源" v-model="dialogVisible" width="500px" @close="onClose">
    <el-form :model="form" label-width="100px" ref="resourceForm" :rules="rules">
      <el-form-item label="玩家ID">
        <el-input :value="userId" disabled></el-input>
      </el-form-item>
      <el-form-item label="玩家昵称">
        <el-input :value="nickname" disabled></el-input>
      </el-form-item>

      <el-form-item label="资源类型:" prop="resourceType">
        <el-select v-model="form.resourceType" placeholder="请选择资源类型" style="width: 100%">
          <el-option v-for="item in resourceTypes" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="数量:" prop="amount">
        <el-input
            v-model="form.amount"
            placeholder="请输入数量"
            @input="validateNumber"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="onClose">取消</el-button>
      <el-button type="primary" @click="onClick">确认添加</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {AddUserRes} from "@/api/gameUser";

export default {
  props: {
    value: {  // v-model 默认使用 value prop
      type: Boolean,
      default: false
    },
    userId: {
      type: Number,
      default: null
    },
    nickname:{
      type:String,
      default:'',
    },
  },

  data(){
    return {
      dialogVisible:this.value,
      user :{
        id: 0,
        nickname: '',
        resType:'',
        resValue:'',
      },

      form:{
        resourceType:'gold',
        amount:'',
        reason:''
      },
      resourceTypes:[
        {value:'gold', label:'金币'},
        {value:'diamond', label:'钻石'},
      ],
      rules:{
        resourceType:[
          {required:true, message:'请选择资源类型', trigger:'change'},
        ],
        amount:[
          {required:true, message:'请输入数量', trigger:'blur'},
          {validator:this.validateAmount,trigger: 'blur'}
        ]
      }
    }
  },

  watch:{
    value(newVal){
      // console.log("1userid:", this.userId)
      // console.log("visible prop changed:", newVal)
      this.dialogVisible = newVal
    },
    dialogVisible(newVal){
      // console.log("2userid:", this.userId)
      // console.log("dialogVisible visible prop changed:", newVal)
      this.$emit('input', newVal) // v-model 默认使用 input 事件
    }
  },

  methods:{
    onClose(){
      this.dialogVisible = false
      // console.log("关闭。dialogVisible:", this.dialogVisible)
      // this.$emit('input', false) // v-model 默认使用 input 事件
    },
    validateAmount(rule, value, callback){
      if(!value){
        callback(new Error('请输入数量'))
      }else if (!/^\d+$/.test(value)) {
        callback(new Error('请输入正整数'))
      } else if (parseInt(value) < 1) {
        callback(new Error('数量必须大于0'))
      } else {
        callback()
      }
    },
    validateNumber(value){
      this.form.amount = value.replace(/[^\d]/g, '')
    },
    async onClick(){
      // console.log('form:',this.form)
      this.user.id = this.userId
      this.user.resType = this.form.resourceType
      this.user.resValue = this.form.amount
      // 显示加载状态
      const loading = this.$loading({
        lock: true,
        text: '处理中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      try {
        const response = await AddUserRes({
          uid:+this.user.id,
          reason:'gm',
          res_type:this.user.resType,
          res_value:+this.user.resValue,
        })
        if (response.code !== 0) {
          console.error('添加资源失败:', response.msg || `请求失败，错误码: ${response.code}`)
          this.$message.error('添加资源失败:'+(response.msg || `请求失败，错误码: ${response.code}`))
          return
        }
        this.$message.info('添加资源成功')
      }catch (error){
        console.error('获取玩家数据失败:', error)
        this.$message.error('获取用户数据失败:'+error)
      }finally {
        // 关闭加载状态
        loading.close()
      }
      this.dialogVisible = false
    }
  }
}
</script>

<style scoped>
.dialog-footer {
  text-align: center;
}
</style>


