<template>
    <div class="store-page">
        <Breadcrumb />
        <a-card title="工单详情" :loading="loading">
            <a-descriptions :column="{ xs: 1, sm: 2 }" bordered size="medium" class="order-info-desc">
                <a-descriptions-item label="工单标题">{{ data.title || '-' }}</a-descriptions-item>
                <a-descriptions-item label="工单ID">{{ data.id || '-' }}</a-descriptions-item>
                <a-descriptions-item label="发起人">
                    {{ data.userInfo?.[data.create_user]?.username || '-' }}
                </a-descriptions-item>
                <a-descriptions-item label="发起人UUID">{{ data.create_user || '-' }}</a-descriptions-item>
                <a-descriptions-item label="通知邮箱">{{ data.email || '-' }}</a-descriptions-item>
                <a-descriptions-item label="当前状态">{{ getState(data.state) }}</a-descriptions-item>
                <a-descriptions-item label="创建时间">{{ data.create_time ? stramptoTime(data.create_time) : '-' }}</a-descriptions-item>
                <a-descriptions-item label="最后更新时间">{{ data.update_time ? stramptoTime(data.update_time) : '-' }}</a-descriptions-item>
            </a-descriptions>
            <div class="buttonGroup">
                <a-button type="primary" size="large" :loading="buttonLoading" @click="CloseOrder()"
                    :disabled="data.state === 2">{{ data.state === 2 ? '已关闭' :
                        '关闭工单' }}</a-button>
            </div>
        </a-card>

        <a-card title="沟通记录" style="margin-top: 15px; padding-bottom: 20px;">
            <div class="message" v-for="(msg, index) in data.msg">
                <a-divider v-if="index !== 0" />
                <div class="head">
                    <div class="head__avatar-wrap">
                        <a-avatar :size="36">
                            <IconUser v-if="!data.userInfo[msg.uuid]?.avatar" />
                            <img alt="" :src="data.userInfo[msg.uuid]?.avatar" v-else />
                        </a-avatar>
                    </div>

                    <div class="right">
                        <div class="username">
                            {{ data.userInfo[msg.uuid]?.username }}
                            <a-tag color="gray" v-if="msg.type === 'system'">
                                <template #icon>
                                    <icon-desktop />
                                </template>
                                系统回复
                            </a-tag>
                            <a-tag color="orangered" v-else-if="msg.type === 'user'">
                                <template #icon>
                                    <icon-user />
                                </template>
                                用户回复
                            </a-tag>
                            <a-tag color="blue" v-else-if="msg.type === 'server'">
                                <template #icon>
                                    <icon-customer-service />
                                </template>
                                客服回复
                            </a-tag>
                            <a-tag color="purple" v-else-if="msg.type === 'ai'">
                                <template #icon>
                                    <icon-robot />
                                </template>
                                AI回复
                            </a-tag>
                        </div>
                        <div class="time">
                            {{ stramptoTime(msg.time) }}
                        </div>
                    </div>
                </div>
                <div class="content" :style="{ whiteSpace: 'pre-wrap' }">
                    {{ msg.content }}
                </div>
                <div class="filebox">
                    <a-upload :default-file-list="msg.files" :show-upload-button="false" :show-remove-button="false">
                        <template #success-icon>
                        </template>
                    </a-upload>
                </div>
            </div>
        </a-card>

        <a-card title="回复工单" style="margin-top: 15px;" v-if="data.state !== 2">
            <a-form :model="form" :rules="rules" layout="vertical" class="reply-form"
                @submit-success="handleSubmit">
                <a-form-item field="content" label="内容">
                    <a-textarea v-model="form.content" placeholder="请详细说明您遇到的问题，详细的阐述有助于我们快速为您解决问题..." :max-length="200"
                        :auto-size="{
                            minRows: 6,
                            maxRows: 20
                        }" 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 html-type="submit" :loading="formLoading">提交</a-button>
                </a-form-item>
            </a-form>
        </a-card>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { adminOrderDetail, closeOrder, adminReplyOrder } from '@/api/workOrder'
