<template>
  <SimulatorLayout ref="layoutRef" :tabs="tabs" v-model:activeTab="activeTab" @save="handleSave" @export="handleExport">
    <template #preview>
      <ChatPreview ref="previewRef" :messages="messages" :settings="settings" />
    </template>

    <template #config>
      <div v-show="activeTab === 'appearance'">
        <div class="section-label">基本信息</div>
        <div class="status-row" style="display: flex; gap: 16px;">
          <div style="flex: 1;">
            <div class="setting-item">
              <label>聊天标题</label>
              <el-input v-model="settings.theirName" placeholder="输入聊天标题" />
            </div>
            <div class="setting-item">
              <label>未读消息</label>
              <el-input v-model="settings.unread" placeholder="50" />
            </div>
          </div>
          <div style="flex: 1;">
            <label style="font-size: 14px; color: #767676; margin-bottom: 8px; display: block;">头像昵称 (默认第一个是自己)</label>
            <div class="avatar-upload-row" style="display: flex; gap: 16px; margin-top: 14px;">
              <div class="avatar-upload-item">
                <input type="file" accept="image/*" @change="(e) => handleAvatarUpload(e, 'my')" class="hidden-file"
                  ref="myAvatarInput" />
                <div class="upload-area" @click="$refs.myAvatarInput.click()">
                  <img v-if="settings.myAvatarUrl" :src="settings.myAvatarUrl" class="avatar-preview" alt="" />
                  <span v-else class="upload-placeholder">+</span>
                </div>
                <span class="text">自己</span>
              </div>
              <div class="avatar-upload-item">
                <input type="file" accept="image/*" @change="(e) => handleAvatarUpload(e, 'their')" class="hidden-file"
                  ref="theirAvatarInput" />
                <div class="upload-area" @click="$refs.theirAvatarInput.click()">
                  <img v-if="settings.theirAvatarUrl" :src="settings.theirAvatarUrl" class="avatar-preview" alt="" />
                  <span v-else class="upload-placeholder">+</span>
                </div>
                <span class="text">对方</span>
              </div>
            </div>
          </div>
        </div>

        <div class="section-divider"></div>
        <div class="section-label">状态栏</div>
        <div class="status-row" style="display: flex; gap: 16px;">
          <div class="setting-item">
            <label>手机</label>
            <el-select v-model="settings.phoneModel" style="width:90px;">
              <el-option label="苹果ios" value="ios" />
            </el-select>
          </div>
          <div class="setting-item">
            <label>时间</label>
            <el-time-picker v-model="settings.statusTime" format="HH:mm" value-format="HH:mm" style="width:128px"
              :clearable="false" />
          </div>
          <div class="setting-item">
            <label>手机信号</label>
            <el-select v-model="settings.signal" style="width:90px">
              <el-option label="1格" value="1" /><el-option label="2格" value="2" /><el-option label="3格"
                value="3" /><el-option label="4格" value="4" />
            </el-select>
          </div>
          <div class="setting-item">
            <label>WiFi信号</label>
            <el-select v-model="settings.wifi" style="width:90px">
              <el-option label="1格" value="1" /><el-option label="2格" value="2" /><el-option label="3格" value="3" />
            </el-select>
          </div>
        </div>
        <div class="status-row" style="display: flex; gap: 16px; align-items: flex-end; margin-bottom: 24px;">
          <div class="setting-item" style="width: 90px;">
            <label>充电中</label>
            <el-select v-model="settings.isCharging" style="width:100%"><el-option label="是" :value="true" /><el-option
                label="否" :value="false" /></el-select>
          </div>
          <div class="setting-item" style="width: 450px;">
            <div style="display: flex; align-items: center; gap: 16px; height: 32px;">
              <el-slider v-model="settings.battery" :min="1" :max="100" :show-tooltip="false" style="flex: 1;" />
              <span style="font-size: 14px; color: #1A1A1A; white-space: nowrap;">电量{{ settings.battery }}%</span>
            </div>
          </div>
        </div>

        <div class="section-divider"></div>
        <div class="section-label">显示设置</div>
        <div class="status-row" style="display: flex; margin-top: 16px;">
          <div class="setting-item switch-item" style="gap: 8px;">
            <span style="font-size: 14px; color: #767676;white-space: nowrap;">听筒模式</span> <el-switch
              v-model="settings.earpiece" />
          </div>
          <div class="setting-item switch-item" style="gap: 8px;">
            <span style="font-size: 14px; color: #767676;white-space: nowrap;">免打扰</span> <el-switch
              v-model="settings.notDisturb" />
          </div>
          <div class="setting-item switch-item" style="gap: 8px;">
            <span style="font-size: 14px; color: #767676;white-space: nowrap;">显示麦克风</span> <el-switch
              v-model="settings.showMicIcon" @change="val => { if (val) settings.voiceMode = false }" />
          </div>
          <div class="setting-item switch-item" style="gap: 8px;">
            <span style="font-size: 14px; color: #767676;white-space: nowrap;">语音模式</span> <el-switch
              v-model="settings.voiceMode" @change="val => { if (val) settings.showMicIcon = false }" />
          </div>
          <div class="setting-item switch-item" style="gap: 8px;">
            <span style="font-size: 14px; color: #767676;white-space: nowrap;">深色模式</span> <el-switch
              v-model="settings.isDark" @change="val => settings.theme = val ? 'dark' : 'light'" />
          </div>
          <div class="setting-item switch-item" style="gap: 8px;">
            <span style="font-size: 14px; color: #767676;white-space: nowrap;">底部条</span> <el-switch
              v-model="settings.showBottomBar" />
          </div>
        </div>

        <div class="setting-item" style="margin-top: 24px; display: flex; align-items: center; gap: 16px;">
          <label style="margin: 0;">聊天背景</label>
          <div class="bg-upload-box">
            <input type="file" accept="image/*" @change="handleWallpaperUpload" class="hidden-file"
              ref="wallpaperInput" />
            <div class="upload-area" @click="$refs.wallpaperInput.click()"
              style="width: 60px; height: 60px; border: 1px dashed #ccc; display: flex; align-items: center; justify-content: center; cursor: pointer; border-radius: 4px; overflow: hidden;">
              <img v-if="settings.wallpaper" :src="settings.wallpaper" class="wallpaper-preview" alt=""
                style="width: 100%; height: 100%; object-fit: cover;" />
              <span v-else style="font-size: 24px; color: #ccc;">+</span>
            </div>
          </div>
          <el-button v-if="settings.wallpaper" size="small" type="danger" link
            @click="settings.wallpaper = ''">清除</el-button>
        </div>
      </div>

      <div v-show="activeTab === 'edit'" class="chat-config-layout" style="display: flex; gap: 32px; height: 100%;">
        <div class="msg-list-col" style="flex: 3;  display: flex; flex-direction: column;">
          <div class="section-label" style="flex-shrink: 0;margin-bottom: 8px;">消息设置</div>
          <div class="tip-text"
            style="font-size: 12px; color: #999; margin-bottom: 8px;margin-top: 8px; flex-shrink: 0;">长按可以快捷排序哟
          </div>

          <div class="msg-list-scroll-wrap"
            style="flex: 1; overflow-y: auto; padding-right: 4px; margin-bottom: 16px;height: 100%;">
            <div class="msg-list">
              <div v-for="(msg, idx) in messages" :key="msg.id" class="msg-item"
                :class="{ active: selectedIdx === idx }" @click="selectedIdx = idx">
                <span class="msg-type-tag" :class="'type-' + msg.type">{{ getTypeLabel(msg) }}</span>
                <span class="msg-brief" v-if="msg.type !== 'system'">{{ getMessageBrief(msg) }}</span>
                <span class="msg-brief" v-else v-html="getSystemHtml(msg)"></span>
                <span class="msg-actions">
                  <el-icon @click.stop="moveUp(idx)">
                    <Top />
                  </el-icon>
                  <el-icon @click.stop="moveDown(idx)">
                    <Bottom />
                  </el-icon>
                  <el-icon @click.stop="removeMessage(idx)" color="#f56c6c">
                    <Delete />
                  </el-icon>
                </span>
              </div>
            </div>
          </div>

          <div class="add-msg-box" style="flex-shrink: 0;margin-bottom: 12px;">
            <el-popover placement="top" :width="80" trigger="click" popper-class="custom-chat-popover">
              <template #reference>
                <el-button
                  style="width: 100%; height:30px; border-radius: 4px;font-size: 14px;color: #1A1A1A;">添加消息</el-button>
              </template>
              <div class="add-type-grid">
                <div class="add-type-item" @click="addMessage('text')"><span class="plus">+</span>对话</div>
                <div class="add-type-item" @click="addMessage('system')"><span class="plus">+</span>系统</div>
                <div class="add-type-item" @click="addMessage('redpacket')"><span class="plus">+</span>红包</div>
                <div class="add-type-item" @click="addMessage('time')"><span class="plus">+</span>时间</div>
                <div class="add-type-item" @click="addMessage('transfer')"><span class="plus">+</span>转账</div>
                <div class="add-type-item" @click="addMessage('call')"><span class="plus">+</span>通话</div>
                <div class="add-type-item" @click="addMessage('voice')"><span class="plus">+</span>语音</div>
              </div>
            </el-popover>
          </div>
        </div>

        <div class="msg-edit-col" style="flex: 2; padding-left: 32px; display: flex; flex-direction: column;"
          v-if="selectedMsg">
          <div class="section-label"
            style="display: flex; align-items: center; gap: 8px; flex-shrink: 0;margin-bottom: 16px;">
            编辑消息 <span class="msg-type-tag" :class="'type-' + selectedMsg.type">{{
              getTypeLabel(selectedMsg) }}</span>
          </div>

          <div class="edit-form" style="flex: 1; overflow-y: auto; padding-right: 4px; padding-bottom: 16px;">
            <!-- text -->
            <template v-if="selectedMsg.type === 'text'">
              <div class="setting-item">
                <label>发送方</label>
                <el-select v-model="selectedMsg.sender" style="width: 100%;">
                  <el-option label="我" value="me" />
                  <el-option label="对方" value="other" />
                </el-select>
              </div>
              <div class="setting-item">
                <label>消息内容</label>
                <div style="position: relative;">
                  <el-input v-model="selectedMsg.content" type="textarea" :rows="4" resize="none" />
                  <el-icon style="position: absolute; right: 8px; bottom: 8px; color: #c0c4cc; font-size: 16px;">
                    <EditPen />
                  </el-icon>
                </div>
              </div>
              <div class="setting-item">
                <label>消息状态</label>
                <el-select v-model="selectedMsg.status" style="width: 100%;">
                  <el-option label="发送成功" value="send" />
                  <el-option v-if="selectedMsg.sender === 'me'" label="发送失败" value="failed" />
                </el-select>
              </div>
            </template>

            <!-- redpacket -->
            <template v-if="selectedMsg.type === 'redpacket'">
              <div class="setting-item">
                <label>发送方</label>
                <el-select v-model="selectedMsg.sender" style="width: 100%;">
                  <el-option label="我" value="me" />
                  <el-option label="对方" value="other" />
                </el-select>
              </div>
              <div class="setting-item">
                <label>消息内容</label>
                <div style="position: relative;">
                  <el-input v-model="selectedMsg.title" type="textarea" :rows="4" placeholder="恭喜发财，大吉大利"
                    resize="none" />
                  <el-icon style="position: absolute; right: 8px; bottom: 8px; color: #c0c4cc; font-size: 16px;">
                    <EditPen />
                  </el-icon>
                </div>
              </div>
              <div class="setting-item">
                <label>红包状态</label>
                <el-select v-model="selectedMsg.status" style="width: 100%;" @change="onRedpacketStatusChange">
                  <el-option label="发送成功" value="send" />
                  <el-option label="被领取" value="received" />
                  <el-option label="已过期" value="expired" />
                </el-select>
              </div>
            </template>

            <!-- transfer -->
            <template v-if="selectedMsg.type === 'transfer'">
              <div class="setting-item">
                <label>发送方</label>
                <el-select v-model="selectedMsg.sender" style="width: 100%;">
                  <el-option label="我" value="me" />
                  <el-option label="对方" value="other" />
                </el-select>
              </div>
              <div class="setting-item">
                <label>金额</label>
                <el-input v-model.number="selectedMsg.amount" type="number" style="width: 100%;">
                  <template #suffix>
                    <el-icon>
                      <EditPen />
                    </el-icon>
                  </template>
                </el-input>
              </div>
              <div class="setting-item">
                <label>消息内容</label>
                <div style="position: relative;">
                  <el-input v-model="selectedMsg.remark" type="textarea" :rows="3" placeholder="你发起了一笔转账"
                    resize="none" />
                  <el-icon style="position: absolute; right: 8px; bottom: 8px; color: #c0c4cc; font-size: 16px;">
                    <EditPen />
                  </el-icon>
                </div>
              </div>
              <div class="setting-item">
                <label>转账状态</label>
                <el-select v-model="selectedMsg.status" style="width: 100%;" @change="onTransferStatusChange">
                  <el-option label="发送成功" value="send" />
                  <!-- <el-option v-if="selectedMsg.sender === 'me'" label="发送失败" value="failed" /> -->
                  <el-option label="过期" value="expired" />
                  <el-option label="收款" value="received" />
                  <el-option label="退还" value="returned" />
                </el-select>
              </div>
            </template>

            <!-- system -->
            <template v-if="selectedMsg.type === 'system'">
              <div class="setting-item">
                <label>发送方</label>
                <el-select v-model="selectedMsg.sender" style="width: 100%;">
                  <el-option label="系统" value="system" />
                </el-select>
              </div>
              <div class="setting-item">
                <label style="display: flex; align-items: center; justify-content: space-between;">
                  <span>消息内容</span>
                  <span style="font-size: 11px; color: #999; font-weight: normal;">（拖动选中文字后可修改颜色）</span>
                </label>
                <div style="position: relative;">
                  <div ref="systemEditorRef" class="rich-editor" contenteditable="true" @input="onSystemEditorInput"
                    style="padding-right: 28px; min-height: 86px;"></div>
                  <el-icon
                    style="position: absolute; right: 8px; bottom: 8px; color: #c0c4cc; font-size: 16px; pointer-events: none;">
                    <EditPen />
                  </el-icon>
                  <el-dropdown trigger="click" @command="handleSystemQuickAdd"
                    style="position: absolute; right: 8px; top: 8px;">
                    <el-icon style="cursor: pointer; font-size: 16px; color: #909399;">
                      <ArrowDown />
                    </el-icon>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item v-for="(item, index) in systemMsgTemplates" :key="index"
                          :command="item.command">
                          {{ item.label }}
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
                <div style="margin-top: 8px; display: flex; align-items: center; gap: 8px;">
                  <el-color-picker v-model="selectedTextColor" size="small" :predefine="predefineColors" />
                  <el-button size="small" @click="applySelectedColor">应用颜色</el-button>
                </div>
              </div>
            </template>

            <!-- call -->
            <template v-if="selectedMsg.type === 'call'">
              <div class="setting-item">
                <label>发送方</label>
                <el-select v-model="selectedMsg.sender" style="width: 100%;">
                  <el-option label="我" value="me" />
                  <el-option label="对方" value="other" />
                </el-select>
              </div>
              <div class="setting-item">
                <label>类型</label>
                <el-select v-model="selectedMsg.callType" style="width: 100%;">
                  <el-option label="视频通话" value="video" />
                  <el-option label="语音通话" value="audio" />
                </el-select>
              </div>
              <div class="setting-item">
                <label>通话状态</label>
                <el-select v-model="selectedMsg.status" style="width: 100%;">
                  <el-option label="接通" value="connected" />
                  <el-option label="拒绝" value="refused" />
                  <el-option label="取消" value="cancelled" />
                  <el-option label="未接听" value="missed" />
                  <el-option v-if="selectedMsg.sender === 'me'" label="发送失败" value="failed" />
                </el-select>
              </div>
              <div class="setting-item">
                <label>接通时长</label>
                <el-input v-model="selectedMsg.duration">
                  <template #suffix>
                    <el-icon>
                      <EditPen />
                    </el-icon>
                  </template>
                </el-input>
              </div>
            </template>

            <!-- voice -->
            <template v-if="selectedMsg.type === 'voice'">
              <div class="setting-item">
                <label>发送方</label>
                <el-select v-model="selectedMsg.sender" style="width: 100%;">
                  <el-option label="我" value="me" />
                  <el-option label="对方" value="other" />
                </el-select>
              </div>
              <div class="setting-item">
                <label>消息状态</label>
                <el-select v-model="selectedMsg.status" style="width: 100%;">
                  <el-option label="发送成功" value="send" />
                  <el-option v-if="selectedMsg.sender === 'other'" label="未读" value="unread" />
                  <el-option v-if="selectedMsg.sender === 'me'" label="发送失败" value="failed" />
                </el-select>
              </div>
              <div class="setting-item">
                <label>语音时长 (最长60s)</label>
                <el-input-number v-model="selectedMsg.duration" :min="1" :max="60" controls-position="right"
                  style="width: 100%;" />
              </div>
            </template>

            <!-- time -->
            <template v-if="selectedMsg.type === 'time'">
              <div class="setting-item">
                <label>时间</label>
                <el-date-picker v-model="selectedMsg.timeText" type="datetime" placeholder="Pick a Date"
                  format="YYYY年MM月DD日 HH:mm:ss" value-format="YYYY年MM月DD日 HH:mm:ss" />
              </div>
            </template>

            <div class="setting-item" style="margin-top: 24px;">
              <label>快捷操作</label>
              <div style="display: flex; gap: 8px; margin-top: 8px;">
                <el-button plain size="small" @click="moveUp(selectedIdx)">上移</el-button>
                <el-button plain size="small" @click="moveDown(selectedIdx)">下移</el-button>
                <el-button plain size="small" @click="copyMessage(selectedIdx)">复制</el-button>
                <el-button plain size="small" type="danger" @click="removeMessage(selectedIdx)">删除</el-button>
              </div>
            </div>
          </div>
        </div>
        <div class="msg-edit-col" style="flex: 1; padding-left: 32px; border-left: 1px solid #f0f0f0;" v-else>
          <div style="text-align: center; color: #999; margin-top: 40px;">请选择一条消息</div>
        </div>
      </div>
    </template>
  </SimulatorLayout>
