<template>
  <div class="crowd-name-list-edit">
    <el-card>
      <template #header>
        <div class="header">
          <span class="title">{{ pageTitle }}</span>
        </div>
      </template>

      <el-steps v-if="!isEdit" :active="step" finish-status="success" align-center class="steps">
        <el-step title="基本信息">
          <template #icon><el-icon><EditPen /></el-icon></template>
        </el-step>
        <el-step title="初始人员">
          <template #icon><el-icon><User /></el-icon></template>
        </el-step>
      </el-steps>

      <!-- Step 1: 基本信息 -->
      <div v-show="step === 0" class="section">
        <div class="section-title">基本信息</div>
        <el-form
          ref="baseForm"
          :model="form"
          :rules="rules"
          label-width="120px"
          style="max-width: 1000px; margin: 0 auto"
        >
          <el-row :gutter="32">
            <el-col :span="12">
              <el-form-item label="客群名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入" maxlength="40" show-word-limit />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客群编号">
                <el-input v-model="form.id" disabled>
                  <template #suffix><el-icon><CircleClose /></el-icon></template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="客群描述" prop="description">
                <el-input
                  v-model="form.description"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入"
                  maxlength="200"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- Step 2: 初始人员（仅新增可见） -->
      <div v-show="step === 1 && !isEdit" class="section">
        <div class="section-title">初始人员</div>
        <div class="hint">至少添加 1 个客户号；可选择手动输入或上传文件。</div>

        <div class="mode-switch">
          <el-radio-group v-model="inputMode">
            <el-radio-button label="manual">手动输入</el-radio-button>
            <el-radio-button label="file">上传文件</el-radio-button>
          </el-radio-group>
        </div>

        <div class="mode-content">
          <el-input
            v-if="inputMode === 'manual'"
            v-model="form.manualText"
            type="textarea"
            :rows="8"
            :placeholder="manualPlaceholder"
          />

          <el-upload
            v-else
            drag
            action="#"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleFile"
            accept=".txt,.csv"
          >
            <el-icon class="el-icon--upload"><Upload /></el-icon>
            <div class="el-upload__text">将文件拖到此处，或<em>点击选择文件</em></div>
            <template #tip>
              <div class="el-upload__tip">
                仅支持 .txt / .csv，每行一个客户号，UTF-8 编码
                <span v-if="form.fileName" class="file-name">已选择：{{ form.fileName }}</span>
              </div>
            </template>
          </el-upload>

          <div class="member-stats" v-if="parsedMembers.length > 0">
            已识别 <b>{{ parsedMembers.length }}</b> 个有效客户号
          </div>
        </div>
      </div>

      <div class="footer">
        <el-button v-if="step === 0" @click="handleCancel">取消</el-button>
        <el-button v-if="step === 1" @click="step = 0">上一步</el-button>
        <el-button v-if="!isEdit && step === 0" type="primary" @click="handleNext">下一步</el-button>
        <el-button v-if="isEdit && step === 0" type="primary" @click="handleSave">保存</el-button>
        <el-button v-if="step === 1" type="primary" @click="handleSave">完成</el-button>
      </div>
    </el-card>
  </div>
</template>

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

const emptyForm = () => ({
  id: '',
  name: '',
  description: '',
  manualText: '',
  fileMembers: [],
  fileName: ''
})

