<!-- 文档管理-编辑 -->
<script lang="ts" setup name="DocumentEdit">
import type { FormInstance, FormRules, UploadUserFile } from 'element-plus'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import tableList from './tableList.vue'
import { uploadApi } from '@/api/system/notice'
import showPhoto from '@/views/tested/device/info/components/showPhotoSinge.vue'
import { getDictByCode } from '@/api/system/dict'
import useUserStore from '@/store/modules/user'
import { getUserDept } from '@/api/system/user'
import { addDocument, detailDocument, updateDocument } from '@/api/eqpt/document/index'
const $route = useRoute()
const $router = useRouter()
const userStore = useUserStore()
const ruleFormRef = ref<FormInstance>() // from组件
const tableRef = ref()
// 显示标题
const textMap: { [key: string]: string } = {
  update: '编辑',
  create: '新增',
  detail: '详情',
}
// 对话框类型：create,update
const dialogStatus = ref('create')
const list = ref()
const ruleForm = ref({
  attachment: '',
  createTime: '',
  createUserId: '',
  createUserName: '',
  fileName: '',
  fileNo: '',
  fileType: '',
  id: '',
  implementationStatus: '',
  remark: '',
  updateTime: '',
}) // 表单
const rules = ref<FormRules>({
  fileName: [{ required: true, message: '文件名称必填', trigger: ['blur', 'change'] }],
  fileNo: [{ required: true, message: '文件号必填', trigger: ['blur', 'change'] }],
  fileType: [{ required: true, message: '文件类别必选', trigger: ['blur', 'change'] }],
  implementationStatus: [{ required: true, message: '实施状态必选', trigger: ['blur', 'change'] }],
  // remark: [{ required: true, message: '备注必填', trigger: ['blur', 'change'] }],
  attachment: [{ required: true, message: '文件附件需上传', trigger: ['blur', 'change'] }],
}) // 表单验证规则
// 弹窗初始化
const initDialog = () => {
  dialogStatus.value = $route.params.type as string
  ruleFormRef.value?.resetFields()
  if ($route.params.type !== 'create') {
    const data = JSON.parse($route.query.row as string)
    ruleForm.value = data
    // 获取变更记录详情
    detailDocument(data.id).then((res) => {
      list.value = res.data
    })
  }
  if ($route.params.type === 'create' || $route.params.type === 'update') {
    ruleForm.value.createTime = dayjs().format('YYYY-MM-DD HH:mm:ss') // 创建时间
    ruleForm.value.createUserId = userStore.id
    ruleForm.value.createUserName = userStore.name
  }
}
onMounted(() => {
  initDialog()
})
// 获取字典下拉
const fileTypeList = ref<{ id: string; value: string; name: string }[]>() // 文件类别
const statusList = ref<{ id: string; value: string; name: string }[]>() // 实施状态
const fetchListData = () => {
  // 文件类别
  getDictByCode('eqptFileType').then((res) => {
    fileTypeList.value = res.data
  })
  getDictByCode('eqptImplementStatus').then((res) => {
    statusList.value = res.data
  })
}
fetchListData()
// 关闭弹窗
const close = () => {
  $router.back()
}
// 新增
const add = () => {
  addDocument(ruleForm.value).then((res) => {
    ElMessage.success('新增成功')
    close()
  })
}
// 编辑
const update = () => {
  updateDocument(ruleForm.value).then((res) => {
    ElMessage.success('修改成功')
    close()
  })
}
// 保存
const saveForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) { return }
  await formEl.validate((valid, fields) => {
    if (valid) {
      ElMessageBox.confirm(
        '确认保存吗？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then((res) => {
        if (dialogStatus.value === 'create') {
          add()
        }
        else {
          update()
        }
      })
    }
  })
}
// 取消
const resetForm = (formEl: FormInstance | undefined) => {
  formEl?.resetFields()
  close()
}
const fileRef = ref() // 文件上传input
const onFileChange = (event: any) => {
  if (event.target.files?.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    const loading = ElLoading.service({
      lock: true,
      background: 'rgba(255, 255, 255, 0.8)',
    })
    fd.append('multipartFile', event.target.files[0])
    uploadApi(fd).then((res) => {
      if (res.code === 200) {
        ruleFormRef.value?.clearValidate('attachment')
        ruleForm.value.attachment = res.data[0]
        // 重置当前验证
        ElMessage.success('文件上传成功')
        fileRef.value.value = ''
        loading.close()
      }
      else {
        ElMessage.error(res.message)
        loading.close()
      }
    })
  }
}
const upload = () => {
  fileRef.value.click()
}
</script>

<template>
  <app-container style="overflow: hidden;">
    <approval-dialog ref="approvalDialogRef" @on-success="() => { $router.back() }" />
    <detail-page :title="`文档管理-${textMap[dialogStatus]}`">
      <template #btns>
        <el-button v-if="!$route.path.includes('detail')" type="primary" @click="saveForm(ruleFormRef)">
          保存
        </el-button>
        <el-button type="info" @click="resetForm(ruleFormRef)">
          关闭
        </el-button>
      </template>
    </detail-page>
    <detail-block-com>
      <el-form ref="ruleFormRef" :model="ruleForm" :class="$route.path.includes('detail') ? 'isDetail' : ''" :rules="rules" label-position="right" label-width="120px" class="form" :disabled="$route.path.includes('detail')">
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="文件号" prop="fileNo">
              <el-input v-model.trim="ruleForm.fileNo" placeholder="文件号" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="文件名称" prop="fileName">
              <el-input v-model.trim="ruleForm.fileName" placeholder="文件名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建人">
              <el-input v-model.trim="ruleForm.createUserName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建时间">
              <el-input v-model.trim="ruleForm.createTime" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="文件类别" prop="fileType">
              <el-select v-model="ruleForm.fileType" placeholder="文件类别" style="width: 100%;">
                <el-option v-for="item in fileTypeList" :key="item.id" :label="item.name" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="实施状态" prop="implementationStatus">
              <el-select v-model="ruleForm.implementationStatus" placeholder="实施状态" style="width: 100%;">
                <el-option v-for="item in statusList" :key="item.id" :label="item.name" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="12">
            <el-form-item label="文件附件" prop="attachment">
              <!-- 上传组件 -->
              <input ref="fileRef" style="display: none;" type="file" accept="application/msword,application/pdf" @change="onFileChange">
              <show-photo :minio-file-name="ruleForm.attachment" />
              <el-button v-if="!$route.path.includes('detail')" type="primary" @click="upload()">
                {{ '上传' }}
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model.trim="ruleForm.remark" placeholder="备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-block-com>
    <detail-block-com v-if="!$route.path.includes('create')">
      <table-list ref="tableRef" :data="list" :status="dialogStatus" />
    </detail-block-com>
  </app-container>
</template>

<style lang="scss" scoped>
// 详情页面隐藏小红点
.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;
    }
  }
}
</style>