</template>

<script setup>
import { ref, reactive, computed, inject, onMounted, watch, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Top, Bottom, Delete, EditPen, ArrowDown } from '@element-plus/icons-vue'
import ChatPreview from '@/components/chat/ChatPreview.vue'
import SimulatorLayout from '@/components/simulator/SimulatorLayout.vue'
import api from '@/api'
import { useUserStore } from '@/stores/user'
import html2canvas from 'html2canvas'
import { checkUserVip } from '@/utils/appUtils'

const userStore = useUserStore()
const showPayment = inject('showPayment')
const route = useRoute()
const router = useRouter()

const workId = ref('')
const originalTitle = ref('')

const layoutRef = ref()
const previewRef = ref()
const previewAreaRef = computed(() => layoutRef.value?.previewAreaRef)

const tabs = ref([
  { label: '聊天设置', value: 'edit' },
  { label: '外观设置', value: 'appearance' }
])
const activeTab = ref('edit')

const selectedIdx = ref(0)
const systemEditorRef = ref()
const selectedTextColor = ref('#e64340')
const predefineColors = ref([
  '#e64340', // 默认红色
  '#EF9C34', // 要求增加的橘色
  '#5C6B94', // 蓝色
  '#069135', // 绿色
  '#657AC6', // 蓝紫色
  '#DB61E1', // 粉紫色
  '#999999', // 灰色
  '#000000'  // 黑色
])

