<template>
  <r-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="userName">
            <el-input
              v-model="form.userName"
              placeholder="请输入用户名称"
              clearable
              size="small"
              :disabled="isView"
            />
          </el-form-item>
        </el-col>
        <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-row>
      <el-row :gutter="20">
        <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-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-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户角色" prop="sysUserRoleDTOs">
            <el-select
              v-model="selectedRoleIds"
              multiple
              placeholder="请选择用户角色"
              clearable
              size="small"
              :disabled="isView"
              @change="handleRolesChange"
            >
              <el-option
                v-for="item in roleListData"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="默认密码" prop="password">
            <el-input
              placeholder="默认密码"
              value="ebiz2025"
              clearable
              size="small"
              :disabled="true"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer" v-if="!isView">
      <el-button
        type="primary"
        size="medium"
        :loading="loading"
        @click="submitForm"
        >确 定</el-button
      >
      <el-button size="medium" @click="handleClose">取 消</el-button>
    </div>
    <div slot="footer" class="dialog-footer" v-else>
      <el-button size="medium" @click="handleClose">关 闭</el-button>
    </div>
  </r-dialog>
</template>

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

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: {
        userCode: '',
        userName: '',
        realName: '',
        mobile: '',
        email: '',
        sysUserRoleDTOs: []
      },
      roleListData: [],
      selectedRoleIds: [], // 新增，用于绑定选中的角色ID数组
      rules: {
        realName: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' }
        ],
        userName: [
          { 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 }
          this.selectedRoleIds = this.form.sysUserRoleDTOs
        }
      },
      immediate: true
    }
  },
  created() {
    this.getRoleListData()
  },
  methods: {
    // 获取角色列表
    getRoleListData() {
      this.loading = true

      getRoleList({})
        .then(response => {
          this.roleListData = response.content.content || []
        })
        .catch(error => {
          this.$message.error('获取角色列表出错', error)
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleClose() {
      this.$refs.form.resetFields()
      this.$emit('update:visible', false)
      this.clearForm()
    },
    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(() => {
              this.$message.success(this.isEdit ? '修改成功' : '添加成功')
              this.$emit('submit', submitData)
              this.handleClose()
            })
            .catch(() => {
              this.$message.error(this.isEdit ? '修改用户出错' : '添加用户出错')
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    },
    // 处理角色选择变化
    handleRolesChange(roleIds) {
      this.form.sysUserRoleDTOs = roleIds.map(id => ({ roleId: id }))
    },
    clearForm() {
      this.form = {}
      this.selectedRoleIds = []
    }
  }
}
</script>

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