<template id="asdfasdf">
    <!-- <div class="h-full overflow-auto p-4 rounded-lg bg-white dark:bg-neutral-800"> -->
    <el-timeline>
        <el-timeline-item
            type="primary"
            placement="top"
            v-for="(item, index) in history"
            :key="index"
            :timestamp="formatDatetime(item.date, item.time)"
        >
            <ElCard>
                <ElButton :icon="InfoCircle" size="small" type="info" plain @click="onDetail(item)"></ElButton>&nbsp;
                <span class="whitespace-pre-wrap" v-html="item.plot"></span>
                <template v-if="index === history.length - 1 && item.options && item.options.length">
                    <br /><br />
                    <el-radio-group v-model="choice" class="ml-4">
                        <el-radio
                            v-for="(c, i) in item.options"
                            :key="i"
                            :label="i"
                            class="w-full !h-auto !whitespace-normal mb-4"
                        >
                            {{ c.content }}<br />
                            <span>
                                {{
                                    c.modifyHp
                                        .map((i) => `${i.name}${i.changeValue > 0 ? '+' : ''}${i.changeValue}`)
                                        .join(', ')
                                }}
                            </span>
                        </el-radio>
                    </el-radio-group>
                </template>
                <template v-else-if="item.options && item.options.length">
                    <br /><br />
                    <el-radio-group :model-value="item.choiceIndex" disabled class="ml-4">
                        <el-radio
                            v-for="(c, i) in item.options"
                            :key="i"
                            :label="i"
                            class="w-full !h-auto !whitespace-normal mb-4"
                        >
                            {{ c.content }}<br />
                            <span>
                                {{
                                    c.modifyHp
                                        .map((i) => `${i.name}${i.changeValue > 0 ? '+' : ''}${i.changeValue}`)
                                        .join(', ')
                                }}
                            </span>
                        </el-radio>
                    </el-radio-group>
                </template>
                <template v-if="index === history.length - 1">
                    <br />
                </template>
            </ElCard>
        </el-timeline-item>
    </el-timeline>
    <div class="text-center">
        <ElButtonGroup v-if="game.status === 'initialized'">
            <ElButton :loading="loading" @click="continueGame(false)">继续</ElButton>
            <ElButton :loading="loading" @click="onAddCharactor(false)">加入角色继续</ElButton>
            <ElButton :loading="loading" @click="continueGame(true)">生成选择</ElButton>
            <ElButton :loading="loading" @click="onAddCharactor(true)">加入角色生成选择</ElButton>
            <ElButton :loading="loading" @click="revert">回退</ElButton>
        </ElButtonGroup>
        <ElButton v-if="game.status === 'finished'" :loading="loading" @click="revert">回退</ElButton>
    </div>
    <ElDialog title="详情" v-model="showDetailDialog" width="1000px">
        <ElCollapse :model-value="['1', '2']">
            <ElCollapseItem title="角色信息" name="1">
                <ElTable :data="detail.charactors" size="small">
                    <ElTableColumn prop="avatar" label="头像" width="50">
                        <template #default="{ row }">
                            <ElImage
                                :src="row.avatar"
                                fit="cover"
                                :preview-src-list="[row.avatar]"
                                style="width: 30px; height: 30px"
                            ></ElImage>
                        </template>
                    </ElTableColumn>
                    <ElTableColumn prop="name" label="角色名称" width="80"></ElTableColumn>
                    <ElTableColumn prop="gender" label="性别" width="45" align="center"></ElTableColumn>
                    <ElTableColumn prop="age" label="年龄" width="45" align="center"></ElTableColumn>
                    <ElTableColumn prop="occupation" label="职业" width="80" show-overflow-tooltip></ElTableColumn>
                    <ElTableColumn prop="personality" label="性格" show-overflow-tooltip></ElTableColumn>
                    <ElTableColumn prop="background" label="背景" show-overflow-tooltip></ElTableColumn>
                    <ElTableColumn prop="hp" label="生命值" width="55" align="center"></ElTableColumn>
                    <ElTableColumn prop="status" label="状态" width="45" align="center">
                        <template #default="{ row }">
                            <span>{{ row.dead ? '死亡' : '存活' }}</span>
                        </template>
                    </ElTableColumn>
                    <ElTableColumn prop="joinAt" label="加入时间" :formatter="timeFormatter" width="80"></ElTableColumn>
                    <ElTableColumn prop="deadAt" label="死亡时间" :formatter="timeFormatter" width="80"></ElTableColumn>
                </ElTable>
            </ElCollapseItem>
            <ElCollapseItem title="剧情概要" name="2">
                {{ detail.summary }}
            </ElCollapseItem>
        </ElCollapse>
    </ElDialog>
    <ElDialog title="加入角色" v-model="showAddCharactorDialog" width="500px">
        <ElForm :model="charactorModel" label-position="top" inline :rules="charactorRules" ref="charactorForm">
            <ElFormItem prop="avatar" label="头像">
                <SingleUpload v-model="charactorModel.avatar" />
            </ElFormItem>
            <ElFormItem prop="name" label="角色名称">
                <ElInput v-model="charactorModel.name" />
            </ElFormItem>
            <ElFormItem prop="gender" label="性别">
                <ElInput v-model="charactorModel.gender" />
            </ElFormItem>
            <ElFormItem prop="age" label="年龄">
                <ElInput v-model="charactorModel.age" />
            </ElFormItem>
            <ElFormItem prop="occupation" label="职业">
                <ElInput v-model="charactorModel.occupation" />
            </ElFormItem>
            <ElFormItem prop="personality" label="性格">
                <ElInput v-model="charactorModel.personality" />
            </ElFormItem>
            <div class="w-full"></div>
            <ElFormItem class="w-full" prop="background" label="背景">
                <ElInput v-model="charactorModel.background" type="textarea" />
            </ElFormItem>
        </ElForm>
        <template #footer>
            <ElButton @click="showAddCharactorDialog = false">取消</ElButton>
            <ElButton type="primary" @click="addCharactor">确定</ElButton>
        </template>
    </ElDialog>
    <!-- </div> -->
