<!-- 新增文件配置管理弹窗 -->
<script lang="ts" setup name="addConfiguration">
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import showPhoto from '../showPhoto.vue'
import type { dictType } from '../tool_interface'
import { getDictByCode } from '@/api/system/dict'
import { uploadApi } from '@/api/system/notice'
import { addeFileListPage, updateFileListPage } from '@/api/system/tool'
const emits = defineEmits(['resetData'])
const ruleFormRef = ref<FormInstance>() // from组件
const updateTime = ref('')
const ruleForm = ref<any>({
  businessDownloadType: '', // 业务类型(字典)
  createTime: '',
  createUser: '',
  descn: '', // 	描述备注
  downloadNo: '', // 文件编号
  fileName: '', // 文件名称
  fileType: '',
  id: '',
  minioFileName: '', // 附件文件名
  moduleName: '', // 模块名称
  updateTime: '',
  updateUser: '',
  versionName: '',
}) // 表单
const resetForm1 = () => {
  ruleForm.value = {
    businessDownloadType: '', // 业务类型(字典)
    createTime: '',
    createUser: '',
    descn: '', // 	描述备注
    downloadNo: '', // 文件编号
    fileName: '', // 文件名称
    fileType: '',
    id: '',
    minioFileName: '', // 附件文件名
    moduleName: '', // 模块名称
    updateTime: '',
    updateUser: '',
    versionName: '',
  }
}
const title = ref('')
const rules = ref<FormRules>({
  businessDownloadType: [{ required: true, message: '请选择业务类型', trigger: 'blur' }],
  descn: [{ required: true, message: '请输入描述备注', trigger: 'blur' }],
  fileName: [{ required: true, message: '请输入文件名称', trigger: 'blur' }],
  fileType: [{ required: true, message: '请选择文件类型', trigger: 'blur' }],
  minioFileName: [{ required: true, message: '请上传附件', trigger: 'blur' }],
  moduleName: [{ required: true, message: '请输入模块名称', trigger: 'blur' }],
  versionName: [{ required: true, message: '请输入版本号', trigger: 'blur' }],
}) // 表单验证规则
const dialogVisible = ref<boolean>(false) // 弹窗显示
// 弹窗初始化
const initDialog = (row: any) => {
  title.value = row.title as string
  dialogVisible.value = true
  resetForm1()
  if (row.title === '新增') {
    // 新增
    ruleFormRef.value?.resetFields()
    updateTime.value = dayjs().format('YYYY-MM-DD HH:mm:ss')
  }
  // 修改 详情
  else {
    ruleForm.value = row
    if (!ruleForm.value.versionName) {
      ruleForm.value.versionName = ''
    }
    updateTime.value = row.updateTime
  }
}
defineExpose({ initDialog })
// 关闭弹窗
const close = () => {
  dialogVisible.value = false
  emits('resetData')
}

// 获取文件类型
const fileTypeList = ref<any>([])
const getFileType = () => {
  getDictByCode('configFileType').then((res) => {
    fileTypeList.value = res.data
  })
}
getFileType()
// 判断文件类型与上传文件是否一致
const checkFile = (type: string) => {
  const data = fileTypeList.value.filter((item: any) => item.value === ruleForm.value.fileType)
  if (data.length) {
    const val = data[0].name
    const fileName = type
    if (val !== fileName) {
      ElMessage.warning('上传文件与所选文件类型不一致')
      return false
    }
  }
  return true
}
// 提交
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) { return }
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (title.value === '新增') {
        // if (!checkFile()) {
        //   return
        // }
        addeFileListPage(ruleForm.value).then((res) => {
          ElMessage({
            type: 'success',
            message: '添加成功',
          })
          close()
        })
      }
      else {
        if (!checkFile()) {
          return
        }
        updateFileListPage(ruleForm.value).then((res) => {
          ElMessage({
            type: 'success',
            message: '修改成功',
          })
          close()
        })
      }
    }
  })
}
const businessTypeList = ref<dictType[]>([])// 获取业务类型
const moduleNameList = ref<dictType[]>([])// 模块名称
const getDict = () => {
  getDictByCode('businessDownloadType').then((res) => {
    businessTypeList.value = res.data
  })
  getDictByCode('downloadTemplateModule').then((res) => {
    moduleNameList.value = res.data
  })
}
getDict()
// 取消
const resetForm = (formEl: FormInstance | undefined) => {
  formEl?.resetFields()
  dialogVisible.value = false
  emits('resetData')
}
const fileRef = ref() // 文件上传input
const onFileChange = (event: any) => {
  // 原生上传
  // console.log(event.target.files)
  if (event.target.files?.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    fd.append('multipartFile', event.target.files[0])
    const type = event.target.files[0].name.split('.')[event.target.files[0].name.split('.').length - 1]
    if (!checkFile(type)) {
      fileRef.value.value = ''
      return
    }
    uploadApi(fd).then((res) => {
      if (res.code === 200) {
        ruleFormRef.value?.clearValidate('minioFileName')
        ruleForm.value.minioFileName = res.data[0]
        fileRef.value.value = ''
        ElMessage.success('上传成功')
      }
      else {
        ElMessage.error(res.message)
      }
    })
  }
}
const upload = () => {
  fileRef.value.click()
}
// 判断是否选择apk
const isAPK = computed(() => {
  const tempValue = fileTypeList.value.filter((item: any) => item.value === ruleForm.value.fileType)
  if (tempValue.length) {
    return fileTypeList.value.filter((item: any) => item.value === ruleForm.value.fileType)[0].name === 'apk' || false
  }
})
</script>

