<template>
  <div class="app-container mobile-zhongcao">
    <el-card class="box-card">
      <el-form :model="form" label-position="top" class="main-form">
        <el-form-item label="商品标题" required>
          <el-input
            v-model="form.title"
            type="textarea"
            :rows="3"
            placeholder="必填"
            clearable
          />
        </el-form-item>
        <el-form-item label="型号" required>
          <el-input v-model="form.model" placeholder="必填" clearable />
        </el-form-item>
        <el-form-item label="商品类型" required>
          <el-input
            v-model="form.goodsType"
            placeholder="必填，如：冰箱、空调、洗衣机"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="btn-main" :loading="loading" @click="handleGenerate">
            生成种草文案
          </el-button>
          <el-button :disabled="!hasInput" @click="clearAll">清空</el-button>
        </el-form-item>
      </el-form>

      <el-alert
        v-if="seedNoteError"
        :title="seedNoteError"
        type="warning"
        :closable="false"
        show-icon
        class="warn-alert"
      />

      <div v-if="result.seedNote || result.daixiadan" class="result-wrap">
        <template v-if="result.seedNote">
          <el-divider content-position="left">种草文案（AI）</el-divider>
          <div class="card-bar">
            <span class="card-t">高转化种草</span>
            <el-button type="primary" size="small" @click="copyText(result.seedNote)">复制</el-button>
          </div>
          <div class="result-body">{{ result.seedNote }}</div>
        </template>

        <el-collapse v-if="result.daixiadan" class="extra-collapse">
          <el-collapse-item title="同步生成的闲鱼代下单 / 教你下单（模板拼接）" name="1">
            <div v-if="result.daixiadan" class="sub-block">
              <div class="card-bar">
                <span class="card-t">代下单</span>
                <el-button type="text" size="small" @click="copyText(result.daixiadan)">复制</el-button>
              </div>
              <pre class="pre-text">{{ result.daixiadan }}</pre>
            </div>
            <div v-if="result.jiaonixiadan" class="sub-block">
              <div class="card-bar">
                <span class="card-t">教你下单</span>
                <el-button type="text" size="small" @click="copyText(result.jiaonixiadan)">复制</el-button>
              </div>
              <pre class="pre-text">{{ result.jiaonixiadan }}</pre>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
    </el-card>
  </div>
</template>

<script>
import { generateXianyuWenan } from '@/api/jarvis/socialMedia'

export default {
  name: 'MobileZhongcao',
  data() {
    return {
      form: {
        title: '',
        model: '',
        goodsType: ''
      },
      loading: false,
      seedNoteError: '',
      result: {
        seedNote: '',
        daixiadan: '',
        jiaonixiadan: ''
      }
    }
  },
  computed: {
    hasInput() {
      return !!(this.form.title || this.form.model || this.form.goodsType)
    }
  },
  methods: {
    clearAll() {
      this.form = { title: '', model: '', goodsType: '' }
      this.seedNoteError = ''
      this.result = { seedNote: '', daixiadan: '', jiaonixiadan: '' }
    },
    async handleGenerate() {
      const title = (this.form.title || '').trim()
      const model = (this.form.model || '').trim()
      const goodsType = (this.form.goodsType || '').trim()
      if (!title) {
        this.$message.warning('请填写商品标题')
        return
      }
      if (!model) {
        this.$message.warning('请填写型号')
        return
      }
      if (!goodsType) {
        this.$message.warning('请填写商品类型')
        return
      }
      this.loading = true
      this.seedNoteError = ''
      this.result = { seedNote: '', daixiadan: '', jiaonixiadan: '' }
      try {
        const res = await generateXianyuWenan({
          title,
          remark: model,
          goods_title: title,
          goods_model: model,
          goods_type: goodsType,
          generateSeedNote: true
        })
        if (res.code === 200 && res.data) {
          const data = res.data
          if (data.success) {
            this.result.daixiadan = data.daixiadan || ''
            this.result.jiaonixiadan = data.jiaonixiadan || ''
            this.result.seedNote = (data.seedNote || '').trim()
            if (data.seedNoteError) {
              this.seedNoteError = data.seedNoteError
            }
            if (this.result.seedNote) {
              this.$message.success('种草文案已生成')
            } else if (this.seedNoteError) {
              this.$message.warning('种草失败，已保留闲鱼基础文案')
            } else {
              this.$message.success('已生成')
            }
          } else {
            this.$message.error(data.error || '生成失败')
          }
        } else {
          this.$message.error(res.msg || '请求失败')
        }
      } catch (e) {
        console.error(e)
        this.$message.error('请求异常：' + (e.message || ''))
      } finally {
        this.loading = false
      }
    },
    copyText(text) {
      if (!text) {
        this.$message.warning('无可复制内容')
        return
      }
      if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(text).then(() => {
          this.$message.success('已复制')
        }).catch(() => this.fallbackCopy(text))
      } else {
        this.fallbackCopy(text)
      }
    },
    fallbackCopy(text) {
      const ta = document.createElement('textarea')
      ta.value = text
      ta.style.position = 'fixed'
      ta.style.left = '-9999px'
      document.body.appendChild(ta)
      ta.select()
      try {
        document.execCommand('copy')
        this.$message.success('已复制')
      } catch (err) {
        this.$message.error('复制失败')
      }
      document.body.removeChild(ta)
    }
  }
}
</script>

<style scoped>
.mobile-zhongcao {
  padding-bottom: 16px;
}
.box-card {
  margin: 0 12px;
  max-width: 720px;
  margin-left: auto;
  margin-right: auto;
}
.main-form ::v-deep .el-form-item {
  margin-bottom: 14px;
}
.btn-main {
  margin-right: 8px;
}
.warn-alert {
  margin-bottom: 16px;
}
.result-wrap {
  margin-top: 8px;
}
.card-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}
.card-t {
  font-weight: 600;
  font-size: 14px;
}
.result-body {
  white-space: pre-wrap;
  word-break: break-word;
  font-size: 13px;
  line-height: 1.6;
  padding: 12px;
  background: #f9fafc;
  border-radius: 4px;
  max-height: 420px;
  overflow-y: auto;
}
.extra-collapse {
  margin-top: 16px;
}
.sub-block {
  margin-bottom: 12px;
}
.pre-text {
  white-space: pre-wrap;
  word-break: break-word;
  font-size: 12px;
  margin: 0;
  padding: 8px;
  background: #fafafa;
  border-radius: 4px;
  max-height: 240px;
  overflow-y: auto;
}

@media (max-width: 768px) {
  .box-card {
    margin-left: 8px;
    margin-right: 8px;
  }
  .btn-main {
    width: 100%;
    margin-right: 0;
    margin-bottom: 8px;
  }
}
</style>
