<template>
  <el-dialog
    title="上传调整文件"
    v-model="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|+|A
00002|+|D</pre>
      <div class="format-line">调整方向：<code>A</code> = 调增，<code>D</code> = 调减</div>
      <div v-if="targetListLabel" class="format-line">本次调整目标：<code>{{ targetListLabel }}</code></div>
    </div>

    <el-upload
      class="upload-area"
      drag action="#"
      :auto-upload="false"
      :show-file-list="false"
      :on-change="handleFile"
      accept=".txt,.csv"
    >
      <el-icon><Upload /></el-icon>
      <div class="el-upload__text">将文件拖到此处，或<em>点击选择文件</em></div>
      <template #tip>
        <div class="el-upload__tip">仅支持 .txt / .csv，建议 UTF-8 编码</div>
      </template>
    </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="120" />
        <el-table-column label="调整方向" width="110">
          <template #default="scope">
            {{ scope.row.direction === 'A' ? '调增-A' : scope.row.direction === 'D' ? '调减-D' : scope.row.direction }}
          </template>
        </el-table-column>
        <el-table-column label="状态" min-width="160">
          <template #default="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.direction }}）：{{ f.reason }}
          </li>
        </ul>
      </div>
    </div>

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

<script>
import { ElMessage } from 'element-plus'
import crowdNameListStore from '@/store/crowdNameListStore'

export default {
  name: 'UploadAdjustDialog',
  props: {
    modelValue: { type: Boolean, default: false },
    defaultListId: { type: String, default: '' }
  },
  emits: ['update:modelValue', 'applied'],
  data() {
    return {
      rawLines: [],
      previewRows: [],
      result: null
    }
  },
  computed: {
    innerVisible: {
      get() { return this.modelValue },
      set(v) { this.$emit('update:modelValue', v) }
    },
    validItems() {
      return this.previewRows.filter((r) => !r.error)
    },
    invalidLines() {
      return this.previewRows.filter((r) => r.error)
    },
    targetListLabel() {
      if (!this.defaultListId) return ''
      const l = crowdNameListStore.getById(this.defaultListId)
      return l ? `${l.id}-${l.name}` : this.defaultListId
    }
  },
  watch: {
    modelValue(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) {
      const listId = this.defaultListId
      const list = listId ? crowdNameListStore.getById(listId) : null
      this.previewRows = lines.map((line, idx) => {
        const parts = line.split('|+|')
        if (parts.length !== 2) {
          return { line: idx + 1, raw: line, error: '格式错误（应为2段，使用 |+| 分隔）' }
        }
        const [customerId, direction] = parts.map((s) => s.trim())
        if (!customerId) return { line: idx + 1, customerId, direction, error: '客户号为空' }
        if (!list) return { line: idx + 1, customerId, direction, error: '目标客群不存在' }
        if (list.status === 'stopped') return { line: idx + 1, customerId, direction, error: '名单已停止' }
        if (direction !== 'A' && direction !== 'D') {
          return { line: idx + 1, customerId, direction, error: '调整方向只能为 A 或 D' }
        }
        return { line: idx + 1, customerId, direction }
      })
    },
    handleApply() {
      if (this.validItems.length === 0) {
        ElMessage.warning('没有有效记录可上传')
        return
      }
      const items = this.validItems.map((r) => ({
        listId: this.defaultListId,
        customerId: r.customerId,
        direction: r.direction
      }))
      this.result = crowdNameListStore.applyBatch(items)
      ElMessage.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>
