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

      <el-steps v-if="!isEdit" :active="step" finish-status="success" align-center class="steps">
        <el-step title="基本信息" icon="el-icon-edit-outline" />
        <el-step title="初始人员（可选）" icon="el-icon-user" />
      </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 suffix-icon="el-icon-circle-close" />
              </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">
          每行一个客户号，留空则创建一个空名单。后续可通过列表页"人员调整"或"上传调整文件"补充人员。
        </div>
        <el-input
          v-model="form.initialMembersText"
          type="textarea"
          :rows="8"
          placeholder="示例：&#10;00001&#10;00002&#10;00003"
          style="max-width: 480px"
        />
        <div class="member-stats" v-if="parsedMembers.length > 0">
          已识别 <b>{{ parsedMembers.length }}</b> 个有效客户号
        </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'

const emptyForm = () => ({
  id: '',
  name: '',
  description: '',
  initialMembersText: ''
})

export default {
  name: 'CrowdNameListEdit',
  data() {
    return {
      step: 0,
      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 ? '编辑客群' : '新增客群'
    },
    parsedMembers() {
      const text = this.form.initialMembersText || ''
      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) {
        this.$message.error('客群不存在')
        this.$router.replace('/customization/hsbc/crowd-name-lists')
        return
      }
      if (target.status === 'stopped') {
        this.$message.warning('已停止名单不可编辑')
        this.$router.replace('/customization/hsbc/crowd-name-lists')
        return
      }
      this.current = target
      this.form = {
        id: target.id,
        name: target.name,
        description: target.description,
        initialMembersText: ''
      }
    } else {
      this.form.id = '保存后系统自动生成'
    }
  },
  methods: {
    handleNext() {
      this.$refs.baseForm.validate((ok) => {
        if (ok) this.step = 1
      })
    },
    handleSave() {
      if (this.step === 0 && !this.isEdit) {
        // 不应直接到保存（按钮控制只在 step 1 出现），兜底
        return
      }
      // 编辑路径直接走基本信息保存
      if (this.isEdit) {
        this.$refs.baseForm.validate((ok) => {
          if (!ok) return
          crowdNameListStore.update(this.current.id, {
            name: this.form.name,
            description: this.form.description
          })
          this.$message.success('保存成功')
          this.$router.push('/customization/hsbc/crowd-name-lists')
        })
        return
      }
      // 新增路径
      crowdNameListStore.create({
        name: this.form.name,
        description: this.form.description,
        members: this.parsedMembers
      })
      this.$message.success(this.parsedMembers.length > 0
        ? `创建成功，初始人员 ${this.parsedMembers.length} 人`
        : '创建成功')
      this.$router.push('/customization/hsbc/crowd-name-lists')
    },
    handleCancel() {
      this.$router.push('/customization/hsbc/crowd-name-lists')
    }
  }
}
</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: 8px; }
.member-stats { margin-top: 8px; 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>