const systemMsgTemplates = ref([
  { label: '+ 我撤回消息', command: '你撤回了一条消息' },
  { label: '+ 对方撤回消息', command: 'xx 撤回了一条消息' },
  { label: '+ 通过好友申请', command: '你已添加了xx，以上是打招呼的消息。' },
  { label: '+ 好友申请被通过', command: "'xx通过了你的朋友验证请求，以上是打招呼的消息。" },
  { label: '+ 被拉黑', command: '消息已发出，但被对方拒收了。' },
  { label: '+ 被删除', command: "xx开启的朋友验证，你还不是他（她）朋友。请先发送朋友验证请求，对方验证通过后，才能聊天。<span style='color: #576B95;'>发送朋友验证</span>" },
  { label: '+ 添加成功', command: '你已成功添加了xx，现在可以聊天了。' },
  { label: '+ 添加成功提示', command: '以上是打招呼的消息' },
  { label: '+ 账号安全', command: '对方账号不在常用环境使用，请仔细核实真实身份，涉及汇款、转账等务必电话确认，请保护自身财产和隐私安全。' },
  { label: '+ 我要投诉', command: "对方账号安全性未知，如涉及金钱交易务必电话确认，保护个人财产和隐私安全。<span style='color: #576B95;'>我要投诉</span>" },
  { label: '+ 红包领取', command: "<img style='width: 16px;height: 16px;vertical-align: middle;margin-right:7px' src='/src/public/wx-chat/receive-tip.png'></img>xxx领取了xxx的<span style='color: #F49738;'>红包</span>" }
])

