<template>
  <a-modal
    :visible="visible"
    :title="isEdit ? '编辑工单' : '新建工单'"
    width="700px"
    @ok="handleOk"
    @cancel="handleCancel"
    @update:visible="handleVisibleChange"
    :confirm-loading="submitting"
  >
    <a-form :model="form" layout="vertical" ref="formRef">
      <a-form-item
        label="工单标题"
        field="title"
        :rules="[{ required: true, message: '请输入工单标题' }]"
      >
        <a-input
          v-model="form.title"
          placeholder="请输入工单标题"
          :max-length="100"
          show-word-limit
        />
      </a-form-item>

      <a-form-item
        label="工单类型"
        field="type"
        :rules="[{ required: true, message: '请选择工单类型' }]"
      >
        <a-select v-model="form.type" placeholder="请选择工单类型">
          <a-option value="incident">故障</a-option>
          <a-option value="request">请求</a-option>
          <a-option value="question">问题</a-option>
          <a-option value="other">其他</a-option>
        </a-select>
      </a-form-item>

      <a-form-item
        label="优先级"
        field="priority"
        :rules="[{ required: true, message: '请选择优先级' }]"
      >
        <a-select v-model="form.priority" placeholder="请选择优先级">
          <a-option value="low">低</a-option>
          <a-option value="medium">中</a-option>
          <a-option value="high">高</a-option>
          <a-option value="urgent">紧急</a-option>
        </a-select>
      </a-form-item>

      <a-form-item
        label="工单描述"
        field="description"
      >
        <a-textarea
          v-model="form.description"
          placeholder="请输入工单描述"
          :auto-size="{ minRows: 4, maxRows: 8 }"
          :max-length="1000"
          show-word-limit
        />
      </a-form-item>

      <!-- <a-form-item
        label="分类"
        field="category_name"
      >
        <a-input
          v-model="form.category_name"
          placeholder="请输入分类名称"
          :max-length="50"
        />
      </a-form-item> -->

      <a-form-item
        label="处理人"
        field="assignee_name"
      >
        <a-select
          v-model="form.assignee_name"
          placeholder="请选择处理人"
          :filter-option="true"
          show-search
          allow-clear
          :loading="loadingUsers"
          @change="handleAssigneeChange"
        >
          <a-option
            v-for="user in userList"
            :key="user.id"
            :value="user.name"
          >
            {{ user.name }} ({{ user.id }})
          </a-option>
        </a-select>
      </a-form-item>

      <a-form-item
        label="标签"
        field="tags"
      >
        <a-input
          v-model="form.tags"
          placeholder="多个标签用逗号分隔"
          :max-length="200"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import {
  createFeedbackTicket,
  updateFeedbackTicket,
} from '@/api/ops/feedbackTicket'
import { fetchUserList, type UserItem } from '@/api/ops/rbac2'

interface Ticket {
  id?: number
  title?: string
  description?: string
  type?: string
  priority?: string
  category_id?: number
  category_name?: string
  assignee_id?: number
  assignee_name?: string
  tags?: string
}

interface Props {
  visible: boolean
  ticket: Ticket | null
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const formRef = ref()
const loadingUsers = ref(false)
const submitting = ref(false)
const userList = ref<UserItem[]>([])

// 表单数据
const form = ref({
  title: '',
  description: '',
  type: '',
  priority: '',
  category_id: undefined as number | undefined,
  category_name: '',
  assignee_id: undefined as number | undefined,
  assignee_name: '',
  tags: '',
})

// 是否为编辑模式
const isEdit = computed(() => !!props.ticket?.id)

// 加载用户列表
const loadUserList = async () => {
  loadingUsers.value = true
  try {
    const res: any = await fetchUserList({ workspace: import.meta.env.VITE_APP_WORKSPACE || '' })
    if (res.code === 0) {
      userList.value = res.details?.data
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
  } finally {
    loadingUsers.value = false
  }
}

// 处理人选择变化
const handleAssigneeChange = (value: string) => {
  const selectedUser = userList.value.find((user) => user.name === value)
  if (selectedUser) {
    form.value.assignee_id = selectedUser.id
    form.value.assignee_name = selectedUser.name
  } else {
    form.value.assignee_id = undefined
  }
}

// 监听对话框显示状态
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      if (props.ticket && isEdit.value) {
        // 编辑模式：填充表单
        form.value = {
          title: props.ticket.title || '',
          description: props.ticket.description || '',
          type: props.ticket.type || '',
          priority: props.ticket.priority || '',
          category_id: props.ticket.category_id,
          category_name: props.ticket.category_name || '',
          assignee_id: props.ticket.assignee_id,
          assignee_name: props.ticket.assignee_name || '',
          tags: '',
        }
      } else {
        // 新建模式：重置表单
        form.value = {
          title: '',
          description: '',
          type: '',
          priority: '',
          category_id: undefined,
          category_name: '',
          assignee_id: undefined,
          assignee_name: '',
          tags: '',
        }
      }
    }
  }
)

// 确认提交
const handleOk = async () => {
  const valid = await formRef.value?.validate()
  console.log('valid', valid)
  if (valid) return

  console.log('form', form)
  submitting.value = true
  try {
    const data = {
      title: form.value.title,
      description: form.value.description || '',
      type: form.value.type,
      priority: form.value.priority,
      category_id: form.value.category_id,
      category_name: form.value.category_name || '',
      assignee_id: form.value.assignee_id,
      assignee_name: form.value.assignee_name || '',
      tags: form.value.tags || '',
      // metadata 和 attachments 传空对象
      metadata: '{}',
      attachments: '{}',
    }

    let res
    if (isEdit.value && props.ticket?.id) {
      // 编辑工单
      res = await updateFeedbackTicket(props.ticket.id, data)
    } else {
      // 新建工单
      res = await createFeedbackTicket(data)
    }

    if (res.code === 0) {
      Message.success(isEdit.value ? '编辑成功' : '创建成功')
      emit('success')
      emit('update:visible', false)
    } else {
      Message.error(res.message || (isEdit.value ? '编辑失败' : '创建失败'))
    }
  } catch (error) {
    Message.error(isEdit.value ? '编辑失败' : '创建失败')
    console.error(error)
  } finally {
    submitting.value = false
  }
}

// 取消
const handleCancel = () => {
  emit('update:visible', false)
}

// 处理对话框可见性变化
const handleVisibleChange = (visible: boolean) => {
  emit('update:visible', visible)
}

// 组件挂载时加载用户列表
onMounted(() => {
  loadUserList()
})
</script>

<script lang="ts">
import { computed } from 'vue'

export default {
  name: 'TicketFormDialog',
}
</script>

<style scoped lang="less">
// 样式可以根据需要添加
</style>
