<template>
  <el-dialog
    :visible.sync="innerVisible"
    :title="dialogTitle"
    width="720px"
    append-to-body
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="reportForm"
      :model="form"
      :rules="rules"
      label-width="110px"
      size="small"
    >
      <el-card class="dialog-section" shadow="never">
        <div slot="header" class="section-title">
          <span>事件信息</span>
        </div>
        <el-row :gutter="16">
          <el-col :span="12">
            <p class="event-field"><strong>事件编号：</strong>{{ (eventInfo && eventInfo.eventCode) || '-' }}</p>
          </el-col>
          <el-col :span="12">
            <p class="event-field"><strong>事件标题：</strong>{{ (eventInfo && eventInfo.eventTitle) || '-' }}</p>
          </el-col>
          <el-col :span="12">
            <p class="event-field"><strong>事件级别：</strong>{{ getEventLevelLabel(eventInfo && eventInfo.eventLevel) || '-' }}</p>
          </el-col>
          <el-col :span="12">
            <p class="event-field"><strong>最新状态：</strong>{{ (eventInfo && eventInfo.statusLabel) || '-' }}</p>
          </el-col>
        </el-row>
      </el-card>

      <el-card class="dialog-section" shadow="never">
        <div slot="header" class="section-title">
          <span>上报内容</span>
        </div>
        <el-form-item label="上报模板" prop="templateId">
          <el-select
            v-model="form.templateId"
            placeholder="请选择上报模板"
            filterable
            style="width: 100%"
            @change="handleTemplateChange"
          >
            <el-option
              v-for="tpl in templateOptions"
              :key="tpl.id"
              :label="tpl.name"
              :value="tpl.id"
            />
          </el-select>
        </el-form-item>

        <template v-if="dynamicFields.length">
          <div v-for="(field, index) in dynamicFields" :key="field.code || field.label || ('field-' + index)">
            <!-- Group field: render header and children -->
            <template v-if="field.type === 'group'">
              <el-divider content-position="left">{{ field.label }}</el-divider>
              <el-form-item
                v-for="childField in field.children || []"
                :key="childField.code"
                :prop="'fields.' + childField.code"
                :rules="generateFieldRules(childField)"
                :label="childField.label"
              >
                <el-select
                  v-if="childField.type === 'select'"
                  v-model="form.fields[childField.code]"
                  filterable
                  clearable
                  style="width: 100%"
                  :placeholder="childField.placeholder || ('请选择' + childField.label)"
                >
                  <el-option
                    v-for="option in childField.options || []"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  />
                </el-select>
                <el-date-picker
                  v-else-if="childField.type === 'date'"
                  v-model="form.fields[childField.code]"
                  style="width: 100%"
                  :type="childField.dateType || 'date'"
                  :value-format="childField.format || 'yyyy-MM-dd'"
                  :placeholder="childField.placeholder || ('请选择' + childField.label)"
                />
                <el-input-number
                  v-else-if="childField.type === 'number'"
                  v-model="form.fields[childField.code]"
                  :min="childField.min !== undefined ? childField.min : 0"
                  :max="childField.max !== undefined ? childField.max : 999999"
                  :precision="childField.precision !== undefined ? childField.precision : 0"
                  style="width: 100%"
                />
                <el-input
                  v-else
                  v-model="form.fields[childField.code]"
                  :type="childField.type === 'textarea' ? 'textarea' : 'text'"
                  :rows="childField.type === 'textarea' ? 3 : 1"
                  :maxlength="childField.maxLength || 200"
                  show-word-limit
                  :placeholder="childField.placeholder || ('请输入' + childField.label)"
                />
              </el-form-item>
            </template>
            
            <!-- List field: render as table -->
            <el-form-item
              v-else-if="field.type === 'list'"
              :label="field.label"
            >
              <el-table
                :data="getListData(field)"
                border
                size="small"
                style="width: 100%"
              >
                <el-table-column
                  v-for="colField in field.children || []"
                  :key="colField.code"
                  :prop="colField.code"
                  :label="colField.label"
                  min-width="120"
                >
                  <template slot-scope="scope">
                    <el-select
                      v-if="colField.type === 'select'"
                      v-model="scope.row[colField.code]"
                      filterable
                      clearable
                      size="mini"
                      style="width: 100%"
                    >
                      <el-option
                        v-for="option in colField.options || []"
                        :key="option.value"
                        :label="option.label"
                        :value="option.value"
                      />
                    </el-select>
                    <el-date-picker
                      v-else-if="colField.type === 'date'"
                      v-model="scope.row[colField.code]"
                      size="mini"
                      style="width: 100%"
                      :type="colField.dateType || 'date'"
                      :value-format="colField.format || 'yyyy-MM-dd'"
                    />
                    <el-input-number
                      v-else-if="colField.type === 'number'"
                      v-model="scope.row[colField.code]"
                      size="mini"
                      style="width: 100%"
                      :min="colField.min !== undefined ? colField.min : 0"
                      :max="colField.max !== undefined ? colField.max : 999999"
                    />
                    <el-input
                      v-else
                      v-model="scope.row[colField.code]"
                      size="mini"
                      :type="colField.type === 'textarea' ? 'textarea' : 'text'"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="80" fixed="right">
                  <template slot-scope="scope">
                    <el-button
                      type="text"
                      size="mini"
                      icon="el-icon-delete"
                      @click="removeListRow(field, scope.$index)"
                    />
                  </template>
                </el-table-column>
              </el-table>
              <el-button
                type="text"
                icon="el-icon-plus"
                size="mini"
                style="margin-top: 8px"
                @click="addListRow(field)"
              >
                添加行
              </el-button>
            </el-form-item>
            
            <!-- Regular fields -->
          <el-form-item
              v-else
            :prop="'fields.' + field.code"
            :rules="generateFieldRules(field)"
            :label="field.label"
          >
            <el-select
              v-if="field.type === 'select'"
              v-model="form.fields[field.code]"
              filterable
              clearable
              style="width: 100%"
              :placeholder="field.placeholder || ('请选择' + field.label)"
            >
              <el-option
                v-for="option in field.options || []"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
            <el-date-picker
              v-else-if="field.type === 'date'"
              v-model="form.fields[field.code]"
              style="width: 100%"
              :type="field.dateType || 'date'"
              :value-format="field.format || 'yyyy-MM-dd'"
              :placeholder="field.placeholder || ('请选择' + field.label)"
            />
            <el-input-number
              v-else-if="field.type === 'number'"
              v-model="form.fields[field.code]"
              :min="field.min !== undefined ? field.min : 0"
              :max="field.max !== undefined ? field.max : 999999"
              :precision="field.precision !== undefined ? field.precision : 0"
              style="width: 100%"
            />
            <el-input
              v-else
              v-model="form.fields[field.code]"
              :type="field.type === 'textarea' ? 'textarea' : 'text'"
              :rows="field.type === 'textarea' ? 3 : 1"
              :maxlength="field.maxLength || 200"
              show-word-limit
              :placeholder="field.placeholder || ('请输入' + field.label)"
            />
          </el-form-item>
          </div>
        </template>
        <el-alert
          v-else
          type="info"
          :closable="false"
          title="请选择模板以生成报送字段"
        />
        <el-form-item label="备注">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            maxlength="300"
            show-word-limit
            placeholder="可选：填写补充说明"
          />
        </el-form-item>
      </el-card>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" :loading="submitting" @click="submit">
        {{ (eventInfo && eventInfo.hasProvinceReports) ? '续 报' : '提 交' }}
      </el-button>
    </span>
  </el-dialog>
