<template>
  <div class="page-home-config">
    <!-- 顶部操作栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <h2 class="toolbar-title">权益介绍页配置</h2>
        <el-tag v-if="pageStatus === 'published'" type="success" size="small" effect="plain">正式线上环境</el-tag>
        <el-tag v-else-if="pageStatus === 'modified'" type="warning" size="small" effect="plain">有未发布的修改</el-tag>
        <el-tag v-else size="small" effect="plain">草稿 (未发布)</el-tag>
      </div>
      <div class="toolbar-right">
        <el-button size="small" icon="el-icon-link" @click="showLinkDialog">获取链接</el-button>
        <el-button size="small" type="primary" plain @click="handleSave('draft')">保存草稿</el-button>
        <el-button size="small" type="primary" @click="handleSave('publish')">发布上线</el-button>
      </div>
    </div>

    <!-- 客群Tab -->
    <el-tabs v-model="currentTier" @tab-click="onTierChange">
      <el-tab-pane
        v-for="tier in tiers"
        :key="tier.key"
        :label="configData[tier.key] ? configData[tier.key].tabName : tier.label"
        :name="tier.key"
      />
    </el-tabs>

    <!-- 配置表单 -->
    <div v-if="currentTierData" class="config-sections">
      <!-- Tab名称配置 -->
      <el-card class="section-card" shadow="hover">
        <div slot="header" class="section-header">
          <i class="el-icon-folder-opened"></i> Tab名称配置
        </div>
        <el-form label-width="80px">
          <el-form-item label="Tab名称">
            <el-input v-model="currentTierData.tabName" placeholder="例如：卓越理财" style="width: 50%" @input="markModified" />
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 头部配置 -->
      <el-card class="section-card" shadow="hover">
        <div slot="header" class="section-header">
          <i class="el-icon-picture-outline"></i> 头部配置
        </div>
        <el-form label-width="100px">
          <el-form-item label="头图配图">
            <div class="image-upload-area">
              <div class="upload-box" @click="triggerUpload('header')">
                <img v-if="currentTierData.header.imageUrl" :src="currentTierData.header.imageUrl" class="preview-img" />
                <div v-else class="upload-placeholder">
                  <i class="el-icon-picture"></i>
                  <span>未上传图片</span>
                </div>
                <div class="upload-overlay">
                  <i class="el-icon-upload2"></i>
                  <span>点击上传</span>
                </div>
              </div>
              <div class="upload-tip">建议图片尺寸：<b>686 × 296 px</b></div>
            </div>
            <input ref="headerUpload" type="file" accept="image/*" style="display:none" @change="onImageUpload($event, 'header')" />
          </el-form-item>
          <el-form-item label="主标题（粗体）">
            <el-input v-model="currentTierData.header.mainTitle" @input="markModified" />
          </el-form-item>
          <el-form-item label="副标题（小字）">
            <el-input v-model="currentTierData.header.subTitle" @input="markModified" />
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 按钮配置 -->
      <el-card class="section-card" shadow="hover">
        <div slot="header" class="section-header">
          <i class="el-icon-thumb"></i> 按钮配置
        </div>
        <el-form label-width="130px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="已解锁按钮文案">
                <el-input v-model="currentTierData.buttons.unlocked" placeholder="例如：进入权益专区" @input="markModified" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="待解锁按钮文案">
                <el-input v-model="currentTierData.buttons.locked" placeholder="例如：待解锁" @input="markModified" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>

      <!-- 权益列表配置 -->
      <el-card class="section-card" shadow="hover">
        <div slot="header" class="section-header">
          <i class="el-icon-s-grid"></i> 权益列表配置
          <el-button type="text" icon="el-icon-circle-plus-outline" @click="addPrivilege" style="float:right">添加权益</el-button>
        </div>
        <div v-if="currentTierData.privileges.length === 0" class="empty-tip">
          暂无权益项
        </div>
        <div v-for="(item, index) in currentTierData.privileges" :key="index" class="privilege-item">
          <div class="privilege-index">NO. {{ index + 1 }}</div>
          <div class="privilege-actions">
            <el-popover placement="bottom" trigger="click" width="180">
              <div>
                <div style="margin-bottom:8px;font-size:13px;color:#666">移动到序号：</div>
                <div style="display:flex;gap:8px">
                  <el-input-number v-model="sortTarget" :min="1" :max="currentTierData.privileges.length" size="mini" controls-position="right" style="width:100px" />
                  <el-button size="mini" type="primary" @click="movePrivilege(index, sortTarget - 1)">确定</el-button>
                </div>
              </div>
              <el-button slot="reference" size="mini" icon="el-icon-sort" circle @click="sortTarget = index + 1" />
            </el-popover>
            <el-button size="mini" type="danger" icon="el-icon-delete" circle @click="removePrivilege(index)" />
          </div>
          <div class="privilege-content">
            <div class="privilege-image" @click="triggerUpload('privilege', index)">
              <img v-if="item.imageUrl" :src="item.imageUrl" class="preview-img-sm" />
              <div v-else class="upload-placeholder-sm">
                <i class="el-icon-picture"></i>
                <span>未上传</span>
              </div>
              <input :ref="'privilegeUpload' + index" type="file" accept="image/*" style="display:none" @change="onImageUpload($event, 'privilege', index)" />
            </div>
            <div class="privilege-text-tip">非必填<br/>无图展示圆点</div>
            <div class="privilege-fields">
              <el-form label-width="60px" inline>
                <el-form-item label="标题">
                  <el-input v-model="item.title" style="width:160px" @input="markModified" />
                </el-form-item>
                <el-form-item label="描述">
                  <el-input v-model="item.desc" style="width:300px" @input="markModified" />
                </el-form-item>
              </el-form>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 获取链接弹窗 -->
    <el-dialog title="获取页面链接" :visible.sync="linkDialogVisible" width="680px">
      <el-form label-width="100px" inline>
        <el-form-item label="Campaign ID">
          <el-select v-model="linkForm.campaignId" clearable placeholder="请选择 (无)" @change="updateLinks">
            <el-option label="CAMP202511" value="CAMP202511" />
            <el-option label="CAMP_WINTER" value="CAMP_WINTER" />
          </el-select>
        </el-form-item>
        <el-form-item label="Channel ID">
          <el-select v-model="linkForm.channelId" clearable placeholder="请选择 (无)" @change="updateLinks">
            <el-option label="APP推送" value="CH_APP" />
            <el-option label="微信公众号" value="CH_WECHAT" />
          </el-select>
        </el-form-item>
      </el-form>
      <div v-if="pageStatus === 'published'" class="link-section">
        <div class="link-label"><span class="dot dot-green"></span> 正式环境链接</div>
        <div class="link-row">
          <span class="link-type">H5 链接</span>
          <el-input :value="prodH5Url" readonly size="small" />
          <el-button size="small" type="primary" plain @click="copyLink(prodH5Url)">复制</el-button>
        </div>
        <div class="link-row">
          <span class="link-type">小程序/APP</span>
          <el-input :value="prodAppUrl" readonly size="small" />
          <el-button size="small" type="primary" plain @click="copyLink(prodAppUrl)">复制</el-button>
        </div>
      </div>
      <div class="link-section">
        <div class="link-label"><span class="dot dot-blue"></span> 草稿预览链接 (测试)</div>
        <div class="link-row">
          <el-input :value="testUrl" readonly size="small" />
          <el-button size="small" type="primary" plain @click="copyLink(testUrl)">复制</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'PageHomeConfig',
  data() {
    return {
      currentTier: 'premier',
      tiers: [
        { key: 'premier', label: '卓越理财' },
        { key: 'elite', label: '卓越理财·尊尚' },
        { key: 'global', label: '环球私人银行' }
      ],
      configData: {},
      pageStatus: 'draft',
      sortTarget: 1,
      linkDialogVisible: false,
      linkForm: { campaignId: '', channelId: '' }
    }
  },
  computed: {
    currentTierData() {
      return this.configData[this.currentTier] || null
    },
    linkQueryStr() {
      const params = []
      if (this.linkForm.campaignId) params.push(`CampaignId=${this.linkForm.campaignId}`)
      if (this.linkForm.channelId) params.push(`Channelid=${this.linkForm.channelId}`)
      return params.length ? '?' + params.join('&') : ''
    },
    prodH5Url() {
      return `https://hsbc.com/home${this.linkQueryStr}`
    },
    prodAppUrl() {
      return `hsbc-app://home${this.linkQueryStr}`
    },
    testUrl() {
      const q = this.linkQueryStr
      return `https://test.hsbc.com/home${q ? q + '&' : '?'}draft=1`
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    async fetchData() {
      const res = await request.get('/api/page-config/home')
      this.configData = res.data.config
      this.pageStatus = res.data.status
    },
    markModified() {
      if (this.pageStatus === 'published') {
        this.pageStatus = 'modified'
      }
    },
    onTierChange() {},
    triggerUpload(type, index) {
      if (type === 'header') {
        this.$refs.headerUpload.click()
      } else {
        const ref = this.$refs['privilegeUpload' + index]
        if (ref) (Array.isArray(ref) ? ref[0] : ref).click()
      }
    },
    onImageUpload(event, type, index) {
      const file = event.target.files[0]
      if (!file) return
      const reader = new FileReader()
      reader.onload = (e) => {
        if (type === 'header') {
          this.currentTierData.header.imageUrl = e.target.result
        } else {
          this.$set(this.currentTierData.privileges[index], 'imageUrl', e.target.result)
        }
        this.markModified()
      }
      reader.readAsDataURL(file)
      event.target.value = ''
    },
    addPrivilege() {
      this.currentTierData.privileges.push({ imageUrl: '', title: '新权益', desc: '描述...' })
      this.markModified()
    },
    removePrivilege(index) {
      this.currentTierData.privileges.splice(index, 1)
      this.markModified()
    },
    movePrivilege(from, to) {
      if (to < 0 || to >= this.currentTierData.privileges.length || from === to) return
      const item = this.currentTierData.privileges.splice(from, 1)[0]
      this.currentTierData.privileges.splice(to, 0, item)
      this.markModified()
    },
    async handleSave(type) {
      const status = type === 'publish' ? 'published' : 'draft'
      await request.put('/api/page-config/home', { config: this.configData, status })
      this.pageStatus = status
      this.$message.success(type === 'publish' ? '已发布权益介绍页配置！' : '已保存权益介绍页配置草稿！')
    },
    showLinkDialog() {
      this.linkForm = { campaignId: '', channelId: '' }
      this.linkDialogVisible = true
    },
    updateLinks() {},
    copyLink(text) {
      navigator.clipboard.writeText(text).then(() => {
        this.$message.success('链接已复制到剪贴板')
      })
    }
  }
}
</script>

