<template>
  <a-modal :visible="visible" title="转交工单" width="600px" @ok="handleOk" @cancel="handleCancel" @update:visible="handleVisibleChange">
    <div class="ticket-info">
      <div class="info-item">
        <span class="label">工单编号：</span>
        <span class="value">{{ ticket?.ticket_no }}</span>
      </div>
      <div class="info-item">
        <span class="label">工单标题：</span>
        <span class="value">{{ ticket?.title }}</span>
      </div>
    </div>

    <a-divider />

    <a-form :model="form" layout="vertical">
      <a-form-item label="转交人员" field="assignee_name" :rules="[{ required: true, message: '请选择转交人员' }]">
        <a-select
          v-model="form.assignee_name"
          placeholder="请输入或选择转交人员"
          :filter-option="true"
          show-search
          allow-clear
          :loading="loading"
          @change="handleUserChange"
        >
          <a-option v-for="user in userList" :key="user.id" :value="user.name">{{ user.name }} ({{ user.phone }})</a-option>
        </a-select>
      </a-form-item>
      <a-form-item label="转交原因" field="reason">
        <a-textarea
          v-model="form.reason"
          placeholder="请输入转交原因"
          :auto-size="{ minRows: 3, maxRows: 5 }"
          :max-length="500"
          show-word-limit
        />
      </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 { transferFeedbackTicket } from '@/api/ops/feedbackTicket'
import { fetchUserList, type UserItem } from '@/api/ops/rbac2'

interface Ticket {
  id: number
  ticket_no: string
  title: 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 userList = ref<UserItem[]>([])
const loading = ref(false)

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

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

// 表单数据
const form = ref({
  assignee_id: undefined as number | undefined,
  assignee_name: '',
  reason: '',
})

// 处理用户选择变化
const handleUserChange = (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
  }
}

// 监听对话框显示状态
watch(
  () => props.visible,
  (newVal) => {
    if (newVal && props.ticket) {
      console.log('TransferDialog ticket:', props.ticket)
    }
    if (!newVal) {
      // 关闭时重置表单
      form.value = {
        assignee_id: undefined,
        assignee_name: '',
        reason: '',
      }
    }
  }
)

// 监听 ticket 变化
watch(
  () => props.ticket,
  (newVal) => {
    console.log('Ticket changed:', newVal)
  }
)

// 确认转交
const handleOk = async () => {
  if (!props.ticket) {
    Message.error('工单信息不存在')
    return
  }

  if (!form.value.assignee_id) {
    Message.warning('请输入新处理人ID')
    return
  }

  if (!form.value.assignee_name.trim()) {
    Message.warning('请输入新处理人名称')
    return
  }

  try {
    const res = await transferFeedbackTicket(props.ticket.id, {
      assignee_id: form.value.assignee_id,
      assignee_name: form.value.assignee_name,
      reason: form.value.reason,
    })
    if (res.code === 0) {
      Message.success('转交成功')
      emit('success')
    } else {
      Message.error(res.message || '转交失败')
    }
  } catch (error) {
    Message.error('转交失败')
    console.error(error)
  }
}

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

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

<script lang="ts">
export default {
  name: 'TransferDialog',
}
</script>

<style scoped lang="less">
.ticket-info {
  padding: 12px 0;

  .info-item {
    display: flex;
    margin-bottom: 8px;
    font-size: 14px;

    .label {
      font-weight: 500;
      color: var(--color-text-2);
      min-width: 80px;
    }

    .value {
      color: var(--color-text-1);
      font-weight: 400;
      flex: 1;
    }
  }

  .info-item:last-child {
    margin-bottom: 0;
  }
}
</style>