</template>

<script>
import { toTemplateFieldArray } from '@/utils/reportTemplateFields'
import { submitProvinceReport } from '@/api/emergency/provinceReport'
import { getLevelLabel, getLevelTagType } from '@/views/duty/alert/utils/alertFormatters'

export default {
  name: 'ProvinceReportDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    eventInfo: {
      type: Object,
      default: null
    },
    templateOptions: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      innerVisible: false,
      submitting: false,
      dynamicFields: [],
      form: {
        templateId: undefined,
        fields: {},
        remark: ''
      },
      rules: {
        templateId: [{ required: true, message: '请选择上报模板', trigger: 'change' }]
      }
    }
  },
  computed: {
    dialogTitle() {
      const isFollowup = this.eventInfo && this.eventInfo.hasProvinceReports
      if (this.eventInfo && this.eventInfo.eventTitle) {
        const prefix = isFollowup ? '省厅续报：' : '省厅上报：'
        return prefix + this.eventInfo.eventTitle
      }
      return isFollowup ? '省厅续报' : '省厅上报'
    }
  },
  watch: {
    visible(val) {
      this.innerVisible = val
      if (val) {
        this.initForm()
      }
    }
  },
  methods: {
    initForm() {
      this.$refs.reportForm && this.$refs.reportForm.resetFields()
      this.form = {
        templateId: undefined,
        fields: {},
        remark: ''
      }
      this.dynamicFields = []
    },
    handleTemplateChange(templateId) {
      const tpl = this.templateOptions.find(item => item.id === templateId)
      if (!tpl) {
        this.dynamicFields = []
        this.form.fields = {}
        return
      }
      this.dynamicFields = toTemplateFieldArray(tpl.fields)
      const nextFields = {}
      
      // Recursively initialize field values
      const initializeFields = (fields) => {
        fields.forEach(field => {
          if (field.type === 'group' && field.children) {
            initializeFields(field.children)
          } else if (field.type === 'list') {
            // Initialize list as empty array
            if (field.code) {
              nextFields[field.code] = []
            }
          } else if (field.code) {
        nextFields[field.code] = field.defaultValue !== undefined ? field.defaultValue : ''
          }
      })
      }
      
      initializeFields(this.dynamicFields)
      this.form.fields = nextFields
    },
    getListData(field) {
      // Get or initialize list data for this field
      if (!field.code) return []
      if (!this.form.fields[field.code]) {
        this.$set(this.form.fields, field.code, [])
      }
      return this.form.fields[field.code]
    },
    addListRow(field) {
      if (!field.code) return
      if (!this.form.fields[field.code]) {
        this.$set(this.form.fields, field.code, [])
      }
      const newRow = {}
      if (field.children) {
        field.children.forEach(colField => {
          if (colField.code) {
            newRow[colField.code] = colField.defaultValue !== undefined ? colField.defaultValue : ''
          }
        })
      }
      this.form.fields[field.code].push(newRow)
    },
    removeListRow(field, index) {
      if (field.code && this.form.fields[field.code]) {
        this.form.fields[field.code].splice(index, 1)
      }
    },
    generateFieldRules(field) {
      const rules = []
      if (field.required) {
        rules.push({ required: true, message: field.label + '为必填项', trigger: 'blur' })
      }
      if (field.type === 'number') {
        rules.push({ type: 'number', message: '请输入数字', trigger: 'blur' })
      }
      return rules
    },
    getEventLevelLabel(level) {
      if (!level) return '-'
      if (['I', 'II', 'III', 'IV'].includes(level)) {
        return `${level}级`
      }
      if (level.startsWith('level')) {
        const label = getLevelLabel(level)
        return (label && label.replace(/[（(].*/, '')) || level
      }
      // Handle already formatted levels like 'Ⅰ级', 'Ⅱ级', etc.
      if (level.includes('级')) {
        return level
      }
      return level
    },
    async submit() {
      try {
        await this.$refs.reportForm.validate()
        this.submitting = true
        
        // Prepare request data
        const requestData = {
          eventId: (this.eventInfo && this.eventInfo.id) || (this.eventInfo && this.eventInfo.eventId),
          templateId: this.form.templateId,
          fields: this.form.fields,
          remark: this.form.remark || ''
        }
        
        const response = await submitProvinceReport(requestData)
        if (response.code === 200) {
          this.$message.success('上报请求已提交成功')
          this.$emit('submitted', response.data || requestData)
        this.handleClose()
        } else {
          this.$message.error(response.msg || '提交上报失败')
        }
      } catch (error) {
        if (error && error.message) {
          console.error('Report submission failed:', error)
          this.$message.error(error.message || '提交上报失败')
        } else {
          console.warn('Report validation failed: ', error)
        }
      } finally {
        this.submitting = false
      }
    },
    handleClose() {
      this.$emit('update:visible', false)
      this.innerVisible = false
    }
  }
}
</script>

<style scoped>
.dialog-section {
  margin-bottom: 16px;
}
.section-title {
  font-weight: 600;
}
.event-field {
  margin: 4px 0;
  font-size: 13px;
}
</style>