<template>
  <div class="container">
    <div class="title">任务需求信息录入</div>
    <el-divider />
    <div class="info">任务信息</div>

    <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        class="ruleForm"
        :size="formSize"
        status-icon
    >
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="关联航次" prop="voyage_name">
            <el-select v-model="ruleForm.voyage_name" >
              <el-option v-for="(item, index) in  voyageOptions" :key="index" :label="item.voyage_name" :value="item.voyage_name" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="状态信息" prop="rescue_status">
            <el-select v-model="ruleForm.rescue_status" >
              <el-option label="任务开始" value="任务开始" />
              <el-option label="任务处理中" value="任务处理中" />
              <el-option label="任务已完成" value="任务已完成" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="状态变更时间" prop="rescue_status_time">
            <el-date-picker
                style="width: 100%"
                v-model="ruleForm.rescue_status_time"
                type="datetime"
                placeholder="请选择"
                format="YYYY/MM/DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="状态变更说明" prop="rescue_status_note">
            <el-input placeholder="请输入" v-model="ruleForm.rescue_status_note" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="任务类型" prop="rescue_type">
            <el-select v-model="ruleForm.rescue_type" >
              <el-option label="应急搜捞" value="SAR" />
              <el-option label="专项调查" value="SI" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="目标类别" prop="rescue_target_type">
            <el-select v-model="ruleForm.rescue_target_type" >
              <el-option label="大型沉物" value="Wreck" />
              <el-option label="锚系类目标" value="Mooring" />
              <el-option label="非合作方目标" value="NCT" />
              <el-option label="其他" value="Other" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="目标名称" prop="rescue_target_name">
            <el-input placeholder="请输入" v-model="ruleForm.rescue_target_name" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="目标经度" prop="rescue_target_lon">
            <el-input placeholder="请输入" v-model="ruleForm.rescue_target_lon" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="目标纬度" prop="rescue_target_lat">
            <el-input placeholder="请输入" v-model="ruleForm.rescue_target_lat" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="搜寻范围半径" prop="rescue_target_radius">
            <el-input placeholder="请输入" v-model="ruleForm.rescue_target_radius">
              <template #append>米</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="目标宽度" prop="rescue_target_width">
            <el-input placeholder="请输入" v-model="ruleForm.rescue_target_width">
              <template #append>米</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="目标长度" prop="rescue_target_length">
            <el-input placeholder="请输入" v-model="ruleForm.rescue_target_length">
              <template #append>米</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="目标高度" prop="rescue_target_height">
            <el-input placeholder="请输入" v-model="ruleForm.rescue_target_height">
              <template #append>米</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="搜寻处置目标重量(空气中)" prop="rescue_air_weight">
            <el-input placeholder="请输入" v-model="ruleForm.rescue_air_weight">
              <template #append>千克</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="搜寻处置目标重量(水中)" prop="rescue_water_weight">
            <el-input placeholder="请输入" v-model="ruleForm.rescue_water_weight">
              <template #append>千克</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="搜寻处置目标水深" prop="rescue_water_depth">
            <el-input placeholder="请输入" v-model="ruleForm.rescue_water_depth">
              <template #append>米</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="搜寻处置目标预估价值" prop="rescue_target_price">
            <el-input placeholder="请输入" v-model="ruleForm.rescue_target_price" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="快速响应等级" prop="rescue_response_level">
            <el-select v-model="ruleForm.rescue_response_level" >
              <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="8">
          <el-form-item label="是否涉密" prop="rescue_secrecy">
            <el-select v-model="ruleForm.rescue_secrecy" >
              <el-option label="是" value="是" />
              <el-option label="否" value="否" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="搜捞目标的所属单位" prop="rescue_unit">
            <el-input placeholder="请输入" v-model="ruleForm.rescue_unit" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="快速响应时间要求" prop="rescue_response_day">
            <el-input placeholder="请输入" v-model="ruleForm.rescue_response_day">
              <template #append>天</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="填报时间" prop="fill_time">
            <el-date-picker
                style="width: 100%"
                v-model="ruleForm.fill_time"
                type="datetime"
                placeholder="请选择"
                format="YYYY/MM/DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系人姓名" prop="fill_person">
            <el-input placeholder="请输入" v-model="ruleForm.fill_person" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系人电话" prop="fill_tel">
            <el-input placeholder="请输入" v-model="ruleForm.fill_tel" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="其他信息" prop="rescue_note">
            <el-input placeholder="请输入" v-model="ruleForm.rescue_note" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="填报来源描述" prop="fill_note">
            <el-input placeholder="请输入" v-model="ruleForm.fill_note" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20" v-if="rescueId">
        <el-col :span="8">
          <el-form-item label="其他附件">
            <el-button type="primary" @click="onFileList">查看附件</el-button>
          </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>
      </div>
    </el-form>

    <el-dialog v-model="dialogTableVisible" title="附件列表" width="800">
      <div class="upload-btn">
        <el-upload
            v-model:file-list="fileList"
            class="upload-demo"
            :action="uploadUrl"
            :show-file-list="false"
            :data="{
              rescue_id: rescueId
            }"
            :on-success="onSuccess"
        >
          <el-button type="primary">上传附件</el-button>
        </el-upload>
      </div>
      <el-table :data="fileData">
        <el-table-column property="file_org_name" label="文件名称" />
        <el-table-column property="file_length" label="文件大小" width="150">
          <template #default="scope">
            <span class="file-size">{{ formatFileSize(scope.row.file_length) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="handleDownload(scope.row.tsy_id)">下载</el-button>
            <el-popconfirm
                confirm-button-text="确定"
                cancel-button-text="取消"
                :icon="InfoFilled"
                icon-color="#626AEF"
                title="是否确认删除?"
                @confirm="handleDelete(scope.row.tsy_id)"
            >
              <template #reference>
                <el-button link type="primary" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import {useRoute, useRouter} from 'vue-router'
import type { ComponentSize, FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import { InfoFilled } from '@element-plus/icons-vue'
import { getParam, voyageReg, regEdit, regFind, regFileList, regFileDelete } from '@/api/task.js'

const router = useRouter();
const uploadUrl = import.meta.env.VITE_APP_BASE_API + '/rescue/reg/file/upload.htm'

const dialogTableVisible = ref(false)
const fileList = ref([])
const fileData = ref([])

const route = useRoute();
const rescueId = route.params.id; // 获取路由参数
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = ref({
  voyage_name: '',
  rescue_status: '',
  rescue_status_time: '',
  rescue_status_note: '',
  rescue_type: '',
  rescue_target_type: '',
  rescue_target_name: '',
  rescue_target_lon: '',
  rescue_target_lat: '',
  rescue_target_radius: '',
  rescue_target_width: '',
  rescue_target_length: '',
  rescue_target_height: '',
  rescue_air_weight: '',
  rescue_water_weight: '',
  rescue_water_depth: '',
  rescue_target_price: '',
  rescue_response_level: '',
  rescue_secrecy: '',
  rescue_unit: '',
  rescue_response_day: '',
  fill_time: '',
  fill_person: '',
  fill_tel: '',
  rescue_note: '',
  fill_note: '',
})

const rules = reactive({
  voyage_name: [
    { required: true, message: '请选择', trigger: 'change' },
  ],
  rescue_status: [
    { required: true, message: '请选择', trigger: 'change' },
  ],
  rescue_status_time: [
    { required: true, message: '请选择', trigger: 'change' },
  ],
  rescue_status_note: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
  rescue_type: [
    { required: true, message: '请选择', trigger: 'change' },
  ],
  rescue_target_type: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
  rescue_target_name: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
  rescue_target_lon: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
  rescue_target_lat: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
  rescue_target_radius: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
  rescue_target_width: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
  rescue_target_length: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
  rescue_target_height: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
  rescue_air_weight: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
  rescue_water_weight: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
  rescue_water_depth: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
  rescue_target_price: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
  rescue_response_level: [
    { required: true, message: '请选择', trigger: 'change' },
  ],
  rescue_secrecy: [
    { required: true, message: '请选择', trigger: 'change' },
  ],
  rescue_unit: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
  rescue_response_day: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
  fill_time: [
    { required: true, message: '请选择', trigger: 'change' },
  ],
  fill_person: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
  fill_tel: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      regEdit(ruleForm.value).then(res => {
        ruleForm.value = res.entity
        ElMessage({
          message: '提交成功',
          type: 'success'
        })
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

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

// 获取任务详情
const getDetail = () => {
  regFind({rescue_id: rescueId}).then(res => {
    ruleForm.value = res.entity
  })
}

// 查看附件列表
const onFileList = () => {
  dialogTableVisible.value = true

  regFileList({rescue_id: rescueId}).then(res => {
    fileData.value = res.array
  })
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

// 文件上传成功回调
const onSuccess = () => {
  regFileList({rescue_id: rescueId}).then(res => {
    fileData.value = res.array
  })
}

// 文件下载
const handleDownload = async (fileId) => {
  window.open(`${import.meta.env.VITE_APP_BASE_API}/rescue/reg/file/download.htm?file_id=${fileId}`)
}

// 文件删除
const handleDelete = (fileId) => {
  regFileDelete({
    file_id: fileId
  }).then(res => {
    regFileList({rescue_id: rescueId}).then(res => {
      fileData.value = res.array
    })
  })
}

const VoyageSocketUrl = ref('')
// 获取系统参数列表
const getParamsList = () => {
  getParam().then(res => {
    const data = res.array.find(item => item.param_name === 'VoyageSocketUrl')

    if (data?.param_value) {
      VoyageSocketUrl.value = data.param_value
    } else {
      VoyageSocketUrl.value = `${window.location.protocol}//${window.location.hostname}:${window.location.port}/ds/`
    }

    getVoyageReg()
  })
}

const voyageOptions = ref([])
// 获取航次数据
const getVoyageReg = () => {
  voyageReg({ baseURL: VoyageSocketUrl.value }).then(res => {
    voyageOptions.value = res.array
    console.log(res.array)
  })
}

onMounted(() => {
  getParamsList()

  if (rescueId) {
    getDetail()
  }
})
</script>

<style lang="scss" scoped>
.container {
  padding: 20px;
  color: #242424;

  .title {
    font-weight: bold;
    color: #333;
  }

  .info {
    display: inline-block;
    padding: 0 20px 10px;
    border-bottom: 2px solid #409eff;
  }

  .ruleForm {
    margin-top: 20px;

    .btn-bar {
      display: flex;
      justify-content: center;
    }
  }
}

.upload-btn {
  text-align: right;
}
</style>
