<template>
  <div class="public-submit-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>公共环境问题反馈</span>
          <p>感谢您为环境保护出一份力！您可以在此提交发现的环境问题，无需登录。</p>
        </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="contactInfo">
          <el-input v-model="form.contactInfo" placeholder="选填，便于我们与您联系（邮箱或电话）"></el-input>
        </el-form-item>
        <el-form-item label="问题地址" prop="textAddress">
           <el-input v-model="form.textAddress" placeholder="请输入问题发生的地址"></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="经度" prop="longitude">
              <el-input-number v-model="form.longitude" :precision="6" :step="0.000001" placeholder="请输入经度"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度" prop="latitude">
              <el-input-number v-model="form.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="gridX">
              <el-input-number v-model="form.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="gridY">
              <el-input-number v-model="form.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-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-button @click="$router.push('/login')">返回登录</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 { PollutionType, SeverityLevel } from '@/api/feedback';
import { submitPublicFeedback } from '@/api/public'; // Assuming the function will be in a new api/public.ts

const feedbackForm = ref<FormInstance>();
const loading = ref(false);
const fileList = ref<UploadFile[]>([]);
const rating = ref(2); 

interface PublicFeedbackForm {
  title: string;
  description: string;
  pollutionType: PollutionType;
  severityLevel: SeverityLevel;
  contactInfo?: string;
  textAddress: string;
  latitude?: number;
  longitude?: number;
  gridX?: number;
  gridY?: number;
}

const form = reactive({
  title: '',
  description: '',
  pollutionType: PollutionType.OTHER,
  contactInfo: '',
  textAddress: '',
  latitude: 0,
  longitude: 0,
  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' }],
  textAddress: [{ required: true, message: '请输入问题地址', trigger: 'blur' }],
  gridX: [{ required: true, type: 'number', message: '网格X必须为数字' }],
  gridY: [{ required: true, type: 'number', message: '网格Y必须为数字' }],
});

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

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: PublicFeedbackForm = { ...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 submitPublicFeedback(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>
.public-submit-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  padding: 20px;
  background-color: #f0f2f5;
}
.box-card {
  width: 800px;
}
.card-header {
  font-size: 1.2em;
  font-weight: bold;
  text-align: center;
}
.card-header p {
  font-size: 0.8em;
  font-weight: normal;
  color: #666;
  margin-top: 5px;
}
</style> 