import { Notification } from '@arco-design/web-vue'
import { useRoute } from 'vue-router'

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 handleFileChange = (fileList) => {
    fileList.forEach(f => {
        if (f.status === 'done' && f.response?.downurl) {
            f.url = f.response?.viewurl ?? f.response.downurl
        }
    })

    form.files = fileList // 更新到表单数据中
}

function getState(state) {
    switch (state) {
        case 0:
            return '待处理'
        case 1:
            return '已回复'
        case 2:
            return '已关闭'
        case 3:
            return 'AI回复'
    }
    return '未知'
}

const handleSubmit = async () => {
    try {
        formLoading.value = true
        const data = {
            id: route.params.id,
            ...form
        }
        const res = await adminReplyOrder(data)
        if (!res || res.code !== 0)
            return Notification.error({
                title: '回复工单失败！',
                content: res?.msg ?? '请稍后再试'
            })
        Notification.success({
            title: '回复工单成功！'
        })
        form.content = ''
        form.files = []
        getOrderDetail()
    } catch (error) {
        Notification.error({
            title: '回复工单失败！',
            content: error.message || '请稍后再试'
        })
    } finally {
        formLoading.value = false
    }
}

const CloseOrder = 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: '关闭工单成功！'
        })
        getOrderDetail()
    } catch (error) {
        Notification.error({
            title: '关闭工单失败！',
            content: error.message || '请稍后再试'
        })
    } finally {
        buttonLoading.value = false
    }
}

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

        data.value = res.data
    } catch (error) {
        Notification.error({
            title: '获取路径数据失败！',
            content: error.message || '请稍后再试'
        })
    }
}

let timer = null

// 轮询
const startPolling = () => {
    if (!timer) {
        timer = setInterval(async () => {
            await getOrderDetail()
        }, 2000)
    }
}

// 停止轮询
const stopPolling = () => {
    if (timer) {
        clearInterval(timer)
        timer = null
    }
}

onMounted(async () => {
    loading.value = true
    await getOrderDetail()
    loading.value = false
    startPolling()
})

// 组件销毁时停止轮询
onUnmounted(() => {
    stopPolling()
})

const stramptoTime = (time) => {
    return new Date(time).toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' })
}
</script>

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

.message {
    display: flex;
    flex-direction: column;
    margin-bottom: 12px;

    .head {
        display: flex;
        align-items: flex-start;
        gap: 12px;

        .head__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;
            }

            :deep(img) {
                width: 36px;
                height: 36px;
                object-fit: cover;
            }
        }

        .right {
            flex: 1;
            min-width: 0;
            display: flex;
            flex-direction: column;
            gap: 4px;

            .username {
                font-size: 1rem;
                font-weight: 600;
                display: flex;
                flex-wrap: wrap;
                align-items: center;
                gap: 8px;
                color: @store-primary;
            }

            .time {
                font-size: 0.8rem;
                color: @store-text-muted;
            }
        }
    }

    .content {
        margin-top: 8px;
        margin-left: 48px;
        display: inline-block;
        width: fit-content;
        max-width: calc(100% - 48px);
        padding: 12px 14px;
        border-radius: @store-radius-sm;
        background: @store-bg;
        line-height: 1.65;
        word-break: break-word;
        color: @store-text-muted;
    }

    .filebox {
        margin-top: 8px;
        margin-left: 48px;
        max-width: calc(100% - 48px);
    }
}

.order-info-desc {
    :deep(.arco-descriptions-item-label) {
        white-space: nowrap;
    }

    :deep(.arco-descriptions-item-value) {
        word-break: break-all;
    }
}

.buttonGroup {
    margin-top: 16px;
}

.reply-form {
    max-width: 640px;
    width: 100%;
}
</style>