let msgIdCounter = 1

const settings = reactive({
  title: '男神',
  unread: '50',
  myName: '鱼鱼',
  theirName: '男神',
  myAvatarUrl: userStore.avatarUrl || '',
  theirAvatarUrl: '',
  phoneModel: 'ios',
  statusTime: new Date().toTimeString().slice(0, 5),
  signal: '3',
  wifi: '3',
  isCharging: true,
  battery: 60,
  earpiece: true,
  voiceMode: false,
  theme: 'light',
  isDark: false,
  showBottomBar: true,
  wallpaper: '',
  notDisturb: false,
  showMicIcon: false,
})

const messages = ref([
  { id: msgIdCounter++, type: 'text', sender: 'other', content: '你好，认识一下', status: 'send' },
  { id: msgIdCounter++, type: 'system', content: '以上是打招呼内容' },
  { id: msgIdCounter++, type: 'text', sender: 'me', content: '我是装样大师', status: 'send' },
])

const selectedMsg = computed(() => {
  if (selectedIdx.value >= 0 && selectedIdx.value < messages.value.length)
    return messages.value[selectedIdx.value]
  return null
})

const typeLabels = { text: '文字', time: '时间', redpacket: '红包', transfer: '转账', system: '系统提示语', call: '通话', voice: '语音' }

