<template>
  <SimulatorLayout ref="layoutRef" @save="handleSave" @export="handleExport">
    <template #preview>
      <BalancePreview ref="previewRef" :settings="balanceSettings" />
    </template>

    <template #config>
      <div class="section-label">余额区域</div>
      <div class="setting-item" style="margin-bottom: 30px;">
        <label>余额数值</label>
        <el-input-number class="input" v-model="balanceSettings.amount" :precision="2" :min="0"
          controls-position="right" style="width: 180px;" />
      </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="balanceSettings.phoneModel" style="width:90px;">
            <el-option label="苹果" value="ios" />
          </el-select>
        </div>
        <div class="setting-item">
          <label>时间</label>
          <el-time-picker v-model="balanceSettings.statusTime" format="HH:mm" value-format="HH:mm" style="width:128px"
            :clearable="false" />
        </div>
        <div class="setting-item">
          <label>手机信号</label>
          <el-select v-model="balanceSettings.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="balanceSettings.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="balanceSettings.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="balanceSettings.battery" :min="1" :max="100" :show-tooltip="false" style="flex: 1;" />
            <span style="font-size: 14px; color: #1A1A1A; white-space: nowrap;">电量{{ balanceSettings.battery }}%</span>
          </div>
        </div>
      </div>

      <div class="status-row" style="display: flex; gap: 32px; align-items: flex-start; margin-bottom: 30px;">
        <div style="flex: 1;">
          <div class="setting-item switch-item" style="justify-content: flex-start; gap: 12px; margin-bottom: 16px;">
            <span style="font-weight: bold; font-size: 16px; color: #1A1A1A;">零钱通</span>
            <el-switch v-model="balanceSettings.showLiqitong" />
          </div>
          <div class="setting-item" v-if="balanceSettings.showLiqitong">
            <label>文案</label>
            <el-input v-model="balanceSettings.liqitongDesc" placeholder="转入零钱通，能赚又能花" style="margin-bottom: 12px;" />
            <el-input v-model="balanceSettings.liqitongRate" placeholder="零钱通 七日年化1.17%" />
          </div>
        </div>

        <div style="flex: 1;">
          <div class="setting-item switch-item" style="justify-content: flex-start; gap: 12px; margin-bottom: 16px;">
            <span style="font-weight: bold; font-size: 16px; color: #1A1A1A;">支付限额</span>
            <el-switch v-model="balanceSettings.showLimit" />
          </div>
          <div class="setting-item" v-if="balanceSettings.showLimit">
            <label>限额额度</label>
            <el-input-number v-model="balanceSettings.limitAmount" :precision="2" :min="0" controls-position="right"
              style="width:100%" />
          </div>
        </div>

        <div style="flex: 1;">
          <div class="setting-item switch-item" style="justify-content: flex-start; gap: 12px; margin-bottom: 16px;">
            <span style="font-weight: bold; font-size: 16px; color: #1A1A1A;">底部设置</span>
            <el-switch v-if="false" v-model="balanceSettings.showFAQ" />
          </div>
          <div class="setting-item" v-if="balanceSettings.showFAQ">
            <label>服务商标注</label>
            <el-input v-model="balanceSettings.serviceText" placeholder="本服务由财付通提供" />
          </div>
        </div>
      </div>

      <div class="setting-item switch-item" style="justify-content: flex-start; gap: 12px;">
        <span style="font-weight: bold; font-size: 16px; color: #1A1A1A;">深色模式</span>
        <el-switch v-model="balanceSettings.isDark" @change="val => balanceSettings.theme = val ? 'dark' : 'light'" />
      </div>
    </template>
  </SimulatorLayout>
</template>