<template>
  <el-dialog v-if="dialogVisible" v-model="dialogVisible" :title="title" width="65%" append-to-body class="container" @close="resetForm">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-position="right" label-width="110px" :class="[title === '详情' ? 'isDetail' : '']">
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="文件编号">
            <el-input v-model="ruleForm.downloadNo" disabled placeholder="系统自动生成" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="模块名称" prop="moduleName">
            <el-select v-model="ruleForm.moduleName" style="width: 100%;" :disabled="title === '详情'" :placeholder="title === '详情' ? '' : '请选择模块名称'">
              <el-option v-for="item in moduleNameList" :key="item.id" :label="item.name" :value="item.name" />
            </el-select>
            <!-- <el-input v-model="ruleForm.moduleName" :disabled="title === '详情'" :placeholder="title === '详情' ? '' : '请输入模块名称'" /> -->
          </el-form-item>
        </el-col>
        <!-- <el-col :span="6">
          <el-form-item label="创建人" prop="updateUser">
            <el-input v-model="ruleForm.updateUser" disabled />
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="创建时间" prop="updateTime">
            <el-date-picker
              v-model="updateTime"
              disabled
              type="datetime"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="业务类型" prop="businessDownloadType">
            <el-select v-model="ruleForm.businessDownloadType" style="width: 100%;" :disabled="title === '详情'" :placeholder="title === '详情' ? '' : '请选择业务类型'">
              <el-option v-for="item in businessTypeList" :key="item.id" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="文件名称" prop="fileName">
            <el-input v-model="ruleForm.fileName" :disabled="title === '详情'" :placeholder="title === '详情' ? '' : '请输入文件名称'" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="文件类型" prop="fileType">
            <el-select v-model="ruleForm.fileType" :disabled="title === '详情'" :placeholder="title === '详情' ? '' : '请选择文件类型'">
              <el-option v-for="item in fileTypeList" :key="item.id" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="16">
          <el-form-item label="描述备注" prop="descn">
            <el-input v-model="ruleForm.descn" type="textarea" autosize :disabled="title === '详情'" :placeholder="title === '详情' ? '' : '请输入描述备注'" />
          </el-form-item>
        </el-col>
        <el-col v-if="isAPK" :span="12">
          <el-form-item label="版本号" prop="versionName">
            <el-input v-model="ruleForm.versionName" :disabled="title === '详情'" :placeholder="title === '详情' ? '' : '请输入版本号'" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="24">
          <el-form-item label="模板附件" prop="minioFileName">
            <show-photo :minio-file-name="ruleForm.minioFileName" width="100%" height="125px" />
            <el-button v-if="title !== '详情'" type="primary" :disabled="title === '详情'" :style="{ 'margin-left': ruleForm.minioFileName === '' ? '0px' : '20px' }" @click="upload">
              {{ ruleForm.minioFileName === '' ? '上传' : '更换附件' }}
            </el-button>
            <input v-show="title === '123'" ref="fileRef" type="file" @change="onFileChange">
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer footer">
        <el-button v-if="title !== '详情'" type="primary" @click="submitForm(ruleFormRef)">
          发布
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">
          关闭
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.container {
  .isDetail {
    ::v-deep {
      .el-form-item.is-required:not(.is-no-asterisk) .el-form-item__label-wrap > .el-form-item__label::before,
      .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label::before {
        content: "";
        display: none;
      }
    }
  }

  .center {
    display: flex;
    align-items: flex-end;
  }
}
</style>