const getTypeLabel = (msg) => {
  if (!msg) return ''
  if (msg.type === 'call') {
    if (msg.callType === 'video') return '视频通话'
    if (msg.callType === 'audio') return '语音通话'
  }
  return typeLabels[msg.type]
}

function handleSystemQuickAdd(command) {
  if (selectedMsg.value && selectedMsg.value.type === 'system') {
    selectedMsg.value.content = command
    if (systemEditorRef.value) {
      systemEditorRef.value.innerHTML = command
    }
  }
}

onMounted(async () => {
  const id = route.query.id || route.query.workId
  if (!id) return

  try {
    let drafts = []
    try {
      drafts = JSON.parse(localStorage.getItem('local_drafts') || '[]')
    } catch (e) { }

    const localWork = drafts.find(w => String(w.id) === String(id))
    if (localWork) {
      workId.value = id
      originalTitle.value = localWork.title || ''
      if (localWork.data_json) {
        const data = typeof localWork.data_json === 'string' ? JSON.parse(localWork.data_json) : localWork.data_json
        if (data.settings) Object.assign(settings, data.settings)
        // 这里的 map(m => ({ ...m, id: msgIdCounter++ })) 确保回显后新发送的消息ID不冲突，并且正常驱动视图
        if (data.messages) messages.value = data.messages.map(m => ({ ...m, id: msgIdCounter++ }))
      }
      return
    }

    const work = await api.works.get(id)
    workId.value = id
    originalTitle.value = work.title || ''
    if (work.data_json) {
      const data = typeof work.data_json === 'string' ? JSON.parse(work.data_json) : work.data_json
      if (data.messages) messages.value = data.messages.map(m => ({ ...m, id: msgIdCounter++ }))
      if (data.settings) Object.assign(settings, data.settings)
    }
  } catch (e) {
    console.error('加载草稿异常:', e)
  }
})

function getMessageBrief(msg) {
  if (msg.type === 'text') return (msg.content || '')
  if (msg.type === 'time') return msg.timeText
  if (msg.type === 'redpacket') return msg.title || ''
  if (msg.type === 'transfer') return `¥${msg.amount || 0}`
  if (msg.type === 'system') {
    const text = (msg.content || '').replace(/<[^>]+>/g, '')
    return text.slice(0, 20)
  }
  if (msg.type === 'call') return `通话时长 ${msg.duration || '00:00'}`
  if (msg.type === 'voice') return `语音消息 ${msg.duration || '1'}"`
  return ''
}

function getSystemHtml(msg) {
  return msg.content || ''
}