<style scoped>
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 12px 16px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0,0,0,.06);
}
.toolbar-left { display: flex; align-items: center; gap: 12px; }
.toolbar-title { margin: 0; font-size: 18px; font-weight: 600; }
.toolbar-right { display: flex; gap: 8px; }

.config-sections { margin-top: 16px; }
.section-card { margin-bottom: 16px; }
.section-header { font-weight: 600; }
.section-header i { margin-right: 6px; color: #909399; }

.image-upload-area { display: flex; align-items: center; gap: 16px; }
.upload-box {
  width: 360px; height: 160px;
  background: #eef6fc; border: 1px solid #dcdfe6; border-radius: 4px;
  position: relative; overflow: hidden; cursor: pointer;
  display: flex; align-items: center; justify-content: center;
}
.upload-box:hover .upload-overlay { display: flex; }
.preview-img { width: 100%; height: 100%; object-fit: cover; }
.upload-placeholder {
  display: flex; flex-direction: column; align-items: center;
  color: #c0c4cc; font-size: 12px;
}
.upload-placeholder i { font-size: 28px; margin-bottom: 4px; }
.upload-overlay {
  display: none; position: absolute; inset: 0;
  background: rgba(0,0,0,.5); color: #fff;
  flex-direction: column; align-items: center; justify-content: center;
  font-size: 14px;
}
.upload-overlay i { font-size: 28px; margin-bottom: 6px; }
.upload-tip {
  font-size: 12px; color: #909399;
  background: #f5f7fa; padding: 8px 12px; border-radius: 4px; border: 1px solid #ebeef5;
}

.privilege-item {
  position: relative;
  border: 1px solid #ebeef5; border-radius: 8px;
  padding: 20px 16px 16px; margin-bottom: 12px;
  background: #fff;
}
.privilege-index {
  position: absolute; left: 0; top: 0;
  background: #409EFF; color: #fff;
  font-size: 11px; font-weight: 700;
  padding: 2px 10px; border-radius: 8px 0 8px 0;
}
.privilege-actions {
  position: absolute; right: 12px; top: 12px;
  display: flex; gap: 6px;
}
.privilege-content { display: flex; align-items: flex-start; gap: 12px; margin-top: 8px; }
.privilege-image {
  width: 56px; height: 56px; flex-shrink: 0;
  background: #eef6fc; border: 1px solid #dcdfe6; border-radius: 4px;
  display: flex; align-items: center; justify-content: center;
  cursor: pointer; overflow: hidden; position: relative;
}
.preview-img-sm { width: 100%; height: 100%; object-fit: cover; }
.upload-placeholder-sm {
  display: flex; flex-direction: column; align-items: center;
  color: #c0c4cc; font-size: 10px;
}
.upload-placeholder-sm i { font-size: 18px; }
.privilege-text-tip { font-size: 10px; color: #c0c4cc; text-align: center; line-height: 1.3; flex-shrink: 0; margin-top: 4px; }
.privilege-fields { flex: 1; }

.empty-tip {
  text-align: center; color: #c0c4cc; padding: 24px;
  border: 1px dashed #dcdfe6; border-radius: 4px;
}

.link-section { margin-top: 16px; padding: 12px; background: #fafafa; border-radius: 6px; border: 1px solid #ebeef5; }
.link-section + .link-section { margin-top: 12px; }
.link-label { font-weight: 600; margin-bottom: 8px; display: flex; align-items: center; gap: 6px; }
.link-row { display: flex; align-items: center; gap: 8px; margin-bottom: 6px; }
.link-type { font-size: 12px; color: #909399; width: 70px; flex-shrink: 0; }
.dot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; }
.dot-green { background: #67C23A; }
.dot-blue { background: #409EFF; }
</style>
