﻿<template>
  <el-dialog
    v-model="visible"
    title="共享文件"
    width="500px"
    class="custom-dialog"
  >
    <el-form label-width="80px">
      <el-form-item label="文件名">
        <el-input :value="file?.name" disabled>
          <template #prefix><el-icon><Document /></el-icon></template>
        </el-input>
      </el-form-item>
      <el-form-item label="共享给">
        <el-select v-model="selectedUsers" multiple placeholder="选择用户" style="width: 100%">
          <el-option
            v-for="user in userList"
            :key="user.id"
            :label="user.nickname || user.username"
            :value="user.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="权限">
        <el-radio-group v-model="permission">
          <el-radio value="view">仅查看</el-radio>
          <el-radio value="edit">可编辑</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">
        <el-icon><Close /></el-icon>
        <span style="margin-left: 4px">取消</span>
      </el-button>
      <el-button type="primary" @click="handleShare" :disabled="selectedUsers.length === 0">
        <el-icon><Check /></el-icon>
        <span style="margin-left: 4px">保存</span>
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { Close, Check, Document } from '@element-plus/icons-vue'
import { getUsers } from '@/api/user'
import { ElMessage } from 'element-plus'

const props = defineProps({
  modelValue: Boolean,
  file: Object
})

const emit = defineEmits(['update:modelValue', 'share'])

const visible = computed({
  get: () => props.modelValue,
  set: (v) => emit('update:modelValue', v)
})

const selectedUsers = ref([])
const permission = ref('view')
const userList = ref([])

const loadUsers = async () => {
  try {
    const res = await getUsers()
    userList.value = res.data || []
  } catch (e) {
    ElMessage.error('获取用户列表失败')
  }
}

watch(visible, (v) => {
  if (v) {
    selectedUsers.value = []
    permission.value = 'view'
    loadUsers()
  }
})

const handleShare = () => {
  emit('share', {
    users: selectedUsers.value,
    permission: permission.value
  })
  visible.value = false
}
</script>
