<template>
  <div class="xianyu-wenan-container">
    <el-card class="box-card">
      <div slot="header">
        <span class="card-title">
          <i class="el-icon-edit-outline"></i>
          闲鱼文案(手动)
        </span>
      </div>

      <div class="input-section">
        <el-form
          :model="form"
          :label-width="labelWidth"
          :label-position="labelPosition"
          class="main-form">
          <el-form-item label="商品标题" required>
            <el-input
              v-model="form.title"
              type="textarea"
              :rows="mobile ? 3 : 2"
              placeholder="请输入商品标题（必填）"
              clearable />
          </el-form-item>
          <el-form-item label="型号/备注">
            <el-input
              v-model="form.remark"
              placeholder="选填，如型号、规格等，会拼在标题后（生成种草时必填）"
              clearable />
          </el-form-item>
          <el-form-item>
            <el-checkbox v-model="form.generateSeedNote">同时生成种草文案（AI）</el-checkbox>
          </el-form-item>
          <el-form-item v-if="form.generateSeedNote" label="商品类型" required>
            <el-input
              v-model="form.goodsType"
              placeholder="种草必填，如：冰箱、空调、洗衣机"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              class="btn-generate"
              :loading="generating"
              @click="handleGenerate">
              生成闲鱼文案
            </el-button>
            <el-button
              class="btn-clear"
              :disabled="!form.title && !form.remark"
              @click="handleClearInput">
              <i class="el-icon-delete"></i> 清空输入
            </el-button>
          </el-form-item>
        </el-form>
      </div>

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

      <div v-if="result.daixiadan || result.jiaonixiadan || result.seedNote" class="result-section">
        <el-row v-if="result.seedNote" :gutter="gutter" class="seed-row">
          <el-col :span="24">
            <el-card shadow="hover" class="result-card">
              <div slot="header" class="result-card-header">
                <span class="result-card-title">种草文案（AI）</span>
                <el-button
                  type="primary"
                  size="small"
                  class="btn-copy"
                  @click="copyResult('seedNote')">
                  <i class="el-icon-document-copy"></i> 复制
                </el-button>
              </div>
              <div class="result-content">{{ result.seedNote }}</div>
            </el-card>
          </el-col>
        </el-row>
        <el-row :gutter="gutter">
          <el-col :xs="24" :sm="24" :md="12">
            <el-card shadow="hover" class="result-card">
              <div slot="header" class="result-card-header">
                <span class="result-card-title">代下单（一键代下）</span>
                <el-button
                  type="primary"
                  size="small"
                  class="btn-copy"
                  @click="copyResult('daixiadan')">
                  <i class="el-icon-document-copy"></i> 复制
                </el-button>
              </div>
              <div class="result-content">{{ result.daixiadan }}</div>
            </el-card>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12">
            <el-card shadow="hover" class="result-card">
              <div slot="header" class="result-card-header">
                <span class="result-card-title">教你下单</span>
                <el-button
                  type="primary"
                  size="small"
                  class="btn-copy"
                  @click="copyResult('jiaonixiadan')">
                  <i class="el-icon-document-copy"></i> 复制
                </el-button>
              </div>
              <div class="result-content">{{ result.jiaonixiadan }}</div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-card>
  </div>
</template>

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