function addMessage(type) {
  const base = { id: msgIdCounter++, type, status: 'send' }
  if (type === 'text') { base.sender = 'me'; base.content = '你好' }
  else if (type === 'time') { base.timeStyle = 'date'; base.timeText = new Date().toTimeString().slice(0, 5) }
  else if (type === 'redpacket') { base.sender = 'me'; base.title = '恭喜发财，大吉大利' }
  else if (type === 'transfer') { base.sender = 'me'; base.amount = 520; base.remark = '你发起了一笔转账'; base.status = 'send' }
  else if (type === 'system') { base.sender = 'system'; base.content = '你撤回了一条消息' }
  else if (type === 'call') { base.sender = 'me'; base.callType = 'audio'; base.status = 'connected'; base.duration = 12 }
  else if (type === 'voice') { base.sender = 'me'; base.status = 'send'; base.duration = 12 }
  messages.value.push(base)
  selectedIdx.value = messages.value.length - 1
}

function copyMessage(idx) {
  const msg = messages.value[idx]
  if (msg) {
    messages.value.splice(idx + 1, 0, { ...msg, id: msgIdCounter++ })
    selectedIdx.value = idx + 1
  }
}

function onSystemEditorInput(e) {
  if (selectedMsg.value && selectedMsg.value.type === 'system') {
    selectedMsg.value.content = e.target.innerHTML
  }
}

function applySelectedColor() {
  const sel = window.getSelection()
  if (!sel || sel.rangeCount === 0 || sel.getRangeAt(0).collapsed) {
    ElMessage.warning('请先选中要着色的文字')
    return
  }
  const range = sel.getRangeAt(0)
  const span = document.createElement('span')
  span.style.color = selectedTextColor.value
  range.surroundContents(span)
  sel.removeAllRanges()
  const idx = selectedIdx.value
  if (systemEditorRef.value && idx >= 0 && messages.value[idx]) {
    messages.value[idx].content = systemEditorRef.value.innerHTML
  }
}

watch(selectedIdx, () => {
  nextTick(() => {
    if (systemEditorRef.value && selectedMsg.value?.type === 'system') {
      systemEditorRef.value.innerHTML = selectedMsg.value.content || ''
    }
  })
})

function removeMessage(idx) {
  messages.value.splice(idx, 1)
  if (selectedIdx.value >= messages.value.length) selectedIdx.value = messages.value.length - 1
}

function moveUp(idx) { if (idx > 0) { [messages.value[idx], messages.value[idx - 1]] = [messages.value[idx - 1], messages.value[idx]]; selectedIdx.value = idx - 1 } }
function moveDown(idx) { if (idx < messages.value.length - 1) { [messages.value[idx], messages.value[idx + 1]] = [messages.value[idx + 1], messages.value[idx]]; selectedIdx.value = idx + 1 } }

function onRedpacketStatusChange(status) {
  if (status === 'received' && selectedMsg.value?.type === 'redpacket') {
    const existing = messages.value.find(m => m.type === 'system' && m.bindId === selectedMsg.value.id)
    if (!existing) {
      let content = ""
      const theirName = settings.theirName || '对方'
      if (selectedMsg.value.sender === 'me') {
        content = `<img style='width: 16px;height: 16px;vertical-align: middle;margin-right:7px' src='/src/public/wx-chat/receive-tip.png'></img>${theirName}领取了你的<span style='color: #F49738;'>红包</span>`
      } else {
        content = `<img style='width: 16px;height: 16px;vertical-align: middle;margin-right:7px' src='/src/public/wx-chat/receive-tip.png'></img>你领取了${theirName}的<span style='color: #F49738;'>红包</span>`
      }

      messages.value.push({
        id: msgIdCounter++,
        type: 'system',
        sender: 'system',
        content: content,
        bindId: selectedMsg.value.id
      })
    }
  } else if (status != 'received' && selectedMsg.value?.type === 'redpacket') {
    messages.value.forEach((msg, idx) => {
      if (msg.type === 'system' && msg.bindId === selectedMsg.value.id) {
        messages.value.splice(idx, 1)
      }
    })
  }
}

function onTransferStatusChange(status) {
  if (status === 'received' && selectedMsg.value?.type === 'transfer') {
    const existing = messages.value.find(m => m.type === 'transfer' && m.bindId === selectedMsg.value.id)
    if (!existing) {
      messages.value.push({
        id: msgIdCounter++,
        type: 'transfer',
        sender: selectedMsg.value.sender === 'me' ? 'other' : 'me',
        amount: selectedMsg.value.amount || 0,
        remark: '已收款',
        status: 'received',
        bindId: selectedMsg.value.id
      })
    }
    selectedMsg.value.remark = "已被接收"
  } else if (status != 'received' && selectedMsg.value?.type === 'transfer') {
    messages.value.forEach((msg, idx) => {
      if (msg.type === 'transfer' && msg.bindId === selectedMsg.value.id) {
        messages.value.splice(idx, 1)
      }
    })
  }
}

function fileToBase64(file, maxWidth = 0) {
  return new Promise((resolve, reject) => {
    if (!maxWidth) {
      const reader = new FileReader()
      reader.onload = () => resolve(reader.result)
      reader.onerror = reject
      reader.readAsDataURL(file)
      return
    }
    const img = new Image()
    img.onload = () => {
      const canvas = document.createElement('canvas')
      let w = img.naturalWidth, h = img.naturalHeight
      if (w > maxWidth) { h = Math.round(h * maxWidth / w); w = maxWidth }
      canvas.width = w; canvas.height = h
      const ctx = canvas.getContext('2d')
      ctx.drawImage(img, 0, 0, w, h)
      resolve(canvas.toDataURL('image/jpeg', 0.8))
    }
    img.onerror = reject
    img.src = URL.createObjectURL(file)
  })
}

