<template>
  <div class="page-zone-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="info" 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>

    <!-- 活动广告轮播图 -->
    <el-card class="section-card" shadow="hover">
      <div slot="header" class="section-header">
        <span><i class="el-icon-data-board"></i> 活动广告轮播图</span>
        <el-button type="text" icon="el-icon-circle-plus-outline" @click="addCarousel" style="float:right">添加轮播</el-button>
      </div>
      <div v-if="configData.adCarousel.length === 0" class="empty-tip">暂无广告轮播图</div>
      <div v-for="(item, index) in configData.adCarousel" :key="'c' + index" class="carousel-item">
        <div class="item-index">NO. {{ index + 1 }}</div>
        <div class="item-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="configData.adCarousel.length" size="mini" controls-position="right" style="width:100px" />
                <el-button size="mini" type="primary" @click="moveItem('adCarousel', 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="removeCarousel(index)" />
        </div>

        <!-- 图片上传 -->
        <div class="carousel-body">
          <div class="image-upload-area">
            <div class="upload-box" @click="triggerUpload('carousel', index)">
              <img v-if="item.imageUrl" :src="item.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>
            <input :ref="'carouselUpload' + index" type="file" accept="image/*" style="display:none" @change="onImageUpload($event, 'carousel', index)" />
          </div>

          <!-- 标题 -->
          <el-form label-width="80px" style="margin-top:12px">
            <el-form-item label="主标题">
              <el-input v-model="item.title" @input="markModified" />
            </el-form-item>
            <el-form-item label="副标题">
              <el-input v-model="item.subtitle" @input="markModified" />
            </el-form-item>
          </el-form>

          <!-- 可见人群标签 -->
          <el-form label-width="110px" style="margin-top:4px">
            <el-form-item label="可见人群标签">
              <el-select v-model="item.tags" multiple placeholder="点击选择..." filterable @change="markModified" style="width:100%">
                <el-option v-for="tag in availableTags" :key="tag.id" :label="tag.name" :value="tag.id" />
              </el-select>
            </el-form-item>
          </el-form>

          <!-- 跳转链接配置 -->
          <div class="link-config-block">
            <div class="link-config-title"><i class="el-icon-link"></i> 跳转链接配置</div>
            <el-form label-width="140px">
              <el-form-item label="H5 跳转链接">
                <el-input v-model="item.linkH5" @input="markModified" />
              </el-form-item>
              <el-form-item label="APP 跳转链接">
                <el-input v-model="item.linkApp" @input="markModified" />
              </el-form-item>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="微信小程序 AppID">
                    <el-input v-model="item.wechatAppId" placeholder="例如：wx1234567890abcdef" @input="markModified" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="微信小程序页面路径">
                    <el-input v-model="item.wechatPath" placeholder="例如：pages/index/index" @input="markModified" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 常用兑换配置 -->
    <el-card class="section-card" shadow="hover">
      <div slot="header" class="section-header">
        <span><i class="el-icon-s-grid"></i> 常用兑换配置</span>
        <el-button type="text" icon="el-icon-circle-plus-outline" @click="addExchangeItem" style="float:right">添加兑换项</el-button>
      </div>
      <div v-if="configData.exchangeConfig.items.length === 0" class="empty-tip">暂无常用兑换项</div>
      <div v-for="(item, index) in configData.exchangeConfig.items" :key="'e' + index" class="exchange-item">
        <div class="item-index">NO. {{ index + 1 }}</div>
        <div class="item-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="configData.exchangeConfig.items.length" size="mini" controls-position="right" style="width:100px" />
                <el-button size="mini" type="primary" @click="moveItem('exchangeItems', 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="removeExchangeItem(index)" />
        </div>
        <div class="exchange-body">
          <div class="exchange-image" @click="triggerUpload('exchange', index)">
            <img v-if="item.imageUrl" :src="item.imageUrl" class="preview-img-sq" />
            <div v-else class="upload-placeholder-sm">
              <i class="el-icon-picture"></i>
              <span>未上传</span>
            </div>
            <input :ref="'exchangeUpload' + index" type="file" accept="image/*" style="display:none" @change="onImageUpload($event, 'exchange', index)" />
          </div>
          <el-form label-width="80px" inline class="exchange-fields">
            <el-form-item label="展示文字">
              <el-input v-model="item.title" style="width:200px" @input="markModified" />
            </el-form-item>
            <el-form-item label="跳转链接">
              <el-input v-model="item.link" style="width:280px" @input="markModified" />
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-card>

    <!-- 积分规则弹窗配置 -->
    <el-card class="section-card" shadow="hover">
      <div slot="header" class="section-header">
        <i class="el-icon-document"></i> 积分规则弹窗配置
      </div>
      <el-form label-width="120px">
        <el-form-item label="弹窗顶部名称">
          <el-input v-model="configData.ruleModal.title" style="width:50%" @input="markModified" />
        </el-form-item>
        <el-form-item label="规则内容">
          <quill-editor
            v-model="configData.ruleModal.content"
            :options="quillOptions"
            @change="markModified"
          />
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 获取链接弹窗 -->
    <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="请选择 (无)">
            <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="请选择 (无)">
            <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: 'PageZoneConfig',
  data() {
    return {
      configData: {
        adCarousel: [],
        exchangeConfig: { items: [] },
        ruleModal: { title: '', content: '' }
      },
      availableTags: [],
      pageStatus: 'draft',
      dataLoaded: false,
      sortTarget: 1,
      linkDialogVisible: false,
      linkForm: { campaignId: '', channelId: '' },
      quillOptions: {
        placeholder: '请输入积分规则内容...',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline'],
            [{ list: 'ordered' }, { list: 'bullet' }],
            [{ header: [1, 2, 3, false] }],
            ['link', 'image'],
            ['clean']
          ]
        }
      }
    }
  },
  computed: {
    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/zone${this.linkQueryStr}`
    },
    prodAppUrl() {
      return `hsbc-app://zone${this.linkQueryStr}`
    },
    testUrl() {
      const q = this.linkQueryStr
      return `https://test.hsbc.com/zone${q ? q + '&' : '?'}draft=1`
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    async fetchData() {
      const res = await request.get('/api/page-config/zone')
      this.configData = res.data.config
      this.availableTags = res.data.availableTags
      this.pageStatus = res.data.status
      this.$nextTick(() => { this.dataLoaded = true })
    },
    markModified() {
      if (!this.dataLoaded) return
      if (this.pageStatus === 'published') {
        this.pageStatus = 'modified'
      }
    },
    triggerUpload(type, index) {
      const ref = this.$refs[type + 'Upload' + 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 === 'carousel') {
          this.$set(this.configData.adCarousel[index], 'imageUrl', e.target.result)
        } else {
          this.$set(this.configData.exchangeConfig.items[index], 'imageUrl', e.target.result)
        }
        this.markModified()
      }
      reader.readAsDataURL(file)
      event.target.value = ''
    },
    addCarousel() {
      this.configData.adCarousel.push({
        imageUrl: '', linkH5: '', linkApp: '', wechatAppId: '', wechatPath: '',
        title: '新广告', subtitle: '', tags: []
      })
      this.markModified()
    },
    removeCarousel(index) {
      this.configData.adCarousel.splice(index, 1)
      this.markModified()
    },
    addExchangeItem() {
      this.configData.exchangeConfig.items.push({ imageUrl: '', title: '新兑换项', link: '' })
      this.markModified()
    },
    removeExchangeItem(index) {
      this.configData.exchangeConfig.items.splice(index, 1)
      this.markModified()
    },
    moveItem(type, from, to) {
      const arr = type === 'adCarousel' ? this.configData.adCarousel : this.configData.exchangeConfig.items
      if (to < 0 || to >= arr.length || from === to) return
      const item = arr.splice(from, 1)[0]
      arr.splice(to, 0, item)
      this.markModified()
    },
    async handleSave(type) {
      const status = type === 'publish' ? 'published' : 'draft'
      await request.put('/api/page-config/zone', { config: this.configData, status })
      this.pageStatus = status
      this.$message.success(type === 'publish' ? '已发布权益首页配置！' : '已保存权益首页配置草稿！')
    },
    showLinkDialog() {
      this.linkForm = { campaignId: '', channelId: '' }
      this.linkDialogVisible = true
    },
    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; }

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