export default {
  name: 'XianyuWenan',
  data() {
    return {
      form: {
        title: '',
        remark: '',
        generateSeedNote: false,
        goodsType: ''
      },
      result: {
        daixiadan: '',
        jiaonixiadan: '',
        seedNote: '',
        seedNoteError: ''
      },
      generating: false,
      mobile: false,
      resizeTimer: null
    }
  },
  computed: {
    labelWidth() {
      return this.mobile ? '80px' : '100px'
    },
    labelPosition() {
      return this.mobile ? 'top' : 'right'
    },
    gutter() {
      return this.mobile ? 12 : 20
    }
  },
  mounted() {
    this.checkMobile()
    window.addEventListener('resize', this.onResize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.onResize)
    if (this.resizeTimer) clearTimeout(this.resizeTimer)
  },
  methods: {
    checkMobile() {
      this.mobile = document.documentElement.clientWidth < 768
    },
    onResize() {
      if (this.resizeTimer) clearTimeout(this.resizeTimer)
      this.resizeTimer = setTimeout(this.checkMobile, 150)
    },
    handleClearInput() {
      this.form.title = ''
      this.form.remark = ''
      this.form.generateSeedNote = false
      this.form.goodsType = ''
      this.$message.success('已清空输入')
    },
    async handleGenerate() {
      const title = (this.form.title || '').trim()
      if (!title) {
        this.$message.warning('请输入商品标题')
        return
      }
      if (this.form.generateSeedNote) {
        const remark = (this.form.remark || '').trim()
        const goodsType = (this.form.goodsType || '').trim()
        if (!remark) {
          this.$message.warning('生成种草时需要填写型号/备注')
          return
        }
        if (!goodsType) {
          this.$message.warning('请填写商品类型')
          return
        }
      }
      this.generating = true
      this.result.seedNote = ''
      this.result.seedNoteError = ''
      try {
        const payload = {
          title: title,
          remark: (this.form.remark || '').trim() || undefined
        }
        if (this.form.generateSeedNote) {
          payload.goods_title = title
          payload.goods_model = (this.form.remark || '').trim()
          payload.goods_type = (this.form.goodsType || '').trim()
          payload.generateSeedNote = true
        }
        const res = await generateXianyuWenan(payload)
        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()
            this.result.seedNoteError = data.seedNoteError || ''
            if (this.result.seedNote) {
              this.$message.success('生成成功')
            } else if (this.result.seedNoteError) {
              this.$message.warning('种草未生成：' + this.result.seedNoteError)
            } else {
              this.$message.success('生成成功')
            }
          } else {
            this.$message.error(data.error || '生成失败')
          }
        } else {
          this.$message.error(res.msg || '生成失败')
        }
      } catch (error) {
        console.error('生成失败', error)
        this.$message.error('生成失败：' + (error.message || '未知错误'))
      } finally {
        this.generating = false
      }
    },
    copyResult(type) {
      const text = this.result[type]
      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 (e) {
        this.$message.error('复制失败，请手动选择复制')
      }
      document.body.removeChild(ta)
    }
  }
}
</script>

<style lang="scss" scoped>
.xianyu-wenan-container {
  padding: 10px;
  box-sizing: border-box;
}
.box-card {
  max-width: 1200px;
  margin: 0 auto;
}
.card-title {
  font-size: 16px;
  font-weight: 500;
}
.input-section {
  margin-bottom: 20px;
}
.result-section {
  margin-top: 20px;
}
.result-card {
  margin-bottom: 16px;
}
.result-card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 8px;
}
.result-card-title {
  font-weight: 500;
  flex: 1;
  min-width: 0;
}
.btn-copy {
  flex-shrink: 0;
}
.result-content {
  white-space: pre-wrap;
  word-break: break-all;
  font-size: 13px;
  line-height: 1.6;
  max-height: 400px;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}
.btn-clear {
  margin-left: 12px;
}
.seed-error-alert {
  margin: 0 0 16px;
}
.seed-row {
  margin-bottom: 8px;
}

/* 移动端适配 */
@media (max-width: 767px) {
  .xianyu-wenan-container {
    padding: 8px;
  }
  .box-card {
    margin: 0 -8px;
    border-radius: 0;
  }
  .box-card ::v-deep .el-card__header {
    padding: 12px 15px;
    font-size: 15px;
  }
  .box-card ::v-deep .el-card__body {
    padding: 12px 15px;
  }
  .card-title {
    font-size: 15px;
  }
  .input-section {
    margin-bottom: 16px;
  }
  .main-form ::v-deep .el-form-item {
    margin-bottom: 14px;
  }
  .main-form ::v-deep .el-form-item__label {
    padding-bottom: 4px;
  }
  .btn-generate {
    width: 100%;
    display: block;
    height: 44px;
    font-size: 15px;
    margin-bottom: 8px;
  }
  .btn-clear {
    width: 100%;
    height: 44px;
    margin-left: 0;
  }
  .result-section {
    margin-top: 16px;
  }
  .result-section ::v-deep .el-row {
    margin-left: -6px !important;
    margin-right: -6px !important;
  }
  .result-section ::v-deep .el-col {
    padding-left: 6px !important;
    padding-right: 6px !important;
  }
  .result-card {
    margin-bottom: 12px;
  }
  .result-card ::v-deep .el-card__header {
    padding: 10px 12px;
  }
  .result-card ::v-deep .el-card__body {
    padding: 10px 12px;
  }
  .result-card-title {
    font-size: 14px;
  }
  .btn-copy {
    min-height: 36px;
    padding: 8px 12px;
  }
  .result-content {
    font-size: 13px;
    max-height: 320px;
    padding: 2px 0;
  }
}
</style>
