<template>
  <div v-if="visible">
    <div class="step-form-dialog" @click.stop>
      <div class="step-form-dialog-header">
        <span class="step-form-dialog-title">{{ isEdit ? '编辑行动项' : '添加行动项' }}</span>
        <el-button 
          type="text" 
          icon="el-icon-close" 
          size="mini"
          @click="handleClose"
          class="step-form-dialog-close"
        ></el-button>
      </div>
      
      <div class="step-form-dialog-body">
        <el-form 
          ref="stepForm" 
          :model="formData" 
          :rules="rules" 
          label-width="100px"
        >
          <el-form-item label="行动项标题" prop="title">
            <el-input 
              v-model="formData.title" 
              placeholder="请输入行动项标题（可选）"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
          
          <el-form-item label="行动项描述" prop="description">
            <el-input 
              v-model="formData.description" 
              type="textarea"
              :rows="4"
              placeholder="请输入行动项描述"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="执行顺序" prop="stepOrder">
            <el-input-number 
              v-model="formData.stepOrder" 
              :min="1"
              :max="999"
              placeholder="执行顺序"
              style="width: 100%"
            />
            <div class="form-item-hint">数字越小越先执行</div>
          </el-form-item>

          <el-form-item label="分配执行人" prop="executorId">
            <el-select 
              v-model="formData.executorId" 
              placeholder="请选择执行人（可选）"
              clearable
              filterable
              style="width: 100%"
            >
              <el-option
                v-for="participant in participants"
                :key="participant.id"
                :label="getParticipantLabel(participant)"
                :value="participant.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      
      <div class="step-form-dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button 
          type="primary" 
          :loading="submitting"
          @click="handleSubmit"
        >
          {{ isEdit ? '保存' : '添加' }}
        </el-button>
      </div>
    </div>
    
    <div class="step-form-dialog-backdrop" @click="handleClose"></div>
  </div>
</template>

<script>
export default {
  name: 'StepFormDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    stepData: {
      type: Object,
      default: null
    },
    participants: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      formData: {
        title: '',
        description: '',
        stepOrder: 1,
        executorId: null
      },
      rules: {
        description: [
          { required: true, message: '请输入行动项描述', trigger: 'blur' },
          { max: 500, message: '描述不能超过500个字符', trigger: 'blur' }
        ],
        stepOrder: [
          { required: true, message: '请输入执行顺序', trigger: 'blur' },
          { type: 'number', min: 1, max: 999, message: '执行顺序必须在1-999之间', trigger: 'blur' }
        ]
      },
      submitting: false
    }
  },
  computed: {
    isEdit() {
      return this.stepData && this.stepData.id
    }
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.resetForm()
        if (this.isEdit) {
          this.loadStepData()
        }
      }
    },
    stepData: {
      immediate: true,
      handler() {
        if (this.visible && this.isEdit) {
          this.loadStepData()
        }
      }
    }
  },
  methods: {
    resetForm() {
      this.formData = {
        title: '',
        description: '',
        stepOrder: 1,
        executorId: null
      }
      this.$nextTick(() => {
        if (this.$refs.stepForm) {
          this.$refs.stepForm.resetFields()
        }
      })
    },
    loadStepData() {
      if (this.stepData) {
        this.formData = {
          title: this.stepData.title || '',
          description: this.stepData.description || '',
          stepOrder: this.stepData.stepOrder || 1,
          executorId: this.stepData.executorId || null
        }
      }
    },
    getParticipantLabel(participant) {
      try {
        const snapshot = typeof participant.personSnapshot === 'string' 
          ? JSON.parse(participant.personSnapshot) 
          : participant.personSnapshot
        const name = snapshot?.name || snapshot?.personName || '-'
        const teamName = snapshot?.teamName || '-'
        const role = snapshot?.role || snapshot?.position || '-'
        return `${name} (${teamName} - ${role})`
      } catch (e) {
        return `参与者 #${participant.id}`
      }
    },
    getParticipantPersonId(participant) {
      return participant.personId || participant.id
    },
    handleClose() {
      if (!this.submitting) {
        this.$emit('update:visible', false)
        this.$emit('close')
      }
    },
    handleSubmit() {
      this.$refs.stepForm.validate((valid) => {
        if (valid) {
          this.submitting = true
          const stepData = {
            title: this.formData.title.trim() || null,
            description: this.formData.description.trim(),
            stepOrder: this.formData.stepOrder || 1,
            executorId: this.formData.executorId || null
          }
          
          // If editing, include the ID
          if (this.isEdit) {
            stepData.id = this.stepData.id
          }
          
          this.$emit('submit', stepData)
          this.submitting = false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.step-form-dialog {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 500px;
  max-height: 80vh;
  background: white;
  border-radius: 8px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
  z-index: 2001;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.step-form-dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #ebeef5;
  background: #f5f7fa;
  flex-shrink: 0;
}

.step-form-dialog-title {
  font-weight: 600;
  font-size: 16px;
  color: #303133;
}

.step-form-dialog-close {
  padding: 0;
  color: #909399;
}

.step-form-dialog-body {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.form-item-hint {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.step-form-dialog-footer {
  padding: 12px 16px;
  border-top: 1px solid #ebeef5;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  flex-shrink: 0;
}

.step-form-dialog-backdrop {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 2000;
  background: rgba(0, 0, 0, 0.3);
}
</style>