<script setup>
import { ref, reactive, inject, onMounted, watch, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { FolderAdd, Download } from '@element-plus/icons-vue'
import BalancePreview from '@/components/balance/BalancePreview.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 previewRef = ref()
const layoutRef = ref()
const previewAreaRef = computed(() => layoutRef.value?.previewAreaRef)


const balanceSettings = reactive({
  statusTime: new Date().toTimeString().slice(0, 5),
  phoneModel: 'ios',
  signal: '4',
  wifi: '3',
  isCharging: true,
  battery: 60,
  pageTitle: '零钱明细',
  nickName: '我的零钱',
  amount: 520.00,
  showLiqitong: true,
  liqitongRate: '七日年化1.17%',
  liqitongDesc: '转入零钱通，能赚又能花',
  showChargeBtn: true,
  showWithdrawBtn: true,
  showFAQ: true,
  serviceText: '本服务由财付通提供',
  theme: 'light',
  isDark: false,
  showLimit: true,
  limitAmount: 5000.00
})

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

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

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

    const work = drafts.find(w => String(w.id) === String(id))
    if (work) {
      workId.value = id
      originalTitle.value = work.title || ''
      if (work.data_json) {
        const configData = typeof work.data_json === 'string' ? JSON.parse(work.data_json) : work.data_json
        Object.assign(balanceSettings, configData)
      }
      return
    }

    const remoteWork = await api.works.get(id)
    if (remoteWork) {
      workId.value = id
      originalTitle.value = remoteWork.title || ''
      if (remoteWork.data_json) {
        const configData = typeof remoteWork.data_json === 'string' ? JSON.parse(remoteWork.data_json) : remoteWork.data_json
        Object.assign(balanceSettings, configData)
      }
    }
  } catch (e) {
    console.error('获取草稿失败:', e)
  }
})

async function handleSave() {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.replace({ query: { ...route.query, showLogin: 1 } })
    return
  }
  try {
    const defaultTitle = originalTitle.value || balanceSettings.pageTitle || '未命名作品'
    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-balance')
      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, // 固定生成 150px 宽度的图片
          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.6)
      } catch (err) {
        console.error('截图生成失败', err)
      }
    }

    const payload = {
      id: draftId,
      title: title,
      type: 'wx-balance',
      page_router: '/balance',
      data_json: JSON.stringify(balanceSettings),
      cover_img: coverImg,
      update_time: Date.now()
    }

    let isSelfUpdate = false
    if (isOverwriteOther) {
      const existIndex = drafts.findIndex(w => String(w.id) === String(draftId))
      if (existIndex !== -1) drafts[existIndex] = payload
    } else {
      const selfIndex = drafts.findIndex(w => String(w.id) === String(draftId))
      if (selfIndex !== -1) {
        drafts[selfIndex] = payload
        isSelfUpdate = true
      } else {
        drafts.unshift(payload)
      }
    }

    localStorage.setItem('local_drafts', JSON.stringify(drafts))
    workId.value = payload.id
    originalTitle.value = payload.title

    let msg = '已新增草稿'
    if (isOverwriteOther) msg = '草稿已覆盖保存'
    else if (isSelfUpdate) msg = '草稿已更新'
    ElMessage.success(msg)
  } 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
  }

  // 关键防护：触发导出前强制等待最新的后台用户信息校验完成（防篡改本地缓存与时间差）
  try {
    if (userStore.fetchProfile) {
      await userStore.fetchProfile()
    }
  } catch (e) { }

  if (!userStore.isVip) {
    showPayment?.()
    return
  }

  const el = document.getElementById('capture-frame') || previewRef.value?.$el
  if (!el) { ElMessage.error('预览未就绪，请稍后重试'); return }
  try {
    const canvas = await html2canvas(el, {
      scale: 3.144,
      useCORS: true,
      onclone: (clonedDoc) => {
        // 移除克隆DOM中外层容器的缩放，使得截图按1:1真实尺寸和字体渲染
        const box = clonedDoc.querySelector('.phone-box')
        if (box) {
          box.style.transform = 'none'
        }
        // 移除圆角以防止出现四个白角
        const frame = clonedDoc.getElementById('capture-frame')
        if (frame) {
          frame.style.borderRadius = '0'
        }
      }
    })
    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-balance-${Date.now()}.png`
    link.href = canvas.toDataURL('image/png')
    link.click()
    ElMessage.success('截图已下载')
  } catch (e) { ElMessage.error('导出失败：' + e.message) }
}
</script>

<style lang="scss" scoped></style>