</template>
<script setup>
import { http } from '@/plugins/http'
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { useRoute } from 'vue-router'
import { format } from 'date-fns'
import { zhCN } from 'date-fns/locale'
import { ElMessage, ElMessageBox } from 'element-plus'
import { InfoCircle } from '@vicons/tabler'
import { useTimeFormatter } from '@/utils/formatter'
import SingleUpload from '@/components/SingleUpload.vue'
import { io } from 'socket.io-client'

const route = useRoute()
const roomId = route.params.roomId
const gameId = route.params.gameId
const game = ref({})
const history = ref([])
const choice = ref(-1)

const needChoice = computed(() => {
    return (history.value[history.value.length - 1].options || []).length > 0
})
async function getData(params) {
    http.get(`/game/${gameId}`, { params }).then((res) => {
        game.value = res
    })
    http.get(`/game/${gameId}/history`, { params }).then((res) => {
        res.forEach((i) => {
            if (i.options && i.choice) {
                i.choiceIndex = i.options.findIndex((o) => o.content === i.choice.content)
            }
        })
        const last = res[res.length - 1]
        if (last && last.options && last.options.length && last.choice) {
            if (
                history.value.length === 0 ||
                (res[res.length - 1] &&
                    history.value[history.value.length - 1] &&
                    res[res.length - 1].id !== history.value[history.value.length - 1].id)
            ) {
                choice.value = last.options.findIndex((i) => i.content === last.choice.content)
            }
        }

        history.value = res
        setTimeout(() => {
            document
                .querySelector('#main-container')
                .scrollTo({ top: document.querySelector('#main-container').scrollHeight, behavior: 'smooth' })
        }, 500)
    })
}
getData()
const socket = ref(null)
onMounted(() => {
    socket.value = io(import.meta.env.VITE_WS_URL)
    socket.value.on('connect', () => {
        console.log('[websocket] connected')
    })
    socket.value.on('disconnect', () => {
        console.log('[websocket] disconnected')
    })
    socket.value.on(`${gameId}`, (...args) => {
        console.log('[websocket] received message', args[0])
        const data = args[0]
        switch (data.type) {
            case 'timeChange':
                if (history.value[history.value.length - 1].id !== -1) {
                    history.value.push({
                        id: -1
                    })
                }
                history.value[history.value.length - 1] = {
                    ...history.value[history.value.length - 1],
                    ...data.data
                }
                break
            case 'plot':
                if (history.value[history.value.length - 1].id !== -1) {
                    history.value.push({
                        id: -1
                    })
                }
                history.value[history.value.length - 1] = {
                    ...history.value[history.value.length - 1],
                    plot: data.data
                }
                // // 创建一个新的SpeechSynthesisUtterance对象
                // var utterance = new SpeechSynthesisUtterance()
                // // 语速
                // utterance.rate = 1.5;
                // // 设置要合成的文本
                // utterance.text = data.data

                // // 获取语音合成对象
                // var synth = window.speechSynthesis

                // // 添加要合成的文本到队列中
                // synth.speak(utterance)
                break
            case 'options':
                if (history.value[history.value.length - 1].id !== -1) {
                    history.value.push({
                        id: -1
                    })
                }
                history.value[history.value.length - 1] = {
                    ...history.value[history.value.length - 1],
                    options: data.data
                }
                break
            case 'state':
                getData()
                break
        }
        if (data.type !== 'votes') {
            setTimeout(() => {
                document
                    .querySelector('#main-container')
                    .scrollTo({ top: document.querySelector('#main-container').scrollHeight, behavior: 'smooth' })
            }, 500)
        }
    })
    socket.value.connect()
})
onBeforeUnmount(() => {
    socket.value?.disconnect()
})
function formatDatetime(date, time) {
    try {
        return (
            format(new Date(date), 'MMMdo', { locale: zhCN }) +
            {
                morning: '上午',
                afternoon: '下午',
                evening: '晚上'
            }[time]
        )
    } catch (error) {
        return ''
    }
}
const loading = ref(false)

