<!-- 体系文件详情 -->
<script name="SysDocDetail" lang="ts" setup>
import { ElLoading, ElMessage, ElMessageBox, dayjs } from 'element-plus'
import type { IFileInfo } from './sysDoc-interface'
import useUserStore from '@/store/modules/user'
import { UploadFile } from '@/api/file'
import { addFileSystem, updateFileSystem } from '@/api/resource/fileSystem'
import { getPhotoUrl } from '@/api/system/tool'
import type { IDictType } from '@/commonInterface/resource-interface'

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

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

const basicFormRef = ref()

// 字典值
const fileTypeDict = ref<Array<IDictType>>([])

const sysFileInfo = ref<IFileInfo>({
  id: '',
  fileNo: '',
  fileName: '',
  fileDistributeNo: '',
  fileType: '',
  fileTypeName: '',
  history: '0',
  versionNo: '',
  effectiveDate: '',
  createUserId: '',
  createUserName: '',
  createTime: '',
  changeFormId: '',
  remark: '',
  file: '',
})

const sysFileRules = ref({
  fileNo: [{ required: true, message: '文件编号不能为空', trigger: 'blur' }],
  fileName: [{ required: true, message: '文件名称不能为空', trigger: 'blur' }],
  fileType: [{ required: true, message: '文件类别不能为空，请选择', trigger: ['change', 'blur'] }],
  fileDistributeNo: [{ required: true, message: '文件发放编号不能为空', trigger: 'blur' }],
  versionNo: [{ required: true, message: '版本号不能为空', trigger: 'blur' }],
  effectiveDate: [{ required: true, message: '实施时间不能为空，请选择', trigger: 'blur' }],
  file: [{ required: true, message: '文件附件不能为空，请选择一个文件上传', trigger: 'blur' }],
}) // 表单验证规则

const minioFileUrl = ref<string>('')

// 逻辑

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

// 添加
const saveFileSystemForm = () => {
  // 将创建时间改为提交的时间
  sysFileInfo.value.createTime = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')
  addFileSystem(sysFileInfo.value).then((res) => {
    if (res.code === 200) {
      // 提示保存成功
      ElMessage.success('保存成功')
      type.value = 'detail'
      title.value = '体系文件（详情）'
    }
    else {
      // 提示失败信息
      ElMessage.error(`保存失败：${res.message}`)
    }
  })
}
// 编辑
const updateFileSystemById = () => {
  updateFileSystem(sysFileInfo.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') {
          saveFileSystemForm()
        }
        else if (type.value === 'update') {
          updateFileSystemById()
        }
      })
    }
  })
}

// 上传请求
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('上传成功')
      sysFileInfo.value.file = res.data[0]
      loading.close()

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

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

// 弹出选择文件更改单窗口
const selectChangeForm = () => {

}

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

  switch (params.type) {
    case 'create' :
      title.value = '体系文件（新增）'

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

      break
    case 'update':
      title.value = '体系文件（编辑）'
      id.value = params.id

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

      break
    case 'detail':
      title.value = '体系文件（详情）'
      id.value = params.id

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

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

// 监听 显示中文 立即监听
watch(() => sysFileInfo.value.fileType, (newVal) => {
  if (fileTypeDict.value.length === 0) {
    fileTypeDict.value = JSON.parse(sessionStorage.getItem('bizFileType')!)
  }
  const targetList = fileTypeDict.value.filter(item => item.value === newVal)
  if (targetList.length > 0) {
    sysFileInfo.value.fileTypeName = targetList[0].name
  }
  else {
    sysFileInfo.value.fileTypeName = ''
  }
}, { immediate: true })

watch(() => sysFileInfo.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="sysFileInfo" :rules="sysFileRules" 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="sysFileInfo.fileNo" placeholder="请输入文件编号" tabindex="1" :clearable="true" :disabled="type === 'detail'" />
            </el-form-item>

            <el-form-item label="文件类别" prop="fileType">
              <el-select v-model="sysFileInfo.fileType" placeholder="请选择文件类别" tabindex="5" style="width: 100%;" :clearable="true" :disabled="type === 'detail'">
                <el-option v-for="dict in fileTypeDict" :key="dict.id" :label="dict.name" :value="dict.value" />
              </el-select>
              <el-input v-model="sysFileInfo.fileTypeName" type="hidden" />
            </el-form-item>
          </el-col>

          <!-- 第一行 第二列 -->
          <el-col :span="6">
            <el-form-item label="文件发放编号" prop="fileDistributeNo">
              <el-input v-model="sysFileInfo.fileDistributeNo" :clearable="true" placeholder="请输入文件发放编号" tabindex="2" :disabled="type === 'detail'" />
            </el-form-item>

            <el-form-item label="实施时间" prop="effectiveDate">
              <el-date-picker
                v-model="sysFileInfo.effectiveDate" type="date"
                format="YYYY-MM-DD" value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择实施时间" :disabled="type === 'detail'" style="width: 100%;"
                tabindex="6"
              />
            </el-form-item>
          </el-col>

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

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

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

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

        <!-- 第二行 -->
        <el-row v-if="type === 'update'" :gutter="24">
          <!-- 第一列 -->
          <el-col :span="12">
            <el-form-item label="文件更改申请单">
              <el-input v-model="sysFileInfo.changeFormId" placeholder="请选择文件更改申请单" :clearable="true">
                <template #append>
                  <el-button size="small" @click="selectChangeForm">
                    选择
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行 -->
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="备注">
              <el-input v-model="sysFileInfo.remark" placeholder="请输入备注信息" tabindex="7" 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="sysFileInfo.file" type="hidden" />
              <!-- <el-link :href="minioFileUrl" :underline="false" target="_blank" @click="previewFileSystem(minioFileUrl)"> -->
              {{ sysFileInfo.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="sysFileInfo.file !== ''">
                    替换
                  </template>
                  <template v-else>
                    上传
                  </template>
                </el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-page>
  </app-container>
</template>
