<!-- 计量资料详情 -->
<script name="TechnologyDataDetail" lang="ts" setup>
import { ElLoading, ElMessage, ElMessageBox, dayjs } from 'element-plus'
import type { IFileInfo } from './data-interface'
import useUserStore from '@/store/modules/user'
import { UploadFile } from '@/api/file'
import { addFileMeter, updateFileMeter } from '@/api/resource/fileTechnology'
import { getPhotoUrl } from '@/api/system/tool'

// 从路由中传过来的参数
const type = ref<string>('')
const id = ref<string>('')

// 获取用户信息
const userInfo = useUserStore()
const route = useRoute()
const router = useRouter()
const title = ref('')

const basicFormRef = ref()

const meterFileInfo = ref<IFileInfo>({
  id: '',
  fileNo: '',
  fileName: '',
  versionNo: '',
  createUserId: '',
  createUserName: '',
  createTime: '',
  remark: '',
  file: '',
})

const meterFileRules = ref({
  fileNo: [{ required: true, message: '文件编号不能为空', trigger: 'blur' }],
  fileName: [{ required: true, message: '文件名称不能为空', trigger: 'blur' }],
  versionNo: [{ required: true, message: '版本号不能为空', trigger: 'blur' }],
  file: [{ required: true, message: '文件附件不能为空，请选择一个文件上传', trigger: 'blur' }],
}) // 表单验证规则

const minioFileUrl = ref<string>('')

// 逻辑

const resetForm = () => {
  sessionStorage.removeItem('meterFileInfo') // 返回列表时 将缓存中的数据删除
  router.go(-1)
}

// 添加
const saveFileDataForm = () => {
  // 将创建时间改为提交的时间
  meterFileInfo.value.createTime = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')
  addFileMeter(meterFileInfo.value).then((res) => {
    if (res.code === 200) {
      // 提示保存成功
      ElMessage.success('保存成功')
      type.value = 'detail'
      title.value = '计量资料（详情）'
    }
    else {
      // 提示失败信息
      ElMessage.error(`保存失败：${res.message}`)
    }
  })
}
// 编辑
const updateFileDataById = () => {
  updateFileMeter(meterFileInfo.value).then((res) => {
    if (res.code === 200) {
      // 提示保存成功
      ElMessage.success('保存成功')
      type.value = 'detail'
      title.value = '计量资料（详情）'
    }
    else {
      // 提示失败信息
      ElMessage.error(`保存失败：${res.message}`)
    }
  })
}

// 保存
const saveForm = async () => {
  if (!basicFormRef) { return }

  await basicFormRef.value.validate((valid: boolean, fields: any) => {
    if (valid === true) {
      ElMessageBox.confirm(
        '确认保存吗？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then(() => {
        if (type.value === 'create') {
          saveFileDataForm()
        }
        else if (type.value === 'update') {
          updateFileDataById()
        }
      })
    }
  })
}

// 上传请求
const uploadQuarterlyEvaluateFile: any = (file: any) => {
  const fd = new FormData()
  fd.append('multipartFile', file.file)
  const loading = ElLoading.service({
    lock: true,
    background: 'rgba(255, 255, 255, 0.8)',
  })
  UploadFile(fd).then((res) => {
    if (res.code === 200) {
      ElMessage.success('上传成功')
      meterFileInfo.value.file = res.data[0]
      loading.close()

      basicFormRef.value.validateField('file', () => {})
    }
  }).catch(() => {
    loading.close()
    ElMessage.error('上传失败')
  })
}

// 预览文件
const previewFileSystem = (url: string) => {
  console.log(url)
}

const initDialog = (params: any) => {
  // 从路由中获取参数
  type.value = params.type
  id.value = params.id !== undefined ? params.id : ''

  switch (params.type) {
    case 'create' :
      title.value = '计量资料（新增）'

      // 创建人和创建时间设置默认值
      meterFileInfo.value.createUserId = userInfo.id
      meterFileInfo.value.createUserName = userInfo.name
      meterFileInfo.value.createTime = dayjs().format('YYYY-MM-DD HH:mm:ss')

      break
    case 'update':
      title.value = '计量资料（编辑）'
      id.value = params.id

      meterFileInfo.value = JSON.parse(sessionStorage.getItem('meterFileInfo')!)

      break
    case 'detail':
      title.value = '计量资料（详情）'
      id.value = params.id

      meterFileInfo.value = JSON.parse(sessionStorage.getItem('meterFileInfo')!)

      break
    default:
      title.value = ''
      break
  }
}

watch(() => meterFileInfo.value.file, (newVal) => {
  if (newVal !== '') {
    getPhotoUrl(newVal).then((res) => {
      if (res.code === 200) {
        minioFileUrl.value = res.data
      }
    })
  }
})

onMounted(async () => {
  initDialog(route.query)
})
</script>

<template>
  <app-container>
    <detail-page :title="`${title}`">
      <template #btns>
        <el-button v-if="type !== 'detail'" type="primary" @click="saveForm()">
          保存
        </el-button>
        <el-button type="info" @click="resetForm()">
          关闭
        </el-button>
      </template>

      <el-form ref="basicFormRef" :model="meterFileInfo" :rules="meterFileRules" label-position="right" label-width="110px" border stripe>
        <el-row :gutter="24">
          <!-- 第一行 第一列 -->
          <el-col :span="6">
            <el-form-item label="文件编号" prop="fileNo">
              <el-input v-model="meterFileInfo.fileNo" placeholder="请输入文件编号" tabindex="1" :clearable="true" :disabled="type === 'detail'" />
            </el-form-item>

            <el-form-item label="创建人">
              <el-input v-model="meterFileInfo.createUserName" :disabled="true" />
            </el-form-item>
          </el-col>

          <!-- 第一行 第二列 -->
          <el-col :span="6">
            <el-form-item label="文件名称" prop="fileName">
              <el-input v-model="meterFileInfo.fileName" :clearable="true" placeholder="请输入文件名称" tabindex="2" :disabled="type === 'detail'" />
            </el-form-item>

            <el-form-item label="创建时间">
              <el-input v-model="meterFileInfo.createTime" :disabled="true" />
            </el-form-item>
          </el-col>

          <!-- 第一行 第三列 -->
          <el-col :span="6">
            <el-form-item label="版本号" prop="versionNo">
              <el-input v-model="meterFileInfo.versionNo" :clearable="true" placeholder="请输入文件版本号" tabindex="3" :disabled="type === 'detail'" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行 -->
        <el-row :gutter="24">
          <el-col :span="18">
            <el-form-item label="备注">
              <el-input v-model="meterFileInfo.remark" placeholder="请输入备注信息" tabindex="4" type="textarea" :clearable="true" :disabled="type === 'detail'" :rows="2" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第四行 -->
        <el-row :gutter="24">
          <el-col :span="20">
            <el-form-item label="文件附件" prop="file">
              <el-input v-model="meterFileInfo.file" type="hidden" />
              <!-- <el-link :href="minioFileUrl" :underline="false" target="_blank" @click="previewFileSystem(minioFileUrl)"> -->
              {{ meterFileInfo.file }}
              <!-- </el-link> -->

              <el-upload
                :show-file-list="false"
                :http-request="uploadQuarterlyEvaluateFile"
                style="width: 50%; margin-left: 20px;"
              >
                <el-button v-if="type !== 'detail'" type="primary">
                  <template v-if="meterFileInfo.file !== ''">
                    替换
                  </template>
                  <template v-else>
                    上传
                  </template>
                </el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-page>
  </app-container>
</template>