async function continueGame(genChoice = false, newCharactor = null) {
    if (needChoice.value && choice.value < 0) {
        ElMessage.info('请选择一个选项')
        return
    }
    loading.value = true
    try {
        await http.post(`/game/${gameId}/continue`, {
            genChoice: genChoice,
            choice: history.value[history.value.length - 1].options[choice.value],
            newCharactor: newCharactor
        })
        loading.value = false
        getData()
    } catch (error) {
        ElMessage.error(error.message)
        loading.value = false
    }
}

async function revert() {
    loading.value = true
    try {
        await http.post(`/game/${gameId}/revert`)
    } catch (error) {
        ElMessage.error(error.message)
    }
    loading.value = false
    getData()
}

const showAddCharactorDialog = ref(false)
const charactorRules = {
    avatar: [{ required: true, message: '请上传头像', trigger: 'blur' }],
    name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
    gender: [{ required: true, message: '请输入性别', trigger: 'blur' }],
    age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
    occupation: [{ required: true, message: '请输入职业', trigger: 'blur' }],
    personality: [{ required: true, message: '请输入性格', trigger: 'blur' }],
    background: [{ required: true, message: '请输入背景', trigger: 'blur' }]
}
const charactorForm = ref(null)
const charactorModel = ref({})
const genChoice = ref(false)

async function onAddCharactor(g = false) {
    charactorModel.value = {}
    charactorForm.value?.clearValidate()
    showAddCharactorDialog.value = true
    genChoice.value = g
}

async function addCharactor() {
    await charactorForm.value.validate()
    showAddCharactorDialog.value = false
    continueGame(genChoice.value, charactorModel.value)
}

const showDetailDialog = ref(false)
const detail = ref({})
function onDetail(row) {
    detail.value = { ...row }
    showDetailDialog.value = true
}
const timeFormatter = useTimeFormatter('MM/dd')
</script>
<style lang="less" scoped></style>