.carousel-item, .exchange-item {
  position: relative; border: 1px solid #ebeef5; border-radius: 8px;
  padding: 24px 16px 16px; margin-bottom: 16px; background: #fff;
}
.item-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;
}
.item-actions {
  position: absolute; right: 12px; top: 12px;
  display: flex; gap: 6px;
}

.image-upload-area { display: flex; align-items: center; gap: 16px; }
.upload-box {
  width: 256px; height: 144px;
  background: #eef6fc; border: 1px solid #dcdfe6; border-radius: 4px;
  position: relative; overflow: hidden; cursor: pointer;
  display: flex; align-items: center; justify-content: center; flex-shrink: 0;
}
.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: 24px; margin-bottom: 4px; }
.upload-tip {
  font-size: 12px; color: #909399;
  background: #f5f7fa; padding: 8px 12px; border-radius: 4px; border: 1px solid #ebeef5;
}

.link-config-block {
  background: #f5f7fa; padding: 16px; border-radius: 6px;
  border: 1px solid #ebeef5; margin-top: 8px;
}
.link-config-title {
  font-size: 13px; font-weight: 600; color: #606266;
  border-bottom: 1px solid #ebeef5; padding-bottom: 8px; margin-bottom: 12px;
}

.exchange-body { display: flex; align-items: flex-start; gap: 16px; margin-top: 8px; }
.exchange-image {
  width: 80px; height: 80px; flex-shrink: 0;
  background: #eef6fc; border: 1px solid #dcdfe6; border-radius: 4px;
  display: flex; align-items: center; justify-content: center;
  cursor: pointer; overflow: hidden;
}
.preview-img-sq { 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; }
.exchange-fields { flex: 1; margin-top: 8px; }

.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>
