<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="content" :rules="[{ required: true, message: '请输入解决方案' }]">
        <a-textarea
          v-model="form.content"
          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 } from 'vue'
import { Message } from '@arco-design/web-vue'
import { resolveFeedbackTicket } from '@/api/ops/feedbackTicket'

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 form = ref({
  content: '',
})

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

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

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

  if (!form.value.content.trim()) {
    Message.warning('请输入解决方案')
    return
  }

  try {
    const res = await resolveFeedbackTicket(props.ticket.id, {
      content: form.value.content,
    })
    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: 'ResolveDialog',
}
</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>
