<template>
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    :rules="rules"
    label-width="120px"
    class="ruleForm"
    :size="formSize"
    status-icon
  >
    <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item label="数据编号" prop="data_code">
          <el-input v-model="ruleForm.data_code" placeholder="如 MB-SH-2024-001" />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="数据类型" prop="data_type">
          <el-select v-model="ruleForm.data_type" placeholder="请选择" style="width: 100%">
            <el-option
              v-for="item in dataTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="入库状态" prop="data_status">
          <el-select v-model="ruleForm.data_status" placeholder="请选择" style="width: 100%">
            <el-option label="待审核" value="待审核" />
            <el-option label="处理中" value="处理中" />
            <el-option label="已入库" value="已入库" />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="数据名称" prop="data_name">
          <el-input v-model="ruleForm.data_name" placeholder="请输入数据名称" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="航次名称" prop="voyage_name">
          <el-input v-model="ruleForm.voyage_name" placeholder="请输入航次名称" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item label="经度" prop="data_lon">
          <el-input v-model="ruleForm.data_lon" placeholder="如 113.52" />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="纬度" prop="data_lat">
          <el-input v-model="ruleForm.data_lat" placeholder="如 18.25" />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="调查区域" prop="survey_area">
          <el-input v-model="ruleForm.survey_area" placeholder="如 120 km²" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item label="数据量" prop="file_size">
          <el-input v-model="ruleForm.file_size" placeholder="如 2.8 GB" />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="是否涉密" prop="data_secrecy">
          <el-select v-model="ruleForm.data_secrecy" style="width: 100%">
            <el-option label="是" value="是" />
            <el-option label="否" value="否" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="入库时间" prop="fill_time">
          <el-date-picker
            v-model="ruleForm.fill_time"
            type="datetime"
            placeholder="请选择"
            format="YYYY/MM/DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item label="录入人" prop="fill_person">
          <el-input v-model="ruleForm.fill_person" placeholder="请输入录入人" />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="联系电话" prop="fill_tel">
          <el-input v-model="ruleForm.fill_tel" placeholder="请输入联系电话" />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="数据来源" prop="data_source">
          <el-input v-model="ruleForm.data_source" placeholder="如 船载测量系统" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="24">
        <el-form-item label="数据说明" prop="data_note">
          <el-input v-model="ruleForm.data_note" type="textarea" :rows="3" placeholder="请输入数据说明、处理状态等补充信息" />
        </el-form-item>
      </el-col>
    </el-row>

    <div class="btn-bar">
      <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
      <el-button @click="resetForm">取消</el-button>
      <el-button type="primary" plain :icon="Upload" @click="handleUpload">上传文件</el-button>
      <el-button type="success" plain :icon="Link" @click="handleCloudPath">指定云资源路径</el-button>
    </div>
  </el-form>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import type { ComponentSize, FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import { Upload, Link } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { dataEdit, dataFind } from '@/api/data.js'
import { getFlatDataTypeOptions } from '@/constants/dataTypes.js'

const router = useRouter()
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const dataTypeOptions = getFlatDataTypeOptions()

const ruleForm = ref({
  id: '',
  data_code: '',
  data_type: '',
  data_name: '',
  voyage_name: '',
  data_status: '待审核',
  data_lon: '',
  data_lat: '',
  survey_area: '',
  file_size: '',
  data_secrecy: '否',
  fill_time: '',
  fill_person: '',
  fill_tel: '',
  data_source: '',
  data_note: ''
})

const rules = reactive({
  data_code: [{ required: true, message: '请输入数据编号', trigger: 'blur' }],
  data_type: [{ required: true, message: '请选择数据类型', trigger: 'change' }],
  data_name: [{ required: true, message: '请输入数据名称', trigger: 'blur' }],
  voyage_name: [{ required: true, message: '请输入航次名称', trigger: 'blur' }],
  data_lon: [{ required: true, message: '请输入经度', trigger: 'blur' }],
  data_lat: [{ required: true, message: '请输入纬度', trigger: 'blur' }],
  data_secrecy: [{ required: true, message: '请选择是否涉密', trigger: 'change' }],
  fill_time: [{ required: true, message: '请选择入库时间', trigger: 'change' }],
  fill_person: [{ required: true, message: '请输入录入人', trigger: 'blur' }]
})

const props = defineProps({
  dataId: {
    type: [String, Number],
    default: ''
  }
})

const emit = defineEmits(['saved', 'upload', 'cloud-path'])

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (!valid) return
    const payload = { ...ruleForm.value }
    if (props.dataId) {
      payload.id = String(props.dataId)
    }
    dataEdit(payload).then((res: { success: boolean; entity?: Record<string, unknown>; message?: string }) => {
      if (res.success) {
        ruleForm.value = { ...ruleForm.value, ...res.entity }
        ElMessage.success('保存成功')
        emit('saved', res.entity)
        if (!props.dataId && res.entity?.id) {
          router.replace(`/input/${res.entity.id}`)
        }
      } else {
        ElMessage.error(res.message || '保存失败')
      }
    })
  })
}

const resetForm = () => {
  router.push('/search')
}

const handleUpload = () => {
  emit('upload')
}

const handleCloudPath = () => {
  emit('cloud-path')
}

const getDetail = () => {
  dataFind({ data_id: props.dataId }).then((res: { success: boolean; entity?: Record<string, unknown> }) => {
    if (res.success && res.entity) {
      ruleForm.value = {
        ...ruleForm.value,
        ...res.entity,
        fill_tel: String(res.entity.fill_tel || ''),
        data_source: String(res.entity.data_source || ''),
        data_note: String(res.entity.data_note || '')
      }
    }
  })
}

onMounted(() => {
  if (props.dataId) {
    getDetail()
  }
})
</script>

<style lang="scss" scoped>
.ruleForm {
  margin-top: 20px;

  .btn-bar {
    display: flex;
    justify-content: center;
    gap: 12px;
    flex-wrap: wrap;
  }
}
</style>