export default {
  name: 'CrowdNameListEdit',
  data() {
    return {
      step: 0,
      inputMode: 'manual',
      form: emptyForm(),
      current: null,
      rules: {
        name: [{ required: true, message: '请输入客群名称', trigger: 'blur' }],
        description: [{ required: true, message: '请输入客群描述', trigger: 'blur' }]
      }
    }
  },
  computed: {
    isEdit() {
      return !!this.$route.params.id
    },
    pageTitle() {
      return this.isEdit ? '编辑客群' : '新增客群'
    },
    manualPlaceholder() {
      return '示例：\n00001\n00002\n00003'
    },
    parsedMembers() {
      if (this.inputMode === 'file') return this.form.fileMembers
      const text = this.form.manualText || ''
      const seen = new Set()
      const out = []
      text.split(/\r?\n/).forEach((l) => {
        const v = l.trim()
        if (v && !seen.has(v)) {
          seen.add(v)
          out.push(v)
        }
      })
      return out
    }
  },
  created() {
    if (this.isEdit) {
      const target = crowdNameListStore.getById(this.$route.params.id)
      if (!target) {
        ElMessage.error('客群不存在')
        this.$router.replace('/customization/hsbc/crowd-tasks')
        return
      }
      if (target.status === 'stopped') {
        ElMessage.warning('已停止名单不可编辑')
        this.$router.replace('/customization/hsbc/crowd-tasks')
        return
      }
      this.current = target
      this.form = {
        id: target.id,
        name: target.name,
        description: target.description,
        manualText: '',
        fileMembers: [],
        fileName: ''
      }
    } else {
      this.form.id = '保存后系统自动生成'
    }
  },
  methods: {
    handleNext() {
      this.$refs.baseForm.validate((ok) => {
        if (ok) this.step = 1
      })
    },
    handleFile(file) {
      const reader = new FileReader()
      reader.onload = (e) => {
        const text = e.target.result || ''
        const seen = new Set()
        const out = []
        text.split(/\r?\n/).forEach((l) => {
          const v = l.trim()
          if (v && !seen.has(v)) {
            seen.add(v)
            out.push(v)
          }
        })
        this.form.fileMembers = out
        this.form.fileName = file.name
        if (out.length === 0) {
          ElMessage.warning('文件未解析出有效客户号')
        } else {
          ElMessage.success(`已解析 ${out.length} 个有效客户号`)
        }
      }
      reader.readAsText(file.raw, 'utf-8')
    },
    handleSave() {
      if (this.isEdit) {
        this.$refs.baseForm.validate((ok) => {
          if (!ok) return
          crowdNameListStore.update(this.current.id, {
            name: this.form.name,
            description: this.form.description
          })
          ElMessage.success('保存成功')
          this.$router.push('/customization/hsbc/crowd-tasks')
        })
        return
      }
      // 新增路径
      if (this.parsedMembers.length === 0) {
        ElMessage.error(
          this.inputMode === 'file' ? '请上传文件并确认包含至少 1 个有效客户号' : '请至少输入 1 个客户号'
        )
        return
      }
      crowdNameListStore.create({
        name: this.form.name,
        description: this.form.description,
        members: this.parsedMembers
      })
      ElMessage.success(`创建成功，初始人员 ${this.parsedMembers.length} 人`)
      this.$router.push('/customization/hsbc/crowd-tasks')
    },
    handleCancel() {
      this.$router.push('/customization/hsbc/crowd-tasks')
    }
  }
}
</script>

<style scoped>
.crowd-name-list-edit { padding: 0; }
.header { display: flex; align-items: center; justify-content: center; }
.title { font-size: 16px; font-weight: 600; color: #409EFF; }

.steps { margin: 16px 0 32px; }

.section { margin-bottom: 24px; max-width: 1000px; margin-left: auto; margin-right: auto; }
.section-title {
  font-size: 14px; font-weight: 600; color: #303133;
  background: #f5f7fa; padding: 10px 14px; border-radius: 4px;
  margin-bottom: 16px;
}
.hint { color: #909399; font-size: 12px; margin-bottom: 12px; }
.mode-switch { margin-bottom: 16px; }
.mode-content { max-width: 480px; }
.mode-content >>> .el-textarea__inner { font-family: 'Menlo', 'Consolas', monospace; }
.file-name { margin-left: 10px; color: #67C23A; }
.member-stats { margin-top: 12px; color: #67C23A; font-size: 13px; }

.footer { text-align: center; margin-top: 24px; padding-top: 16px; border-top: 1px solid #ebeef5; }
.footer .el-button { min-width: 100px; }
</style>
