<template>
  <div class="submit-feedback-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>提交新的环境问题反馈</span>
        </div>
      </template>
      <el-form :model="form" :rules="rules" ref="feedbackForm" label-width="120px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入反馈标题"></el-input>
        </el-form-item>
        <el-form-item label="问题描述" prop="description">
          <el-input type="textarea" :rows="4" v-model="form.description" placeholder="请详细描述您发现的问题"></el-input>
        </el-form-item>
        <el-form-item label="污染类型" prop="pollutionType">
          <el-select v-model="form.pollutionType" placeholder="请选择污染类型">
            <el-option v-for="(label, key) in pollutionTypeMap" :key="key" :label="label" :value="key"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="严重程度" prop="severityLevel">
          <el-rate v-model="rating" :max="3" :texts="['低', '中', '高']" show-text></el-rate>
        </el-form-item>
        <el-form-item label="问题地址" prop="location.textAddress">
           <el-input v-model="form.location.textAddress" placeholder="请输入问题发生的地址"></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="经度" prop="location.longitude">
              <el-input-number v-model="form.location.longitude" :precision="6" :step="0.000001" placeholder="请输入经度"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度" prop="location.latitude">
              <el-input-number v-model="form.location.latitude" :precision="6" :step="0.000001" placeholder="请输入纬度"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="网格X" prop="location.gridX">
              <el-input-number v-model="form.location.gridX" :precision="0" :step="1" placeholder="请输入网格X坐标"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="网格Y" prop="location.gridY">
              <el-input-number v-model="form.location.gridY" :precision="0" :step="1" placeholder="请输入网格Y坐标"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="照片/视频附件">
            <el-upload
                ref="upload"
                class="upload-demo"
                action="#"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-change="handleChange"
                :file-list="fileList"
                list-type="picture-card"
                :auto-upload="false"
                multiple
              >
              <el-icon><Plus /></el-icon>
            </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading">立即提交</el-button>
          <el-button @click="resetForm">重置表单</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules, UploadFile } from 'element-plus';
import { useFeedbackStore } from '@/store/feedback';
import { PollutionType } from '@/api/types';
import { SeverityLevel } from '@/api/feedback';
import type { FeedbackSubmissionRequest, LocationInfo } from '@/api/feedback';

const feedbackForm = ref<FormInstance>();
const loading = ref(false);
const fileList = ref<UploadFile[]>([]);
const rating = ref(2); // For el-rate which uses a number. 1=LOW, 2=MEDIUM, 3=HIGH

const form = reactive<Omit<FeedbackSubmissionRequest, 'severityLevel'>>({
  title: '',
  description: '',
  pollutionType: PollutionType.PM25,
  location: {
    latitude: 0,
    longitude: 0,
    textAddress: '',
    gridX: 0,
    gridY: 0,
  },
});

const pollutionTypeMap: Record<PollutionType, string> = {
  [PollutionType.PM25]: 'PM2.5',
  [PollutionType.O3]: '臭氧 (O3)',
  [PollutionType.NO2]: '二氧化氮 (NO2)',
  [PollutionType.SO2]: '二氧化硫 (SO2)',
  [PollutionType.OTHER]: '其他',
};

const rules = reactive<FormRules>({
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  description: [{ required: true, message: '请输入问题描述', trigger: 'blur' }],
  pollutionType: [{ required: true, message: '请选择污染类型', trigger: 'change' }],
  'location.textAddress': [{ required: true, message: '请输入问题地址', trigger: 'blur' }],
  'location.latitude': [{ required: true, type: 'number', message: '纬度必须为数字' }],
  'location.longitude': [{ required: true, type: 'number', message: '经度必须为数字' }],
  'location.gridX': [{ required: true, type: 'number', message: '网格X必须为数字' }],
  'location.gridY': [{ required: true, type: 'number', message: '网格Y必须为数字' }],
});

const feedbackStore = useFeedbackStore();

const handleRemove = (file: UploadFile, fileListUpdated: UploadFile[]) => {
  fileList.value = fileListUpdated;
};

const handlePreview = (file: UploadFile) => {
  console.log(file);
};

const handleChange = (file: UploadFile, fileListUpdated: UploadFile[]) => {
    fileList.value = fileListUpdated;
}

const submitForm = async () => {
  if (!feedbackForm.value) return;
  await feedbackForm.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        let severity: SeverityLevel;
        if (rating.value === 1) {
          severity = SeverityLevel.LOW;
        } else if (rating.value === 2) {
          severity = SeverityLevel.MEDIUM;
        } else {
          severity = SeverityLevel.HIGH;
        }

        const submissionData: FeedbackSubmissionRequest = {
          ...form,
          severityLevel: severity,
        };

        const formData = new FormData();
        formData.append('feedback', new Blob([JSON.stringify(submissionData)], { type: 'application/json' }));
        
        fileList.value.forEach(file => {
            if (file.raw) {
              formData.append('files', file.raw);
            }
        });

        await feedbackStore.submitFeedback(formData);
        ElMessage.success('反馈提交成功！感谢您的贡献。');
        resetForm();
      } catch (error) {
        ElMessage.error('提交失败，请稍后再试。');
      } finally {
        loading.value = false;
      }
    }
  });
};

const resetForm = () => {
  feedbackForm.value?.resetFields();
  fileList.value = [];
  rating.value = 2;
};
</script>

<style scoped>
.submit-feedback-container {
  padding: 20px;
}
.card-header {
  font-size: 1.2em;
  font-weight: bold;
}
</style> 
