<template>
  <el-dialog :title="title" :visible.sync="visible" width="800px" append-to-body @close="handleClose">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户编码" prop="userCode">
            <el-input v-model="form.userCode" placeholder="请输入用户编码" clearable size="small" :disabled="isView || isEdit" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户名称" prop="userName">
            <el-input v-model="form.userName" placeholder="请输入用户名称" clearable size="small" :disabled="isView" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="真实姓名" prop="realName">
            <el-input v-model="form.realName" placeholder="请输入真实姓名" clearable size="small" :disabled="isView" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="form.mobile" placeholder="请输入手机号" clearable size="small" :disabled="isView" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" placeholder="请输入邮箱" clearable size="small" :disabled="isView" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户角色" prop="userRoles">
            <el-select v-model="form.userRoles" placeholder="请选择用户角色" clearable size="small" :disabled="isView">
              <el-option v-for="item in roleOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer" v-if="!isView">
      <el-button type="primary" size="small" :loading="loading" @click="submitForm">确 定</el-button>
      <el-button size="small" @click="handleClose">取 消</el-button>
    </div>
    <div slot="footer" class="dialog-footer" v-else>
      <el-button size="small" @click="handleClose">关 闭</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addUser, updateUser } from '@/api/generatedApi/system'

export default {
  name: 'UserDialog',
  props: {
    title: {
      type: String,
      default: '添加用户'
    },
    visible: {
      type: Boolean,
      default: false
    },
    userData: {
      type: Object,
      default: () => ({})
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    isView: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      form: {
        userRoles: '',
        userCode: '',
        userName: '',
        status: 0,
        dingtalkId: '',
        password: '',
        realName: '',
        jobNo: '',
        mobile: '',
        email: '',
        sysUserRoleDTOs: []
      },
      rules: {
        userCode: [{ required: true, message: '请输入用户编码', trigger: 'blur' }],
        userName: [{ required: true, message: '请输入用户名称', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      },
      roleOptions: [{ value: 'admin', label: '管理员' }, { value: 'user', label: '普通用户' }],
      loading: false
    }
  },
  watch: {
    userData: {
      handler(val) {
        if (val && Object.keys(val).length > 0) {
          this.form = { ...val }
        }
      },
      immediate: true
    }
  },
  methods: {
    handleClose() {
      this.$refs.form.resetFields()
      this.$emit('update:visible', false)
    },
    submitForm() {
      // 查看模式下不允许提交
      if (this.isView) {
        return
      }

      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true
          const submitData = { ...this.form }

          // 根据是否是编辑模式调用不同的API
          const apiRequest = this.isEdit ? updateUser(submitData) : addUser(submitData)

          apiRequest
            .then(response => {
              if (response.code === '0') {
                this.$message.success(this.isEdit ? '修改成功' : '添加成功')
                this.$emit('submit', submitData)
                this.handleClose()
              } else {
                this.$message.error(response.msg || (this.isEdit ? '修改失败' : '添加失败'))
              }
            })
            .catch(error => {
              console.error(this.isEdit ? '修改用户出错：' : '添加用户出错：', error)
              this.$message.error(this.isEdit ? '修改用户出错' : '添加用户出错')
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}
</style>