async function handleAvatarUpload(event, type) {
  const file = event.target.files[0]
  if (!file) return
  try {
    const base64 = await fileToBase64(file)
    if (type === 'my') settings.myAvatarUrl = base64
    else settings.theirAvatarUrl = base64
  } catch { ElMessage.error('图片读取失败') }
  event.target.value = ''
}

async function handleWallpaperUpload(event) {
  const file = event.target.files[0]
  if (!file) return
  try { settings.wallpaper = await fileToBase64(file, 800) } catch { ElMessage.error('图片读取失败') }
  event.target.value = ''
}

async function handleSave() {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.replace({ query: { ...route.query, showLogin: 1 } })
    return
  }
  try {
    const defaultTitle = originalTitle.value || settings.title || '未命名作品'
    const { value: title } = await ElMessageBox.prompt('请输入作品名称', '保存草稿', {
      confirmButtonText: '保存',
      cancelButtonText: '取消',
      inputValue: defaultTitle,
      inputPlaceholder: '输入名称（同名将提示覆盖，异名将新建）',
    })
    if (!title) return

    let drafts = []
    try {
      drafts = JSON.parse(localStorage.getItem('local_drafts') || '[]')
      if (!Array.isArray(drafts)) drafts = []
    } catch (e) {
      drafts = []
    }

    let draftId = ''
    let isOverwriteOther = false

    // 只有当修改了名称（或新建作品）时，才去检查重名/新建
    if (title !== originalTitle.value) {
      const existIndex = drafts.findIndex(w => w.title === title && w.type === 'wx-chat')
      if (existIndex !== -1) {
        await ElMessageBox.confirm(`已存在同名作品「${title}」，是否覆盖该作品？`, '提示', {
          confirmButtonText: '覆盖',
          cancelButtonText: '取消',
          type: 'warning'
        })
        draftId = drafts[existIndex].id
        isOverwriteOther = true
      } else {
        // 名称改变且无冲突，则新增为新草稿
        draftId = 'draft_' + Date.now()
      }
    } else {
      // 名称未改变，直接更新当前正在编辑的草稿
      draftId = workId.value || ('draft_' + Date.now())
    }

    let coverImg = ''
    const el = document.getElementById('capture-frame') || previewRef.value?.$el
    if (el) {
      try {
        const canvas = await html2canvas(el, {
          scale: 150 / el.offsetWidth, // 生成缩略图
          useCORS: true,
          onclone: (clonedDoc) => {
            const box = clonedDoc.querySelector('.phone-box')
            if (box) box.style.transform = 'none'
            const frame = clonedDoc.getElementById('capture-frame')
            if (frame) {
              frame.style.borderRadius = '0'
              if (!userStore.isVip) {
                const watermark = clonedDoc.querySelector('.watermark-overlay')
                if (watermark) {
                  watermark.style.borderRadius = '0'
                  frame.appendChild(watermark)
                }
              }
            }
          }
        })
        coverImg = canvas.toDataURL('image/jpeg', 0.8)
      } catch (err) {
        console.error('生成封面失败', err)
      }
    }

    const payload = {
      id: draftId,
      type: 'wx-chat',
      page_router: '/chat',
      title,
      cover_img: coverImg,
      data_json: JSON.stringify({ messages: messages.value, settings }),
      updated_at: new Date().toISOString(),
      created_at: new Date().toISOString()
    }

    const existingIndex = drafts.findIndex(d => d.id === draftId)
    if (existingIndex !== -1) {
      // 保持原有创建时间
      payload.created_at = drafts[existingIndex].created_at
      drafts[existingIndex] = payload
    } else {
      drafts.unshift(payload)
    }

    localStorage.setItem('local_drafts', JSON.stringify(drafts))

    // 如果是覆盖了别的作品，或者新建了作品，更新当前状态
    originalTitle.value = title
    if (!workId.value || isOverwriteOther) {
      workId.value = draftId
      router.replace({ query: { id: draftId } })
    }

    ElMessage.success('草稿保存成功')
  } catch (e) {
    if (e !== 'cancel') {
      console.error(e)
      ElMessage.error('保存失败')
    }
  }
}

