<template>
  <div class="store-page service-page">
    <div class="service-page__inner service-page__inner--wide">
      <Breadcrumb />

      <header class="page-header">
        <div>
          <h1 class="store-section-title">提交工单</h1>
          <p class="store-section-desc">选择常见问题模板，或自行填写后提交，客服将尽快回复</p>
        </div>
        <a-button type="outline" @click="$router.push('/service/orderList')">
          <template #icon><icon-list /></template>
          我的工单
        </a-button>
      </header>

      <a-card :bordered="false" class="form-card">
        <WorkOrderTemplatePicker
          v-model="selectedTemplateId"
          @select="applyTemplate"
        />

        <a-form :model="form" :rules="rules" layout="vertical" @submit-success="handleSubmit">
          <a-form-item field="title" label="工单标题">
            <a-input v-model="form.title" :max-length="25" allow-clear show-word-limit placeholder="简要概括您的问题" />
          </a-form-item>

          <a-form-item field="content" label="问题描述">
            <a-textarea
              v-model="form.content"
              placeholder="请详细说明您遇到的问题，信息越完整越便于我们快速处理"
              :max-length="500"
              :auto-size="{ minRows: 8, maxRows: 16 }"
              allow-clear
              show-word-limit
            />
          </a-form-item>

          <a-form-item field="files" label="上传附件（选填）">
            <a-upload action="/cloud/api.php" :file-list="form.files" @change="handleFileChange" />
          </a-form-item>

          <a-form-item field="email" label="通知邮箱">
            <EmailAutoComplete
              v-model="form.email"
              :max-length="30"
              allow-clear
              placeholder="客服回复后将通过邮件通知您"
            />
          </a-form-item>

          <a-alert v-if="!hasPermission('action.service.createOrder')" type="warning" class="perm-alert">
            当前账号暂无发起工单权限
          </a-alert>

          <a-form-item>
            <a-space>
              <a-button
                type="primary"
                html-type="submit"
                size="large"
                class="submit-btn"
                :loading="loading"
                :disabled="!hasPermission('action.service.createOrder')"
              >
                提交工单
              </a-button>
              <a-button size="large" @click="clearForm">清空内容</a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </a-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { createOrder } from '@/api/workOrder'
import { useRouter } from 'vue-router'
import { Notification } from '@arco-design/web-vue'
import { hasPermission } from '@/utils/permission'
import WorkOrderTemplatePicker from '@/components/service/WorkOrderTemplatePicker.vue'

const loading = ref(false)
const router = useRouter()
const selectedTemplateId = ref('')

const rules = {
  title: [{ required: true, message: '请输入工单标题' }],
  content: [{ required: true, message: '请详细说明您遇到的问题' }],
  email: [{ type: 'email', required: true, message: '请填写正确的通知邮箱' }]
}

const form = reactive({
  title: '',
  content: '',
  email: '',
  files: []
})

const applyTemplate = (item) => {
  form.title = item.title
  form.content = item.content
}

const clearForm = () => {
  selectedTemplateId.value = ''
  form.title = ''
  form.content = ''
  form.files = []
}

const handleSubmit = async () => {
  if (!hasPermission('action.service.createOrder')) {
    Notification.warning({ title: '无权限', content: '当前账号暂无发起工单权限' })
    return
  }
  try {
    loading.value = true
    const res = await createOrder(form)
    if (!res || res.code !== 0) {
      return Notification.error({
        title: '提交失败',
        content: res?.msg ?? '请稍后再试'
      })
    }
    Notification.success({ title: '提交成功', content: '我们已收到您的工单' })
    router.push(`/service/orderDetail/${res.data}`)
  } catch (error) {
    Notification.error({
      title: '提交失败',
      content: error.message || '请稍后再试'
    })
  } finally {
    loading.value = false
  }
}

const handleFileChange = (fileList) => {
  fileList.forEach((f) => {
    if (f.status === 'done' && f.response?.downurl) {
      f.url = f.response?.viewurl ?? f.response.downurl
    }
  })
  form.files = fileList
}
</script>

<style lang="less" scoped>
@import '@/styles/store-theme.less';

.page-header {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-end;
  justify-content: space-between;
  gap: 16px;
  margin-bottom: 20px;
}

.form-card {
  border-radius: @store-radius;
  border: 1px solid @store-card-border;
  box-shadow: @store-shadow;
  padding: 8px 4px 4px;
}

.perm-alert {
  margin-bottom: 16px;
  border-radius: @store-radius-sm;
}

.submit-btn {
  border-radius: 999px;
  background: @store-primary !important;
  border-color: @store-primary !important;
}
</style>
