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

      <a-skeleton animation :loading="loading" class="store-spin">
        <StoreDetailSkeleton variant="order" />
        <template #content>
          <template v-if="data.id">
          <a-card :bordered="false" class="info-card">
            <div class="info-card__head">
              <div>
                <h1 class="info-card__title">{{ data.title }}</h1>
                <p class="info-card__sub">工单 #{{ data.id }} · {{ formatTimeFull(data.create_time) }}</p>
              </div>
              <WorkOrderStateTag :state="data.state" />
            </div>
            <a-descriptions :column="{ xs: 1, sm: 2 }" size="medium" class="info-desc">
              <a-descriptions-item label="通知邮箱">{{ data.email }}</a-descriptions-item>
              <a-descriptions-item label="最后更新">{{ formatTimeFull(data.update_time) }}</a-descriptions-item>
            </a-descriptions>
            <div class="info-card__actions">
              <a-button
                type="primary"
                :loading="buttonLoading"
                :disabled="data.state === 2"
                class="submit-btn"
                @click="handleCloseOrder"
              >
                {{ data.state === 2 ? '已关闭' : '关闭工单' }}
              </a-button>
              <a-button @click="$router.push('/service/orderList')">返回列表</a-button>
            </div>
          </a-card>

          <a-card :bordered="false" class="chat-card">
            <template #title>
              <span class="chat-card__title">沟通记录</span>
            </template>
            <div v-if="!data.msg?.length" class="chat-empty">暂无消息</div>
            <div v-else class="chat-list">
              <div
                v-for="(msg, index) in data.msg"
                :key="index"
                class="chat-item"
                :class="messageClass(msg.type)"
              >
                <div class="chat-item__avatar-wrap">
                  <a-avatar :size="36">
                    <icon-user v-if="!data.userInfo?.[msg.uuid]?.avatar" />
                    <img v-else :src="data.userInfo[msg.uuid].avatar" alt="" />
                  </a-avatar>
                </div>
                <div class="chat-item__body">
                  <div class="chat-item__meta">
                    <span class="chat-item__name">{{ data.userInfo?.[msg.uuid]?.username || '用户' }}</span>
                    <a-tag size="small" :color="tagColor(msg.type)">{{ tagLabel(msg.type) }}</a-tag>
                    <span class="chat-item__time">{{ formatTimeFull(msg.time) }}</span>
                  </div>
                  <div class="chat-item__content">{{ msg.content }}</div>
                  <div v-if="msg.files?.length" class="chat-item__files">
                    <a-upload
                      :default-file-list="msg.files"
                      :show-upload-button="false"
                      :show-remove-button="false"
                    />
                  </div>
                </div>
              </div>
            </div>
          </a-card>

          <a-card
            v-if="data.state !== 2 && hasPermission('action.service.createOrder')"
            :bordered="false"
            class="reply-card"
          >
            <template #title>
              <span class="chat-card__title">继续回复</span>
            </template>
            <a-form :model="form" :rules="rules" layout="vertical" @submit-success="handleSubmit">
              <a-form-item field="content" label="回复内容">
                <a-textarea
                  v-model="form.content"
                  placeholder="补充说明或回复客服"
                  :max-length="500"
                  :auto-size="{ minRows: 4, maxRows: 12 }"
                  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>
                <a-button type="primary" html-type="submit" :loading="formLoading" class="submit-btn">
                  发送回复
                </a-button>
              </a-form-item>
            </a-form>
          </a-card>
          </template>
        </template>
      </a-skeleton>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { orderDetail, closeOrder, createOrder } from '@/api/workOrder'
import { Notification } from '@arco-design/web-vue'
import { useRoute } from 'vue-router'
import { hasPermission } from '@/utils/permission'
import { formatStoreTimeFull } from '@/utils/storeFormat'
import WorkOrderStateTag from '@/components/service/WorkOrderStateTag.vue'
import StoreDetailSkeleton from '@/components/skeleton/StoreDetailSkeleton.vue'

const route = useRoute()
const loading = ref(false)
const formLoading = ref(false)
const buttonLoading = ref(false)
const data = ref({})

const form = reactive({ content: '', files: [] })
const rules = {
  content: [{ required: true, message: '请填写回复内容' }]
}

const formatTimeFull = (time) => formatStoreTimeFull(time)

const tagLabel = (type) => {
  const map = { system: '系统', user: '我', server: '客服', ai: 'AI' }
  return map[type] ?? type
}

const tagColor = (type) => {
  const map = { system: 'gray', user: 'orangered', server: 'arcoblue', ai: 'purple' }
  return map[type] ?? 'gray'
}

