<template>
  <el-dialog
    title="上传调整文件"
    :visible.sync="innerVisible"
    width="640px"
    :close-on-click-modal="false"
    @close="reset"
  >
    <div class="format-block">
      <div class="format-title">文件格式说明</div>
      <div class="format-line">每行一条调整记录，使用 <code>|+|</code> 作为分隔符：</div>
      <pre class="format-sample">客户号|+|客群编号|+|调整方向
00001|+|A0000120251224|+|A
00002|+|A0000120251224|+|D</pre>
      <div class="format-line">调整方向：<code>A</code> = 调增，<code>D</code> = 调减</div>
    </div>

    <el-upload
      class="upload-area"
      drag action="#"
      :auto-upload="false"
      :show-file-list="false"
      :on-change="handleFile"
      accept=".txt,.csv"
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击选择文件</em></div>
      <div slot="tip" class="el-upload__tip">仅支持 .txt / .csv，建议 UTF-8 编码</div>
    </el-upload>

    <div v-if="rawLines.length > 0" class="preview">
      <div class="preview-title">解析预览（共 {{ rawLines.length }} 行，有效 {{ validItems.length }} 行，无效 {{ invalidLines.length }} 行）</div>
      <el-table :data="previewRows" border size="small" max-height="240">
        <el-table-column prop="line" label="行号" width="60" align="center" />
        <el-table-column prop="customerId" label="客户号" width="100" />
        <el-table-column prop="listId" label="客群编号" />
        <el-table-column label="调整方向" width="100">
          <template slot-scope="scope">
            {{ scope.row.direction === 'A' ? '调增-A' : scope.row.direction === 'D' ? '调减-D' : scope.row.direction }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="160">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.error" type="danger" size="small">{{ scope.row.error }}</el-tag>
            <el-tag v-else type="success" size="small">有效</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div v-if="result" class="result-block">
      <el-alert
        :title="`处理完成：成功 ${result.success} 条，失败 ${result.failed} 条`"
        :type="result.failed === 0 ? 'success' : 'warning'"
        :closable="false"
        show-icon
      />
      <div v-if="result.failures.length > 0" class="result-failures">
        <div>失败明细：</div>
        <ul>
          <li v-for="(f, i) in result.failures" :key="i">
            第 {{ f.line }} 行（{{ f.item.customerId }} → {{ f.item.listId }} / {{ f.item.direction }}）：{{ f.reason }}
          </li>
        </ul>
      </div>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button
        type="primary"
        :disabled="validItems.length === 0"
        @click="handleApply"
      >确认上传（{{ validItems.length }} 条）</el-button>
    </div>
  </el-dialog>
</template>

<script>
import crowdNameListStore from '@/store/crowdNameListStore'

export default {
  name: 'UploadAdjustDialog',
  props: {
    visible: { type: Boolean, default: false }
  },
  data() {
    return {
      rawLines: [],
      previewRows: [],
      result: null
    }
  },
  computed: {
    innerVisible: {
      get() { return this.visible },
      set(v) { this.$emit('update:visible', v) }
    },
    validItems() {
      return this.previewRows.filter((r) => !r.error)
    },
    invalidLines() {
      return this.previewRows.filter((r) => r.error)
    }
  },
  watch: {
    visible(v) {
      if (v) this.reset()
    }
  },
  methods: {
    reset() {
      this.rawLines = []
      this.previewRows = []
      this.result = null
    },
    handleFile(file) {
      const reader = new FileReader()
      reader.onload = (e) => {
        const text = e.target.result || ''
        const lines = text.split(/\r?\n/).map((l) => l.trim()).filter((l) => l)
        this.rawLines = lines
        this.parseLines(lines)
      }
      reader.readAsText(file.raw, 'utf-8')
    },
    parseLines(lines) {
      this.previewRows = lines.map((line, idx) => {
        const parts = line.split('|+|')
        if (parts.length !== 3) {
          return { line: idx + 1, raw: line, error: '格式错误（应为3段，使用 |+| 分隔）' }
        }
        const [customerId, listId, direction] = parts.map((s) => s.trim())
        if (!customerId) return { line: idx + 1, customerId, listId, direction, error: '客户号为空' }
        const list = crowdNameListStore.getById(listId)
        if (!list) return { line: idx + 1, customerId, listId, direction, error: '客群编号不存在' }
        if (list.status === 'stopped') return { line: idx + 1, customerId, listId, direction, error: '名单已停止' }
        if (direction !== 'A' && direction !== 'D') {
          return { line: idx + 1, customerId, listId, direction, error: '调整方向只能为 A 或 D' }
        }
        return { line: idx + 1, customerId, listId, direction }
      })
    },
    handleApply() {
      if (this.validItems.length === 0) {
        this.$message.warning('没有有效记录可上传')
        return
      }
      const items = this.validItems.map((r) => ({
        listId: r.listId,
        customerId: r.customerId,
        direction: r.direction
      }))
      this.result = crowdNameListStore.applyBatch(items)
      this.$message.success(`已提交 ${items.length} 条调整，审核通过后生效（demo 默认通过）`)
      this.$emit('applied')
    },
    handleCancel() {
      this.innerVisible = false
    }
  }
}
</script>

<style scoped>
.format-block {
  background: #f5f7fa; border-radius: 4px;
  padding: 12px 16px; margin-bottom: 16px; font-size: 13px;
}
.format-title { font-weight: 600; color: #303133; margin-bottom: 6px; }
.format-line { color: #606266; margin: 4px 0; }
.format-line code { background: #fff; padding: 1px 4px; border-radius: 2px; color: #F56C6C; }
.format-sample {
  background: #fff; padding: 8px 12px; border: 1px solid #ebeef5; border-radius: 2px;
  font-family: 'Menlo', 'Consolas', monospace; font-size: 12px;
  margin: 6px 0; white-space: pre;
}

.upload-area { margin-bottom: 16px; }

.preview { margin-top: 12px; }
.preview-title { font-size: 13px; color: #606266; margin-bottom: 8px; }

.result-block { margin-top: 16px; }
.result-failures {
  margin-top: 8px; font-size: 12px; color: #909399;
  max-height: 120px; overflow-y: auto;
}
.result-failures ul { padding-left: 18px; margin: 4px 0; }

.dialog-footer { text-align: center; }
</style>
