<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :title="title"
    width="600px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="handleClose"
  >
    <el-form
      ref="projectForm"
      :model="formData"
      :rules="rules"
      label-width="100px"
      label-position="right"
    >
      <!-- 项目名称 -->
      <el-form-item label="项目名称" prop="projectName">
        <el-input
          v-model="formData.projectName"
          placeholder="请输入项目名称"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>

      <!-- 项目描述 -->
      <el-form-item label="项目描述" prop="projectDesc">
        <el-input
          v-model="formData.projectDesc"
          type="textarea"
          :rows="3"
          placeholder="请输入项目描述"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>

      <!-- 目标人员 -->
      <el-form-item label="目标人员">
        <div class="target-persons-wrapper">
          <el-button
            icon="el-icon-plus"
            size="small"
            @click="handleAddPerson"
          >添加人员</el-button>
          <div v-if="formData.targetPersons && formData.targetPersons.length > 0" class="persons-list">
            <el-tag
              v-for="(person, index) in formData.targetPersons"
              :key="index"
              closable
              @close="handleRemovePerson(index)"
              type="info"
            >
              {{ person.name }} ({{ person.certNo }})
            </el-tag>
          </div>
          <div v-else class="empty-hint">
            <i class="el-icon-info"></i>
            <span>暂未添加目标人员，可后续添加</span>
          </div>
        </div>
      </el-form-item>

      <!-- 时间范围 -->
      <el-form-item label="开始日期" prop="startDate">
        <el-date-picker
          v-model="formData.startDate"
          type="date"
          placeholder="选择开始日期"
          value-format="yyyy-MM-dd"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="结束日期" prop="endDate">
        <el-date-picker
          v-model="formData.endDate"
          type="date"
          placeholder="选择结束日期"
          value-format="yyyy-MM-dd"
          :picker-options="endDatePickerOptions"
          style="width: 100%"
        />
      </el-form-item>

      <!-- 目标人数 -->
      <el-form-item label="目标人数" prop="targetCount">
        <el-input-number
          v-model="formData.targetCount"
          :min="0"
          :max="10000"
          :step="10"
          controls-position="right"
          style="width: 100%"
        />
      </el-form-item>
    </el-form>

    <!-- 高级设置（可选扩展） -->
    <el-collapse class="advanced-settings" v-model="activeCollapse">
      <el-collapse-item title="高级设置" name="advanced">
        <el-form label-width="100px" label-position="right">
          <el-form-item label="自动预警">
            <el-switch v-model="formData.autoWarning" />
            <span class="form-item-hint">开启后将自动计算预警人员</span>
          </el-form-item>
          <el-form-item label="预警阈值">
            <el-input-number
              v-model="formData.warningThreshold"
              :min="1"
              :max="100"
              controls-position="right"
            />
            <span class="form-item-hint">匹配度低于此值时触发预警</span>
          </el-form-item>
        </el-form>
      </el-collapse-item>
    </el-collapse>

    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" :loading="submitting" @click="handleSubmit">
        <i v-if="!submitting" class="el-icon-check"></i>
        确 定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'AddProjectDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: '新建项目'
    },
    form: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    // 结束日期验证规则
    const validateEndDate = (rule, value, callback) => {
      if (value && this.formData.startDate && value < this.formData.startDate) {
        callback(new Error('结束日期不能早于开始日期'))
      } else {
        callback()
      }
    }

    return {
      submitting: false,
      activeCollapse: [],
      formData: {
        projectId: null,
        projectName: '',
        projectDesc: '',
        startDate: '',
        endDate: '',
        targetCount: 0,
        targetPersons: [],
        autoWarning: true,
        warningThreshold: 60
      },
      rules: {
        projectName: [
          { required: true, message: '请输入项目名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        startDate: [
          { required: true, message: '请选择开始日期', trigger: 'change' }
        ],
        endDate: [
          { required: true, message: '请选择结束日期', trigger: 'change' },
          { validator: validateEndDate, trigger: 'change' }
        ],
        targetCount: [
          { required: true, message: '请输入目标人数', trigger: 'blur' }
        ]
      },
      endDatePickerOptions: {
        disabledDate: (time) => {
          if (this.formData.startDate) {
            return time.getTime() < new Date(this.formData.startDate).getTime()
          }
          return false
        }
      }
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible
      },
      set(val) {
        if (!val) {
          this.handleClose()
        }
      }
    }
  },
  watch: {
    form: {
      handler(newVal) {
        if (newVal && Object.keys(newVal).length > 0) {
          this.formData = { ...this.formData, ...newVal }
        }
      },
      immediate: true,
      deep: true
    },
    visible(val) {
      if (val) {
        // 对话框打开时重置表单验证状态
        this.$nextTick(() => {
          if (this.$refs.projectForm) {
            this.$refs.projectForm.clearValidate()
          }
        })
      }
    }
  },
  methods: {
    /** 添加人员 */
    handleAddPerson() {
      // 这里可以打开一个选择人员的对话框
      this.$message.info('人员选择功能待实现')
      // 模拟添加人员
      if (!this.formData.targetPersons) {
        this.formData.targetPersons = []
      }
      this.formData.targetPersons.push({
        name: '张三',
        certNo: '3301**********202101'
      })
    },
    /** 移除人员 */
    handleRemovePerson(index) {
      this.formData.targetPersons.splice(index, 1)
    },
    /** 提交表单 */
    handleSubmit() {
      this.$refs.projectForm.validate(valid => {
        if (valid) {
          this.submitting = true
          // 模拟提交
          setTimeout(() => {
            this.submitting = false
            this.$emit('submit', { ...this.formData })
          }, 500)
        }
      })
    },
    /** 关闭对话框 */
    handleClose() {
      this.$emit('close')
      this.$refs.projectForm.resetFields()
      this.formData = {
        projectId: null,
        projectName: '',
        projectDesc: '',
        startDate: '',
        endDate: '',
        targetCount: 0,
        targetPersons: [],
        autoWarning: true,
        warningThreshold: 60
      }
      this.activeCollapse = []
    }
  }
}
</script>

<style lang="scss" scoped>
.target-persons-wrapper {
  width: 100%;

  .persons-list {
    margin-top: 12px;
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }

  .empty-hint {
    margin-top: 12px;
    padding: 12px;
    background-color: #f5f7fa;
    border-radius: 4px;
    color: #909399;
    font-size: 13px;
    display: flex;
    align-items: center;
    gap: 6px;

    i {
      font-size: 14px;
    }
  }
}

.advanced-settings {
  margin: 20px 0;

  :deep(.el-collapse-item__header) {
    font-size: 14px;
    color: #606266;
  }
}

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

.dialog-footer {
  text-align: right;

  .el-button + .el-button {
    margin-left: 8px;
  }
}
</style>