const messageClass = (type) => {
  if (type === 'user') return 'chat-item--mine'
  if (type === 'server' || type === 'ai') return 'chat-item--staff'
  return 'chat-item--system'
}

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

const handleSubmit = async () => {
  if (!hasPermission('action.service.createOrder')) {
    Notification.warning({ title: '无权限', content: '当前账号暂无回复权限' })
    return
  }
  try {
    formLoading.value = true
    const res = await createOrder({ id: route.params.id, ...form })
    if (!res || res.code !== 0) {
      return Notification.error({ title: '发送失败', content: res?.msg ?? '请稍后再试' })
    }
    Notification.success({ title: '发送成功' })
    form.content = ''
    form.files = []
    await fetchDetail()
  } catch (error) {
    Notification.error({ title: '发送失败', content: error.message || '请稍后再试' })
  } finally {
    formLoading.value = false
  }
}

const handleCloseOrder = async () => {
  try {
    buttonLoading.value = true
    const res = await closeOrder({ id: route.params.id })
    if (!res || res.code !== 0) {
      return Notification.error({ title: '关闭失败', content: res?.msg ?? '请稍后再试' })
    }
    Notification.success({ title: '工单已关闭' })
    await fetchDetail()
  } catch (error) {
    Notification.error({ title: '关闭失败', content: error.message || '请稍后再试' })
  } finally {
    buttonLoading.value = false
  }
}

const fetchDetail = async () => {
  const res = await orderDetail({ id: route.params.id })
  if (!res || res.code !== 0) {
    Notification.error({ title: '获取详情失败', content: res?.msg ?? '请稍后再试' })
    return
  }
  data.value = res.data ?? {}
}

let timer = null
const startPolling = () => {
  if (!timer) {
    timer = setInterval(() => {
      if (data.value?.state !== 2) fetchDetail()
    }, 3000)
  }
}
const stopPolling = () => {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
}

onMounted(async () => {
  loading.value = true
  await fetchDetail()
  loading.value = false
  if (data.value?.state !== 2) startPolling()
})

onUnmounted(stopPolling)
</script>

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

.info-card,
.chat-card,
.reply-card {
  border-radius: @store-radius;
  border: 1px solid @store-card-border;
  box-shadow: @store-shadow;
  margin-bottom: 16px;
}

.info-card__head {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  justify-content: space-between;
  gap: 12px;
  margin-bottom: 16px;
}

.info-card__title {
  margin: 0 0 6px;
  font-size: 1.25rem;
  font-weight: 600;
  color: @store-primary;
}

.info-card__sub {
  margin: 0;
  font-size: 0.85rem;
  color: @store-text-muted;
}

.info-card__actions {
  margin-top: 16px;
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.chat-card__title {
  font-weight: 600;
  color: @store-primary;
}

.chat-empty {
  text-align: center;
  color: @store-text-muted;
  padding: 24px;
}

.chat-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.chat-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  width: 100%;

  &__avatar-wrap {
    flex: 0 0 36px;
    width: 36px;
    min-width: 36px;
    height: 36px;
    overflow: hidden;
    border-radius: 50%;

    :deep(.arco-avatar) {
      display: block;
      width: 36px;
      height: 36px;
      line-height: 36px;
    }

    :deep(.arco-avatar-image),
    :deep(img) {
      width: 36px;
      height: 36px;
      object-fit: cover;
    }
  }

  &__body {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    flex: 0 1 auto;
    max-width: calc(100% - 48px);
    min-width: 0;
  }

  &__meta {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 8px;
    margin-bottom: 6px;
    max-width: 100%;
  }

  &__name {
    font-weight: 600;
    color: @store-primary;
  }

  &__time {
    font-size: 0.8rem;
    color: @store-text-muted;
  }

  &__content {
    display: inline-block;
    width: fit-content;
    max-width: 100%;
    padding: 12px 14px;
    border-radius: @store-radius-sm;
    background: @store-bg;
    line-height: 1.65;
    white-space: pre-wrap;
    word-break: break-word;
    color: @store-text-muted;
  }

  &__files {
    margin-top: 8px;
    width: fit-content;
    max-width: 100%;
  }

  &--mine {
    flex-direction: row-reverse;

    .chat-item__body {
      align-items: flex-end;
    }

    .chat-item__meta {
      justify-content: flex-end;
    }

    .chat-item__content {
      background: fade(@store-accent, 12%);
      border: 1px solid fade(@store-accent, 25%);
      border-top-right-radius: 4px;
    }
  }

  &--staff .chat-item__content {
    background: #f0f6ff;
    border: 1px solid #d6e4ff;
    border-top-left-radius: 4px;
  }

  &--system .chat-item__content {
    background: var(--color-fill-2);
    border-top-left-radius: 4px;
  }
}

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