<template>
  <el-form 
    ref="alertForm" 
    :model="formData" 
    :rules="rules" 
    :label-width="compact ? '60px' : '100px'" 
    :class="compact ? 'alert-form-compact' : 'alert-form'"
  >
    <el-form-item label="警情摘要" :label="compact ? '摘要' : '警情摘要'" prop="summary">
      <el-input
        v-model="formData.summary"
        type="textarea"
        :rows="compact ? 3 : 4"
        :size="compact ? 'small' : undefined"
        show-word-limit
        maxlength="500"
        :placeholder="compact ? '警情摘要' : '请输入警情摘要'"
      />
    </el-form-item>

    <el-form-item :label="compact ? '渠道' : '来源渠道'" prop="sourceChannel">
      <el-select 
        v-model="formData.sourceChannel" 
        :placeholder="compact ? '来源渠道' : '请选择来源渠道'"
        :size="compact ? 'small' : undefined"
        :style="compact ? 'width: 100%' : undefined"
      >
        <el-option v-for="dict in sourceChannels" :key="dict.value" :label="dict.label" :value="dict.value" />
      </el-select>
    </el-form-item>

    <el-form-item :label="compact ? '来电' : '来电号码'" prop="callerNumber" v-if="isPhoneChannel">
      <el-input 
        v-model="formData.callerNumber" 
        :placeholder="compact ? '来电号码' : '请输入来电号码'"
        :size="compact ? 'small' : undefined"
      />
    </el-form-item>

    <!-- 来源扩展信息（动态表单） -->
    <el-collapse v-if="showSourceExtInfo" v-model="extInfoCollapse" class="source-ext-info-collapse">
      <el-collapse-item title="来源扩展信息" name="extInfo">
        <!-- 转办渠道扩展信息 -->
        <template v-if="isTransferChannel">
          <el-form-item label="转办单位" prop="sourceExtInfo.transferUnit">
            <el-input 
              v-model="formData.sourceExtInfo.transferUnit" 
              :placeholder="compact ? '转办单位' : '请输入转办单位'"
              :size="compact ? 'small' : undefined"
            />
          </el-form-item>
          <el-form-item label="转办人" prop="sourceExtInfo.transferPerson">
            <el-input 
              v-model="formData.sourceExtInfo.transferPerson" 
              :placeholder="compact ? '转办人' : '请输入转办人'"
              :size="compact ? 'small' : undefined"
            />
          </el-form-item>
          <el-form-item label="转办时间" prop="sourceExtInfo.transferTime">
            <el-date-picker
              v-model="formData.sourceExtInfo.transferTime"
              type="datetime"
              :placeholder="compact ? '转办时间' : '选择转办时间'"
              value-format="yyyy-MM-dd HH:mm:ss"
              :size="compact ? 'small' : undefined"
              :style="compact ? 'width: 100%' : undefined"
            />
          </el-form-item>
        </template>

        <!-- 监测渠道扩展信息 -->
        <template v-if="isMonitoringChannel">
          <el-form-item label="设备ID" prop="sourceExtInfo.deviceId">
            <el-input 
              v-model="formData.sourceExtInfo.deviceId" 
              :placeholder="compact ? '设备ID' : '请输入设备ID'"
              :size="compact ? 'small' : undefined"
            />
          </el-form-item>
          <el-form-item label="监测数据" prop="sourceExtInfo.monitoringData">
            <el-input 
              v-model="formData.sourceExtInfo.monitoringData" 
              type="textarea"
              :rows="compact ? 2 : 3"
              :placeholder="compact ? '监测数据' : '请输入监测数据'"
              :size="compact ? 'small' : undefined"
            />
          </el-form-item>
        </template>

        <!-- 媒体渠道扩展信息 -->
        <template v-if="isMediaChannel">
          <el-form-item label="媒体来源" prop="sourceExtInfo.mediaSource">
            <el-input 
              v-model="formData.sourceExtInfo.mediaSource" 
              :placeholder="compact ? '媒体来源' : '请输入媒体来源'"
              :size="compact ? 'small' : undefined"
            />
          </el-form-item>
          <el-form-item label="链接" prop="sourceExtInfo.mediaUrl">
            <el-input 
              v-model="formData.sourceExtInfo.mediaUrl" 
              type="url"
              :placeholder="compact ? '链接' : '请输入链接URL'"
              :size="compact ? 'small' : undefined"
            />
          </el-form-item>
          <el-form-item label="发布时间" prop="sourceExtInfo.publishTime">
            <el-date-picker
              v-model="formData.sourceExtInfo.publishTime"
              type="datetime"
              :placeholder="compact ? '发布时间' : '选择发布时间'"
              value-format="yyyy-MM-dd HH:mm:ss"
              :size="compact ? 'small' : undefined"
              :style="compact ? 'width: 100%' : undefined"
            />
          </el-form-item>
        </template>
      </el-collapse-item>
    </el-collapse>

    <el-form-item :label="compact ? '等级' : '初判等级'" prop="initialLevel">
      <el-select 
        v-model="formData.initialLevel" 
        :placeholder="compact ? '初判等级' : '请选择初判等级'"
        :size="compact ? 'small' : undefined"
        :style="compact ? 'width: 100%' : undefined"
      >
        <el-option v-for="dict in alertLevels" :key="dict.value" :label="dict.label" :value="dict.value" />
      </el-select>
    </el-form-item>

    <el-form-item :label="compact ? '时间' : '发生时间'" prop="occurredAt">
      <el-date-picker
        v-model="formData.occurredAt"
        type="datetime"
        :placeholder="compact ? '发生时间' : '选择发生时间'"
        value-format="yyyy-MM-dd HH:mm:ss"
        :size="compact ? 'small' : undefined"
        :style="compact ? 'width: 100%' : undefined"
      />
    </el-form-item>

    <el-form-item :label="compact ? '地点' : '发生地点'" prop="location">
      <el-input 
        v-model="formData.location" 
        :placeholder="compact ? '请选择发生地点' : '请选择发生地点'"
        readonly
        :size="compact ? 'small' : undefined"
        style="cursor: pointer"
        @click="$emit('open-location-picker')"
      >
        <el-button 
          slot="append" 
          icon="el-icon-map-location" 
          :size="compact ? 'small' : undefined"
          @click.stop="$emit('open-location-picker')"
        >
          {{ compact ? '选择' : '选择位置' }}
        </el-button>
      </el-input>
    </el-form-item>

    <el-form-item label="备注" prop="remark">
      <el-input 
        v-model="formData.remark" 
        type="textarea" 
        :rows="2" 
        :placeholder="compact ? '备注' : '其他补充说明'"
        :size="compact ? 'small' : undefined"
      />
    </el-form-item>

    <el-form-item>
      <el-button 
        v-if="isDraftStatus" 
        :type="compact ? 'default' : 'default'"
        :size="compact ? 'small' : undefined"
        :class="compact ? 'form-action-btn' : undefined"
        @click="$emit('save-draft')"
        :loading="submitting"
      >
        保存草稿
      </el-button>
      <el-button 
        v-if="isDraftStatus" 
        type="primary" 
        :size="compact ? 'small' : undefined"
        :class="compact ? 'form-action-btn' : undefined"
        @click="$emit('submit')"
        :loading="submitting"
      >
        提交
      </el-button>
      <el-button 
        v-if="!isDraftStatus" 
        type="primary" 
        :size="compact ? 'small' : undefined"
        :class="compact ? 'form-action-btn' : undefined"
        @click="$emit('update')"
        :loading="submitting"
      >
        更新
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  name: 'AlertForm',
  props: {
    formData: {
      type: Object,
      required: true,
      default: () => ({
        summary: '',
        sourceChannel: undefined,
        callerNumber: '',
        initialLevel: undefined,
        occurredAt: '',
        location: '',
        remark: '',
        sourceExtInfo: {} // 来源扩展信息（JSON对象）
      })
    },
    sourceChannels: {
      type: Array,
      required: true,
      default: () => []
    },
    alertLevels: {
      type: Array,
      required: true,
      default: () => []
    },
    editingAlertId: {
      type: [Number, String, null],
      default: null
    },
    editingAlertStatus: {
      type: String,
      default: null
    },
    submitting: {
      type: Boolean,
      default: false
    },
    compact: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      extInfoCollapse: [] // 控制扩展信息折叠面板的展开状态
    }
  },
  computed: {
    rules() {
      return {
        summary: [{ required: true, message: '请填写警情摘要', trigger: 'blur' }],
        sourceChannel: [{ required: true, message: '请选择来源渠道', trigger: 'change' }],
        initialLevel: [{ required: true, message: '请选择初判等级', trigger: 'change' }],
        occurredAt: [{ required: true, message: '请选择发生时间', trigger: 'change' }],
        location: [{ required: true, message: '请填写发生地点', trigger: 'blur' }]
      }
    },
    isPhoneChannel() {
      return ['phone_122', 'phone_12345', 'phone_110'].includes(this.formData.sourceChannel)
    },
    isTransferChannel() {
      return this.formData.sourceChannel === 'transfer'
    },
    isMonitoringChannel() {
      return this.formData.sourceChannel === 'monitoring'
    },
    isMediaChannel() {
      return this.formData.sourceChannel === 'media'
    },
    showSourceExtInfo() {
      return this.isTransferChannel || this.isMonitoringChannel || this.isMediaChannel
    },
    isDraftStatus() {
      return !this.editingAlertId || this.editingAlertStatus === 'draft'
    }
  },
  watch: {
    'formData.sourceChannel'(newVal, oldVal) {
      // 当来源渠道改变时，重置扩展信息
      if (newVal !== oldVal) {
        this.resetSourceExtInfo()
        // 如果切换到需要扩展信息的渠道，自动展开折叠面板
        if (this.showSourceExtInfo) {
          this.extInfoCollapse = ['extInfo']
        } else {
          this.extInfoCollapse = []
        }
      } else {
        // 如果渠道没有改变，但需要显示扩展信息且有数据，也展开（编辑模式）
        this.checkAndExpandExtInfo()
      }
    },
    // 监听编辑模式变化，当进入编辑模式且有扩展信息时自动展开
    editingAlertId(newVal) {
      if (newVal) {
        this.$nextTick(() => {
          this.checkAndExpandExtInfo()
        })
      }
    },
    // 监听扩展信息数据变化，当有数据时自动展开
    'formData.sourceExtInfo': {
      handler() {
        if (this.showSourceExtInfo) {
          this.$nextTick(() => {
            this.checkAndExpandExtInfo()
          })
        }
      },
      deep: true
    }
  },
  methods: {
    validate() {
      return this.$refs.alertForm.validate()
    },
    resetFields() {
      this.$refs.alertForm.resetFields()
      this.resetSourceExtInfo()
    },
    resetSourceExtInfo() {
      // 重置扩展信息对象
      if (!this.formData.sourceExtInfo) {
        this.$set(this.formData, 'sourceExtInfo', {})
      }
      
      if (this.isTransferChannel) {
        this.$set(this.formData.sourceExtInfo, 'transferUnit', '')
        this.$set(this.formData.sourceExtInfo, 'transferPerson', '')
        this.$set(this.formData.sourceExtInfo, 'transferTime', '')
      } else if (this.isMonitoringChannel) {
        this.$set(this.formData.sourceExtInfo, 'deviceId', '')
        this.$set(this.formData.sourceExtInfo, 'monitoringData', '')
      } else if (this.isMediaChannel) {
        this.$set(this.formData.sourceExtInfo, 'mediaSource', '')
        this.$set(this.formData.sourceExtInfo, 'mediaUrl', '')
        this.$set(this.formData.sourceExtInfo, 'publishTime', '')
      }
    },
    /**
     * 检查并展开扩展信息面板（编辑模式时使用）
     */
    checkAndExpandExtInfo() {
      if (this.showSourceExtInfo) {
        const hasExtInfo = this.formData.sourceExtInfo && 
          Object.keys(this.formData.sourceExtInfo).length > 0 &&
          Object.values(this.formData.sourceExtInfo).some(val => val !== null && val !== undefined && val !== '')
        
        if (hasExtInfo && !this.extInfoCollapse.includes('extInfo')) {
          this.$nextTick(() => {
            this.extInfoCollapse = ['extInfo']
          })
        }
      }
    }
  },
  mounted() {
    // 初始化扩展信息对象
    if (!this.formData.sourceExtInfo) {
      this.$set(this.formData, 'sourceExtInfo', {})
    }
    // 检查是否需要展开扩展信息面板（编辑模式）
    this.$nextTick(() => {
      this.checkAndExpandExtInfo()
    })
  }
}
</script>

<style lang="scss" scoped>
.alert-form-compact {
  padding: 0;
  
  .el-form-item {
    margin-bottom: 18px;
  }
  
  .el-form-item__label {
    font-size: 13px;
    font-weight: 500;
    color: #606266;
    padding: 0 0 6px 0;
    line-height: 1.5;
    text-align: left;
  }
  
  .el-form-item__content {
    line-height: 1.5;
  }
  
  .el-input,
  .el-select,
  .el-date-picker,
  .el-textarea {
    width: 100%;
  }
  
  .el-input__inner,
  .el-textarea__inner {
    font-size: 13px;
  }
  
  .el-button {
    font-size: 13px;
  }
  
  .form-action-btn {
    width: 100%;
    margin-bottom: 8px;
    height: 32px;
    padding: 0;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
}

.source-ext-info-collapse {
  margin-bottom: 18px;
  
  ::v-deep .el-collapse-item__header {
    font-weight: 500;
    color: #606266;
  }
  
  ::v-deep .el-collapse-item__content {
    padding: 16px 0 0 0;
  }
}
</style>