async function handleExport() {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.replace({ query: { ...route.query, showLogin: 1 } })
    return
  }
  if (!userStore.isVip) {
    showPayment?.()
    return
  }

  const el = document.getElementById('capture-frame') || previewRef.value?.$el
  if (!el) { ElMessage.error('预览未就绪'); return }

  try {
    async function imageToBase64(src) {
      if (!src || src.startsWith('data:')) return src
      return new Promise((resolve) => {
        const img = new Image()
        img.crossOrigin = 'anonymous'
        img.onload = () => {
          const canvas = document.createElement('canvas')
          canvas.width = img.naturalWidth; canvas.height = img.naturalHeight
          canvas.getContext('2d').drawImage(img, 0, 0)
          resolve(canvas.toDataURL('image/png'))
        }
        img.onerror = () => resolve(src)
        img.src = src
      })
    }

    const avatarImgs = el.querySelectorAll('.avatar:not(.placeholder)')
    const originalSrcs = []
    for (const img of avatarImgs) {
      originalSrcs.push(img.src)
      img.src = await imageToBase64(img.src)
    }

    const canvas = await html2canvas(el, {
      scale: 3.144,
      useCORS: true,
      onclone: (clonedDoc) => {
        const box = clonedDoc.querySelector('.phone-box')
        if (box) box.style.transform = 'none'
        const frame = clonedDoc.getElementById('capture-frame')
        if (frame) frame.style.borderRadius = '0'
      }
    })

    avatarImgs.forEach((img, i) => { img.src = originalSrcs[i] })

    const ctx = canvas.getContext('2d')
    ctx.fillStyle = 'rgba(255,255,255,.6)'
    ctx.font = '24px sans-serif'
    ctx.fillText('模拟截图', canvas.width - 160, canvas.height - 20)

    const link = document.createElement('a')
    link.download = `wechat-chat-${Date.now()}.png`
    link.href = canvas.toDataURL('image/png')
    link.click()
    ElMessage.success('截图已下载')
  } catch (e) { ElMessage.error('导出失败：' + e.message) }
}
</script>

<style lang="scss" scoped>
.hidden-file {
  display: none;
}

.avatar-upload-item {
  display: flex;
  flex-direction: column;
  align-items: center;

  .text {
    font-size: 12px;
    color: #AAAAAA;
    line-height: 20px;
  }
}

.upload-area {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  border: 1px dashed #ccc;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  background: #f9f9f9;
  overflow: hidden;

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  span {
    font-size: 24px;
    color: #ccc;
  }
}

.msg-list {
  display: flex;
  flex-direction: column;
  gap: 4px;

  .msg-item {
    display: flex;
    align-items: center;
    gap: 5px;
    padding: 4px 14px 4px 4px;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.2s;
    border: 1px solid transparent;

    &:hover {
      background: #f0f0f0;
    }

    &.active {
      border-color: #C05BFF;
      background: linear-gradient(215deg, rgba(166, 121, 244, 0.2) 7.14%, rgba(119, 140, 245, 0.2) 100%);
    }



    .msg-brief {
      max-width: 350px;
      flex: 1;
      font-weight: 400;
      font-size: 14px;
      color: #1A1A1A;
      line-height: 14px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .msg-actions {
      display: none;
      gap: 6px;
      font-size: 14px;
      color: #999;
    }

    &:hover .msg-actions,
    &.active .msg-actions {
      display: flex;
    }

    .el-icon:hover {
      color: #1890ff;
    }
  }
}

.msg-type-tag {
  font-size: 14px;
  padding: 4px;
  border-radius: 4px;
  font-weight: 400;
  font-size: 14px;
  line-height: 14px;

  &.type-text {
    color: #069135;
    background: #CFFFD2;
    border: 1px solid #CFFFD2;
  }

  &.type-transfer {
    color: #E09711;
    background: #FFF9CF;
    border: 1px solid #FFF9CF;
  }

  &.type-redpacket {
    color: #FF573D;
    background: #FFECE9;
    border: 1px solid #FFECE9;
  }

  &.type-time {
    color: #DB61E1;
    background: #FEEBFF;
    border: 1px solid #FEEBFF;
  }

  &.type-system {
    color: #657AC6;
    background: #EDF1FF;
    border: 1px solid #EDF1FF;
  }

  &.type-call {
    color: #409EFF;
    background: #ECF5FF;
    border: 1px solid #ECF5FF;
  }

  &.type-voice {
    color: #3DB0B8;
    background: #E3FFF1;
    border: 1px solid #E3FFF1;
  }
}

.edit-form {
  .setting-item {
    margin-bottom: 20px;
    display: flex;
    flex-direction: column;
    gap: 8px;

    label {
      font-size: 14px;
      color: #767676;
      margin: 0;
      line-height: 1.2;
      margin-top: 0 !important;
      margin-bottom: 0 !important;
    }
  }
}

.rich-editor {
  min-height: 80px;
  max-height: 150px;
  overflow-y: auto;
  padding: 8px;
  border-radius: 4px;
  box-shadow: 0 0 0 1px #dcdfe6 inset;
  outline: none;
  font-size: 13px;
  line-height: 1.5;
  background: #fff;

  &:empty::before {
    content: "输入文本...";
    color: #c0c4cc;
  }
}
</style>

<style lang="scss">
.custom-chat-popover {
  border-radius: 12px !important;
  padding: 4px !important;
  border: none !important;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08) !important;

  .add-type-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 4px;

    .add-type-item {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      width: 60px !important;
      font-size: 12px;
      text-align: center;
      padding: 0 8px;
      height: 24px;
      color: #1A1A1A;
      cursor: pointer;
      border-radius: 4px;
      transition: background-color 0.2s;
      user-select: none;

      .plus {
        font-size: 16px;
        font-weight: 300;
        margin-right: 4px;
        line-height: 1;
      }

      &:hover {
        background-color: #F7F8FF;
      }
    }
  }
}
</style>
