<template>
  <div class="record-container">
    <!-- 检索记录表格 -->
    <div class="record-section">
      <div class="section-header">
        <el-button type="primary" @click="showAddDialog('search')">添加检索记录</el-button>
        <h2>检索记录</h2>
      </div>
      <el-table :data="state.searchRecords" border style="width: 100%" :header-cell-style="{ background: '#fafafa', color: '#606266'}">
        <el-table-column prop="searcher" label="检索人员" />
        <el-table-column prop="content" label="检索内容" />
        <el-table-column prop="time" label="检索时间" />
        <el-table-column prop="location" label="检索地点" />
        <el-table-column prop="report" label="检索报告">
          <template #default="{row}">
            <el-link type="primary" @click="downloadFile(row.reportId)">{{ row.report }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" />
        <el-table-column prop="operator" label="操作人" />
        <el-table-column label="操作" width="120">
          <template #default="{row}">
            <el-button type="text" @click="editRecord('search', row)">编辑</el-button>
            <el-button type="text" @click="deleteRecord('search', row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 论证记录表格 -->
    <div class="record-section">
      <div class="section-header">
        <el-button type="primary" @click="showAddDialog('argument')">添加论证记录</el-button>
        <h2>论证记录</h2>
      </div>
      <el-table :data="state.vestRecords" border style="width: 100%" :header-cell-style="{ background: '#fafafa', color: '#606266'}">
        <el-table-column prop="expert" label="论证专家" />
        <el-table-column prop="content" label="论证内容" />
        <el-table-column prop="conclusion" label="立项结论" />
        <el-table-column prop="time" label="论证时间" />
        <el-table-column prop="location" label="论证地点" />
        <el-table-column prop="report" label="论证报告">
          <template #default="{row}">
            <el-link type="primary" @click="downloadFile(row.reportId)">{{ row.report }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" />
        <el-table-column prop="operator" label="操作人" />
        <el-table-column label="操作" width="120">
          <template #default="{row}">
            <el-button type="text" @click="editRecord('argument', row)">编辑</el-button>
            <el-button type="text" @click="deleteRecord('argument', row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 调研记录表格 -->
    <div class="record-section">
      <div class="section-header">
        <el-button type="primary" @click="showAddDialog('research')">添加调研记录</el-button>
        <h2>调研记录</h2>
      </div>
      <el-table :data="state.reportRecords" border style="width: 100%" :header-cell-style="{ background: '#fafafa', color: '#606266'}">
        <el-table-column prop="researcher" label="调研人员" />
        <el-table-column prop="content" label="调研内容" />
        <el-table-column prop="time" label="调研时间" />
        <el-table-column prop="location" label="调研地点" />
        <el-table-column prop="report" label="调研报告">
          <template #default="{row}">
            <el-link type="primary" @click="downloadFile(row.reportId)">{{ row.report }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" />
        <el-table-column prop="operator" label="操作人" />
        <el-table-column label="操作" width="120">
          <template #default="{row}">
            <el-button type="text" @click="editRecord('research', row)">编辑</el-button>
            <el-button type="text" @click="deleteRecord('research', row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加/编辑检索记录对话框 -->
    <el-dialog
        :title="`${currentAction === 'add' ? '添加' : '编辑'}检索记录`"
        v-model="searchDialogVisible"
        width="50%"
    >
      <el-form :model="searchForm" :rules="rules" ref="searchFormRef" label-width="100px">
        <el-form-item label="检索人员：" prop="searcher">
          <el-input v-model="searchForm.searcher" placeholder="请输入检索人员" />
        </el-form-item>
        <el-form-item label="检索内容：" prop="content">
          <el-input
              v-model="searchForm.content"
              type="textarea"
              :rows="4"
              placeholder="请输入检索内容"
              resize="vertical"
          />
        </el-form-item>
        <el-form-item label="检索时间：" prop="time">
          <el-date-picker
              v-model="searchForm.time"
              type="date"
              placeholder="选择日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="检索地点：" prop="location">
          <div class="location-selector">
            <el-select
                style="width: 100px"
                v-model="searchForm.province"
                placeholder="省"
                @change="(value)=>{handleProvinceChange(value)}"
            >
              <el-option
                  v-for="item in provinces"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
              />
            </el-select>
            <el-select
                style="width: 100px"
                v-model="searchForm.city"
                placeholder="市"
                :disabled="!searchForm.province"
                @change="(value)=>{handleCityChange(value)}"
            >
              <el-option
                  v-for="item in cities"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
              />
            </el-select>
            <el-select
                style="width: 100px"
                v-model="searchForm.district"
                placeholder="县/区"
                :disabled="!searchForm.city"
            >
              <el-option
                  v-for="item in districts"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
              />
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="检索报告：" prop="report">
          <el-upload :on-preview="(e: any) => $emit('preview', e)" :file-list="taskDocumentSearch"
                     :on-remove="(a: any) => handFileRemove(a)" :before-upload="beforeUpload" class="upload-demo"
                     :http-request="(event: any) => handUpload(event)">
            <el-button type="primary">
              <el-icon><Upload /></el-icon>
              上传
            </el-button>
            <template #tip>
              <div class="el-upload__tip">
                上传检索报告，支持pdf格式，大小不超过5MB。
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="searchDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitSearchForm">保存</el-button>
      </template>
    </el-dialog>

    <!-- 添加/编辑论证记录对话框 -->
    <el-dialog
        :title="`${currentAction === 'add' ? '添加' : '编辑'}论证记录`"
        v-model="argumentDialogVisible"
        width="50%"
    >
      <el-form :model="argumentForm" :rules="rules" ref="argumentFormRef" label-width="100px">
        <el-form-item label="论证专家：" prop="expert">
          <el-input v-model="argumentForm.expert" placeholder="请输入论证专家" />
        </el-form-item>
        <el-form-item label="论证内容：" prop="content">
          <el-input
              v-model="argumentForm.content"
              type="textarea"
              :rows="4"
              placeholder="请输入论证内容"
              resize="vertical"
          />
        </el-form-item>
        <el-form-item label="立项结论：" prop="conclusion">
          <el-input v-model="argumentForm.conclusion" placeholder="请输入立项结论" />
        </el-form-item>
        <el-form-item label="论证时间：" prop="time">
          <el-date-picker
              v-model="argumentForm.time"
              type="date"
              placeholder="选择日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="论证地点：" prop="location">
          <div class="location-selector">
            <el-select
                style="width: 100px"
                v-model="argumentForm.province"
                placeholder="省"
                @change="(value)=>{handleProvinceChange(value)}"
            >
              <el-option
                  v-for="item in provinces"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
              />
            </el-select>
            <el-select
                style="width: 100px"
                v-model="argumentForm.city"
                placeholder="市"
                :disabled="!argumentForm.province"
                @change="(value)=>{handleCityChange(value)}"
            >
              <el-option
                  v-for="item in cities"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
              />
            </el-select>
            <el-select
                style="width: 100px"
                v-model="argumentForm.district"
                placeholder="县/区"
                :disabled="!argumentForm.city"
            >
              <el-option
                  v-for="item in districts"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
              />
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="论证报告：" prop="report">
          <el-upload :on-preview="(e: any) => $emit('preview', e)" :file-list="taskDocumentArgument"
                     :on-remove="(a: any) => handFileRemove(a)" :before-upload="beforeUpload" class="upload-demo"
                     :http-request="(event: any) => handUpload(event)">
            <el-button type="primary">
              <el-icon><Upload /></el-icon>
              上传
            </el-button>
            <template #tip>
              <div class="el-upload__tip">
                上传论证报告，支持pdf格式，大小不超过5MB。
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="argumentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitArgumentForm">保存</el-button>
      </template>
    </el-dialog>

    <!-- 添加/编辑调研记录对话框 -->
    <el-dialog
        :title="`${currentAction === 'add' ? '添加' : '编辑'}调研记录`"
        v-model="researchDialogVisible"
        width="50%"
    >
      <el-form :model="researchForm" :rules="rules" ref="researchFormRef" label-width="100px">
        <el-form-item label="调研人员：" prop="researcher">
          <el-input v-model="researchForm.researcher" placeholder="请输入调研人员" />
        </el-form-item>
        <el-form-item label="调研内容：" prop="content">
          <el-input
              v-model="researchForm.content"
              type="textarea"
              :rows="4"
              placeholder="请输入调研内容"
              resize="vertical"
          />
        </el-form-item>
        <el-form-item label="调研时间：" prop="time">
          <el-date-picker
              v-model="researchForm.time"
              type="date"
              placeholder="选择日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="调研地点：" prop="location">
          <div class="location-selector">
            <el-select
                style="width: 100px"
                v-model="researchForm.province"
                placeholder="省"
                @change="(value)=>{handleProvinceChange(value)}"
            >
              <el-option
                  v-for="item in provinces"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
              />
            </el-select>
            <el-select
                style="width: 100px"
                v-model="researchForm.city"
                placeholder="市"
                :disabled="!researchForm.province"
                @change="(value)=>{handleCityChange(value)}"
            >
              <el-option
                  v-for="item in cities"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
              />
            </el-select>
            <el-select
                style="width: 100px"
                v-model="researchForm.district"
                placeholder="县/区"
                :disabled="!researchForm.city"
            >
              <el-option
                  v-for="item in districts"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
              />
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="调研报告：" prop="report">
          <el-upload :on-preview="(e: any) => $emit('preview', e)" :file-list="taskDocumentResearch"
                     :on-remove="(a: any) => handFileRemove(a)" :before-upload="beforeUpload" class="upload-demo"
                     :http-request="(event: any) => handUpload(event)">
            <el-button type="primary">
              <el-icon><Upload /></el-icon>
              上传
            </el-button>
            <template #tip>
              <div class="el-upload__tip">
                上传调研报告，支持pdf格式，大小不超过5MB。
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="researchDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitResearchForm">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {ref, reactive, onMounted, computed} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Upload } from '@element-plus/icons-vue'
import {add, del, get, update} from "@/api/public/basic";
import {useUserInfosState} from "@/stores/userInfos";
import cityData from '@/assets/city.js'
import CryptoJS from "crypto-js";
import {HOST_R} from "@/api/evn"; // 导入城市数据
const userInfos = useUserInfosState();
//import { provinceData, cityData, area } from 'china-area-data'
const props = defineProps({
  projectId: {
    type: String,
    required: true
  }
})
const state=reactive({
  loading:false,
  tableData:[],
  searchRecords:[],
  totalsearch:0,
  queryParams: {// 页码
    pageNum: 1,
    pageSize: 10,// 每页大小
    projectId:'',
  },
  vestRecords:[],
  totalvest:0,
  reportRecords:[],
  totalreport:0,
  projectIdmain:'',
})
const handleQuerysearch = async () => {
  try {
    state.queryParams.projectId=props.projectId
    const response = await get(state.queryParams, 'i2pxS9rxJvw')
    state.searchRecords = response.data.result || []
    state.totalsearch= response.data.count || 0
  } catch (error) {
    ElMessage.error('获取项目成员失败')
    console.error(error)
  }
}
//i2pyUcstWY1
const handleQueryvest = async () => {
  try {
    state.queryParams.projectId=props.projectId
    const response = await get(state.queryParams, 'i2pySPfZNi7')
    state.vestRecords = response.data.result || []
    state.totalvest= response.data.count || 0
  } catch (error) {
    ElMessage.error('获取项目成员失败')
    console.error(error)
  }
}
const handleQueryreport = async () => {
  try {
    state.queryParams.projectId=props.projectId
    const response = await get(state.queryParams, 'i2pyUcstWY1')
    state.reportRecords = response.data.result || []
    state.totalreport= response.data.count || 0
  } catch (error) {
    ElMessage.error('获取项目成员失败')
    console.error(error)
  }
}

onMounted(() => {
  state.projectIdmain=props.projectId
  handleQuerysearch()
  handleQueryvest()
  handleQueryreport()

})
// 表格数据
const searchRecords = ref([{}])
const argumentRecords = ref([])
const researchRecords = ref([])
// 对话框控制
const searchDialogVisible = ref(false)
const argumentDialogVisible = ref(false)
const researchDialogVisible = ref(false)
const currentAction = ref('add') // 'add' or 'edit'
const currentRecordId = ref(null)
// 表单数据
const searchForm = reactive({
      searcher: '',
      content: '',
      time: '',
      province: '',
      city: '',
      district: '',
      report: '',
  reportId:''
    })

    const argumentForm = reactive({
      expert: '',
      content: '',
      conclusion: '',
      time: '',
      province: '',
      city: '',
      district: '',
      report: '',
      reportId:''
    })

    const researchForm = reactive({
      researcher: '',
      content: '',
      time: '',
      province: '',
      city: '',
      district: '',
      report: '',
      reportId:''
    })

    // 表单验证规则
    const rules = reactive({
      searcher: [{ required: true, message: '请输入检索人员', trigger: 'blur' }],
      content: [{ required: true, message: '请输入检索内容', trigger: 'blur' }],
      time: [{ required: true, message: '请选择检索时间', trigger: 'change' }],
      province: [{ required: true, message: '请选择省份', trigger: 'change' }],
      city: [{ required: true, message: '请选择城市', trigger: 'change' }],
      district: [{ required: true, message: '请选择区县', trigger: 'change' }],
      report: [{ required: true, message: '请上传检索报告', trigger: 'change' }],
      expert: [{ required: true, message: '请输入论证专家', trigger: 'blur' }],
      conclusion: [{ required: true, message: '请输入立项结论', trigger: 'blur' }],
      researcher: [{ required: true, message: '请输入调研人员', trigger: 'blur' }]
    })


// 在setup函数中处理数据
const provinces = ref(cityData.map(province => ({
  code: province.code,
  name: province.name
})))

const cities = ref([])
const districts = ref([])

// 处理省份变化
const handleProvinceChange = (provinceCode) => {
  const selectedProvince = cityData.find(p => p.code === provinceCode)
  cities.value = selectedProvince?.city?.map(city => ({
    code: city.code,
    name: city.name
  })) || []
  districts.value = []
}

// 处理城市变化
const handleCityChange = (cityCode) => {
  const selectedProvince = cityData.find(p =>
      p.city.some(c => c.code === cityCode))
  if (!selectedProvince) return

  const selectedCity = selectedProvince.city.find(c => c.code === cityCode)
  districts.value = selectedCity?.area?.map(area => ({
    code: area.code,
    name: area.name
  })) || []
}




    // const searchCities = ref([])
    // const searchDistricts = ref([])
    // const argumentCities = ref([])
    // const argumentDistricts = ref([])
    // const researchCities = ref([])
    // const researchDistricts = ref([])


const taskDocumentSearch = computed(() => {
  return searchForm.report ? [{ name: searchForm.report }] : [];
});
const taskDocumentArgument = computed(() => {
  return argumentForm.report ? [{ name: argumentForm.report }] : [];
});
const taskDocumentResearch = computed(() => {
  return researchForm.report ? [{ name: researchForm.report }] : [];
});
const handUpload = (event: any) => {
  // 计算hash值
  console.log(event.file.name)
  console.log("文件名？？？")
  var reader = new FileReader();
  reader.onload = (e: any) => {
    var fileData = e.target.result;
    var wordArray = CryptoJS.lib.WordArray.create(fileData);
    var hash = CryptoJS.SHA1(wordArray).toString();
    fetch(`/api/upload/${event.file.name}?privacy=0&isFolder=0&parentId=0&signature=${hash}`, {
      method: 'POST',
      body: fileData,
    })
        .then(response => {
          if (!response.ok) {
            throw new Error('文件上传失败！');
          }
          return response.text();
        })
        .then(responseText => {
          const data = JSON.parse(responseText);  // 手动解析 JSON
          console.log('文件 ID：', data.data.id);
          console.log('文件名称：', data.data.name);
          console.log('文件上传成功：', responseText);
          // console.log('文件上传成功：', responseText.data.id);
          // console.log(responseText.id)
          if(searchDialogVisible.value===true&&argumentDialogVisible.value===false&&researchDialogVisible.value===false) {
            searchForm.report=data.data.name
            searchForm.reportId=data.data.id
          }else if(searchDialogVisible.value===false&&argumentDialogVisible.value===true&&researchDialogVisible.value===false){
            argumentForm.report=data.data.name
            argumentForm.reportId=data.data.id
          }else if(searchDialogVisible.value===false&&argumentDialogVisible.value===false&&researchDialogVisible.value===true){
            researchForm.report=data.data.name
            researchForm.reportId=data.data.id
          }

          //form.planId=data.data.id
          ElMessage.success('文件上传成功！');
        })
        .catch(error => {
          console.log('文件上传失败4！', error);
        });
  };
  reader.readAsArrayBuffer(event.file);
};

const handFileRemove = (event:any) => {
  if(searchDialogVisible.value===true&&argumentDialogVisible.value===false&&researchDialogVisible.value===false) {
    searchForm.report=''
  }else if(searchDialogVisible.value===false&&argumentDialogVisible.value===true&&researchDialogVisible.value===false){
    argumentForm.report=''
  }else if(searchDialogVisible.value===false&&argumentDialogVisible.value===false&&researchDialogVisible.value===true){
    researchForm.report=''
  }
}


    // 文件上传
    const searchReportList = ref([])
    const argumentReportList = ref([])
    const researchReportList = ref([])

    // 方法
    const showAddDialog = (type) => {
      currentAction.value = 'add'
      currentRecordId.value = null

      if (type === 'search') {
        resetSearchForm()
        searchDialogVisible.value = true
      } else if (type === 'argument') {
        resetArgumentForm()
        argumentDialogVisible.value = true
      } else if (type === 'research') {
        resetResearchForm()
        researchDialogVisible.value = true
      }
    }

    const editRecord = (type, record) => {
      currentAction.value = 'edit'
      currentRecordId.value = record.id
      let [province, city, district] = ['', '', '']
      if (record.locationCode) {
        [province, city, district] = record.locationCode.split('/').map(item => item.trim()) || ['', '', '']
      }
      if (type === 'search') {
        Object.assign(searchForm, {
          searcher: record.searcher,
          content: record.content,
          time: record.time,
          report: record.report,
          province: province || '', // 省份
          city: city || '',       // 城市
          district: district || '' // 区县
        })
        searchDialogVisible.value = true
      } else if (type === 'argument') {
        Object.assign(argumentForm, {
          expert: record.expert,
          content: record.content,
          conclusion: record.conclusion,
          time: record.time,
          report: record.report,
          province: province || '', // 省份
          city: city || '',       // 城市
          district: district || '' // 区县
        })
        argumentDialogVisible.value = true
      } else if (type === 'research') {
        Object.assign(researchForm, {
          researcher: record.researcher,
          content: record.content,
          time: record.time,
          report: record.report,
          province: province || '', // 省份
          city: city || '',       // 城市
          district: district || '' // 区县
        })
        researchDialogVisible.value = true
      }
    }

    const deleteRecord = (type, id) => {
      ElMessageBox.confirm('确定要删除这条记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (type === 'search') {
          del({ id: [id] }, 'i2pxS9rxJvw').then(() => {
            handleQuerysearch(); // 刷新数据
          }).catch(error => {
            console.error('删除失败:', error);
            ElMessage.error('删除失败');
          });
          //searchRecords.value = searchRecords.value.filter(item => item.id !== id)
        } else if (type === 'argument') {//i2pyUcstWY1
          del({ id: [id] }, 'i2pySPfZNi7').then(() => {
            handleQueryvest(); // 刷新数据
          }).catch(error => {
            console.error('删除失败:', error);
            ElMessage.error('删除失败');
          });
          //argumentRecords.value = argumentRecords.value.filter(item => item.id !== id)
        } else if (type === 'research') {//i2pySPfZNi7
          del({ id: [id] }, 'i2pyUcstWY1').then(() => {
            handleQueryreport// 刷新数据
          }).catch(error => {
            console.error('删除失败:', error);
            ElMessage.error('删除失败');
          });
          researchRecords.value = researchRecords.value.filter(item => item.id !== id)
        }
        ElMessage.success('删除成功')
      })
    }

    const beforeUpload = (file) => {
      const isPDF = file.type === 'application/pdf'
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isPDF) {
        ElMessage.error('只能上传PDF格式的文件!')
      }
      if (!isLt5M) {
        ElMessage.error('文件大小不能超过5MB!')
      }
      return isPDF && isLt5M
    }

    const handleSearchReportChange = (file) => {
      searchForm.report = file.name
    }

    const handleArgumentReportChange = (file) => {
      argumentForm.report = file.name
    }

    const handleResearchReportChange = (file) => {
      researchForm.report = file.name
    }

    const submitSearchForm = async () => {
      // 这里应该验证表单并提交
      const location = `${provinces.value.find(p => p.code === searchForm.province)?.name}/${
          cities.value.find(c => c.code === searchForm.city)?.name}/${
          districts.value.find(d => d.code === searchForm.district)?.name}`

      const record = {
        searcher: searchForm.searcher,
        content: searchForm.content,
        time: searchForm.time,
        location,
        locationCode: `${searchForm.province}/${searchForm.city}/${searchForm.district}`,
        report: searchForm.report,
        updateTime: new Date().toISOString().split('T')[0],
        operator: userInfos.userInfos.nickname,
        projectId:state.projectIdmain
      }
      if (currentAction.value === 'add') {
        await add(record, 'i2pxS9rxJvw');
        handleQuerysearch()
      } else {
          update(currentRecordId.value, record, 'i2pxS9rxJvw').then((response) => {
            handleQuerysearch()
            ElMessage.success('修改成功');
            state.loading = false;
          });
        }
      searchDialogVisible.value = false
      ElMessage.success('操作成功')
    }

    const submitArgumentForm = async () => {
      // 类似submitSearchForm的实现
      const location = `${provinces.value.find(p => p.code === argumentForm.province)?.name}/${
          cities.value.find(c => c.code === argumentForm.city)?.name}/${
          districts.value.find(d => d.code === argumentForm.district)?.name}`

      const record = {
        expert: argumentForm.expert,
        content: argumentForm.content,
        conclusion: argumentForm.conclusion,
        time: argumentForm.time,
        location,
        locationCode: `${argumentForm.province}/${argumentForm.city}/${argumentForm.district}`,
        report: argumentForm.report,
        updateTime: new Date().toISOString().split('T')[0],
        operator: userInfos.userInfos.nickname,
        projectId:state.projectIdmain
      }

      if (currentAction.value === 'add') {
        await add(record, 'i2pySPfZNi7');
        handleQueryvest()
        handleQueryreport()
      } else {
        update(currentRecordId.value, record, 'i2pySPfZNi7').then((response) => {
          handleQueryvest()
          handleQueryreport()
          ElMessage.success('修改成功');
          state.loading = false;
        });
      }

      argumentDialogVisible.value = false
      ElMessage.success('操作成功')
    }

    const submitResearchForm = async () => {
      // 类似submitSearchForm的实现
      const location = `${provinces.value.find(p => p.code === researchForm.province)?.name}/${
          cities.value.find(c => c.code === researchForm.city)?.name}/${
        districts.value.find(d => d.code === researchForm.district)?.name}`
      
      const record = {
        researcher: researchForm.researcher,
        content: researchForm.content,
        time: researchForm.time,
        location,
        locationCode: `${researchForm.province}/${researchForm.city}/${researchForm.district}`,
        report: researchForm.report,
        updateTime: new Date().toISOString().split('T')[0],
        operator: userInfos.userInfos.nickname,
        projectId:state.projectIdmain
      }

      if (currentAction.value === 'add') {
        await add(record, 'i2pyUcstWY1');
        handleQueryreport()
        handleQueryvest()
      } else {
        update(currentRecordId.value, record, 'i2pyUcstWY1').then((response) => {
          handleQueryreport()
          handleQueryvest()
          ElMessage.success('修改成功');
          state.loading = false;
        });
      }

      researchDialogVisible.value = false
      ElMessage.success('操作成功')
    }

    const resetSearchForm = () => {
      Object.assign(searchForm, {
        searcher: '',
        content: '',
        time: '',
        province: '',
        city: '',
        district: '',
        report: ''
      })
      searchReportList.value = []
    }

    const resetArgumentForm = () => {
      Object.assign(argumentForm, {
        expert: '',
        content: '',
        conclusion: '',
        time: '',
        province: '',
        city: '',
        district: '',
        report: ''
      })
      argumentReportList.value = []
    }

    const resetResearchForm = () => {
      Object.assign(researchForm, {
        researcher: '',
        content: '',
        time: '',
        province: '',
        city: '',
        district: '',
        report: ''
      })
      researchReportList.value = []
    }
    const downloadFile = (filename) => {
      ElMessage.success(`开始下载文件`)
      window.open(`${HOST_R}/uploads/${filename}`, '_blank')
    }
</script>

<style scoped>
.record-container {
  padding: 20px;
}

.record-section {
  margin-bottom: 30px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.location-selector {
  display: flex;
  gap: 10px;
}

.location-selector .el-select {
  flex: 1;
}

.upload-demo .el-upload__tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
h2{
  position: relative;
  margin: auto;
  font-size: 25px;
}
</style>
