<!-- 新增或详情 -->
<script lang="ts" setup name="addNotice">
import type { FormInstance, FormRules, UploadUserFile } from 'element-plus'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import type { deptType } from '../file-interface'
import FilePreviewDialog from '@/components/filePreview/filePreviewDialog.vue'
import comTreeSelect from '@/views/system/user/selecTree.vue'
import { getUserList } from '@/api/system/user'
import useUserStore from '@/store/modules/user'
import { toTreeList } from '@/utils/structure'
import { getDeptTreeList } from '@/api/system/dept'
import { UploadFile, addFile, updateFile } from '@/api/measure/file'
import type { userType } from '@/views/system/user/user-interface'
import showPhoto from '@/views/system/tool/showPhoto.vue'
import type { fileResType } from '@/views/measure/file/file-interface'
import { getDictByCode } from '@/api/system/dict'
import { SCHEDULE } from '@/utils/scheduleDict'
import type { dictType } from '@/global'
const $route = useRoute()
const $router = useRouter()
const ruleFormRef = ref<FormInstance>() // from组件
const userInfo = useUserStore() // 当前用户信息
const title = ref('')
const routerName = ref('')
const ruleForm = reactive({
  fileNo: '', // 文件编号
  fileName: '', // 文件名称
  fileCode: '', // 文件号
  fileType: '', // 文件类别
  fileTypeName: '', // 文件类别名称
  publishTime: '', // 发布时间
  createUserId: '', // 创建人id
  effectiveTime: '', // 实施时间
  effectiveStatus: '', // 实施状态
  effectiveStatusName: '', // 实时状态名字
  remark: '', // 备注
  minioFileName: '', // 附件
  minioFilePdfName: '', // pdf附件
  id: '',
  formId: SCHEDULE.FILE_APPROVAL,
}) // 表单
const rules = ref<FormRules>({
  fileName: [{ required: true, message: '文件名称必填', trigger: 'blur' }],
  fileCode: [{ required: true, message: '文件号必填', trigger: 'blur' }],
  fileTypeName: [{ required: true, message: '文件类别必填', trigger: 'blur' }],
  fileType: [{ required: true, message: '文件类别必填', trigger: 'blur' }],
  publishTime: [{ required: true, message: '发布时间必填', trigger: 'blur' }],
  createUserId: [{ required: true, message: '创建人必填', trigger: 'blur' }],
  effectiveTime: [{ required: true, message: '实施时间必填', trigger: 'blur' }],
  minioFileName: [{ required: true, message: '附件必填', trigger: 'blur' }],
  effectiveStatus: [{ required: true, message: '实施状态必填', trigger: 'blur' }],
}) // 表单验证规则

// --------------------------------------------------字典----------------------------------------
const userList = ref<userType[]>([]) // 可使用人列表
const getuser = () => {
  getUserList({ offset: 1, limit: 99999 }).then((res) => {
    userList.value = res.data.rows
  })
} // 获取创建人列表
getuser()
const effectiveStatusList = ref<fileResType[]>([])
// 获取实施状态
getDictByCode('effectiveStatus').then((res) => {
  if (res.code === 200) {
    effectiveStatusList.value = res.data
  }
})

const qualityFileTypeList = ref<dictType[]>([]) // 文件类别列表
// 获取质量文件的文件类别
getDictByCode('fileType').then((res) => {
  qualityFileTypeList.value = []
  res.data.forEach((item: dictType) => {
    if (item.name === '质量手册' || item.name === '程序文件'
      || item.name === '质量记录' || item.name === '操作规程'
      || item.name === '作业指导书') {
      qualityFileTypeList.value.push(item)
    }
  })
})
// ---------------------------------------------------------------------------------------------
// 弹窗初始化
const initDialog = (row: any) => {
  ruleFormRef.value?.resetFields()
  routerName.value = row.routerName
  if (routerName.value !== '质量文件') {
    ruleForm.fileType = row.fileType
    ruleForm.fileTypeName = row.fileTypeName
  }
  title.value = row.title
  if (row.title === '新建') {
    // 默认发布人和发布单位
    ruleForm.createUserId = userInfo.$state.id
    ruleForm.publishTime = dayjs().format('YYYY-MM-DD')
    if (routerName.value !== '质量文件') {
      ruleForm.fileType = row.fileType
      ruleForm.fileTypeName = row.fileTypeName || routerName.value
    }
  }
  else if (row.title === '详情') {
    ruleForm.id = row.id
    ruleForm.createUserId = row.createUserId // 创建人
    ruleForm.fileNo = row.fileNo // 文件编号
    ruleForm.fileName = row.fileName // 文件名称
    ruleForm.fileCode = row.fileCode // 文件号
    ruleForm.effectiveTime = row.effectiveTime // 实施时间
    ruleForm.effectiveStatus = row.effectiveStatus // 实施状态
    ruleForm.effectiveStatusName = row.effectiveStatusName // 实施状态名称
    ruleForm.remark = row.remark // 备注
    ruleForm.publishTime = row.publishTime // 发布时间
    ruleForm.minioFileName = row.minioFileName // word文件
    ruleForm.minioFilePdfName = row.minioFilePdfName // pdf文件
    ruleForm.fileType = row.fileType // 文件类别
    ruleForm.fileTypeName = row.fileTypeName// 文件类别名称
    console.log('-0-0-xiaqing', ruleForm.fileType, row)
  }
}

// 关闭弹窗
const close = () => {
  $router.back()
}
// 保存
const saveForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) { return }
  await formEl.validate((valid, fields) => {
    if (valid) {
      ElMessageBox.confirm(
        '确认保存吗？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then((res) => {
        const loading = ElLoading.service({
          lock: true,
          text: '加载中...',
          background: 'rgba(255, 255, 255, 0.8)',
        })
        console.log('保存时的title', title.value)

        if (title.value === '新建') {
          addFile(ruleForm).then((res) => {
            ruleForm.fileNo = res.data.fileNo
            ruleForm.id = res.data.id
            ElMessage.success('保存成功')
            // title.value = '详情'
            close()
            loading.close()
          })
        }
        if (title.value === '编辑') {
          updateFile(ruleForm).then((res) => {
            ElMessage.success('保存成功')
            // title.value = '详情'
            close()
            loading.close()
          })
        }
      })
    }
  })
}

// 关闭
const resetForm = (formEl: FormInstance | undefined) => {
  formEl?.resetFields()
  close()
}

const fileRef = ref() // 文件上传input
const onFileChange = (event: any) => {
  if (routerName.value === '计量规程规范') {
    if (event.target.files[0].type !== 'application/pdf') {
      ElMessage.warning('请上传pdf文件格式')
      return
    }
  }
  else {
    if (event.target.files[0].type !== 'application/msword' && event.target.files[0].type !== 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
      ElMessage.warning('请上传doc、docx文件格式')
      return
    }
  }

  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])
    UploadFile(fd).then((res) => {
      if (res.code === 200) {
        ruleForm.minioFileName = res.data[0]
        // 重置当前验证
        ruleFormRef.value?.clearValidate('minioFileName')
        ElMessage.success('文件上传成功')
        loading.close()
      }
      else {
        ElMessage.error(res.message)
        loading.close()
      }
    })
  }
}
const upload = () => {
  fileRef.value.click()
}

// 文件类别选择事件
const changeFileType = (val: string) => {
  const index = qualityFileTypeList.value.findIndex(item => item.value === val)
  if (index !== -1) {
    ruleForm.fileTypeName = qualityFileTypeList.value[index].name
  }
}

// 实施状态事件
const changeEffectiveStatus = (val: string) => {
  const index = effectiveStatusList.value.findIndex(item => item.value === val)
  if (index !== -1) {
    ruleForm.effectiveStatusName = effectiveStatusList.value[index].name
  }
}

// 点击编辑按钮
const handleClickEdit = () => {
  title.value = '编辑'
  console.log('title', title.value)
}
const refFilePreviewDlg = ref()
// 点击文件名称
const handleClickFollowLink = (minioFilePdfName: string) => {
  console.log('点击文件名称', minioFilePdfName)
  if (minioFilePdfName.lastIndexOf('.pdf') > 0) {
    refFilePreviewDlg.value.initDialog(minioFilePdfName)
  }
}

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

<template>
  <app-container style="overflow: hidden;">
    <detail-page :title="`${routerName}-${title}`">
      <template #btns>
        <el-button v-if="title !== '详情'" type="primary" @click="saveForm(ruleFormRef)">
          保存
        </el-button>
        <!-- 只有创建人可编辑 -->
        <el-button v-if="title === '详情' && ruleForm.createUserId === userInfo.$state.id" type="primary" @click="handleClickEdit">
          编辑
        </el-button>
        <el-button type="info" @click="resetForm(ruleFormRef)">
          关闭
        </el-button>
      </template>

      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-position="right" label-width="110px" class="form" :class="[title === '详情' ? 'isDetail' : '']">
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="文件编号" prop="fileNo">
              <el-input v-model.trim="ruleForm.fileNo" placeholder="系统自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="文件名称" prop="fileName">
              <el-input v-model.trim="ruleForm.fileName" :placeholder="title === '详情' ? ' ' : '请输入文件名称'" :disabled="title === '详情'" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="文件号" prop="fileCode">
              <el-input v-model.trim="ruleForm.fileCode" :placeholder="title === '详情' ? ' ' : '请输入文件号'" :disabled="title === '详情'" />
            </el-form-item>
          </el-col>
          <el-col v-if="routerName !== '质量文件'" :span="6">
            <el-form-item label="文件类别" prop="fileTypeName">
              <el-input v-model.trim="ruleForm.fileTypeName" disabled />
            </el-form-item>
          </el-col>
          <el-col v-if="routerName === '质量文件'" :span="6">
            <el-form-item label="文件类别" prop="fileType">
              <el-select v-model="ruleForm.fileType" :placeholder="title === '详情' ? ' ' : '请选择文件类别'" clearable :disabled="title === '详情'" @change="changeFileType">
                <el-option
                  v-for="item in qualityFileTypeList"
                  :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="publishTime">
              <el-date-picker
                v-model="ruleForm.publishTime" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD" disabled
                :placeholder="title === '详情' ? ' ' : '请选择发布时间'"
                class="normal-date"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建人" prop="createUserId">
              <el-select v-model="ruleForm.createUserId" :placeholder="title === '详情' ? ' ' : '请选择创建人'" disabled style="width: 100%;">
                <el-option v-for="item in userList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="实施时间" prop="effectiveTime">
              <el-date-picker
                v-model="ruleForm.effectiveTime"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                :disabled="title === '详情'"
                :placeholder="title === '详情' ? ' ' : '请选择实施时间'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="实施状态" prop="effectiveStatus">
              <el-select v-model="ruleForm.effectiveStatus" :placeholder="title === '详情' ? ' ' : '请选择实施状态'" clearable :disabled="title === '详情'" @change="changeEffectiveStatus">
                <el-option
                  v-for="item in effectiveStatusList"
                  :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="12">
            <el-form-item label="备注:" prop="remark">
              <el-input
                v-model="ruleForm.remark"
                class="full-width-input"
                autosize
                type="textarea"
                :disabled="title === '详情'"
                :placeholder="title === '详情' ? ' ' : '请输入备注'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col v-if="routerName === '计量规程规范'" :span="24">
            <el-form-item label="附件(pdf):" prop="minioFileName">
              <input v-show="title === ''" ref="fileRef" multiple type="file" @change="onFileChange">
              <span v-if="title === '详情' && !ruleForm.minioFileName">无</span>
              <div v-else style="display: flex;">
                <show-photo :minio-file-name="ruleForm.minioFileName || ''" style="display: inline-block;" />
              </div>
              <el-button v-if="title !== '详情'" type="primary" :disabled="title === '详情'" @click="upload">
                {{ ruleForm.minioFileName ? '更换' : '上传' }}
              </el-button>
            </el-form-item>
          </el-col>
          <el-col v-else :span="24">
            <el-form-item label="附件(word):" prop="minioFileName">
              <input v-show="title === ''" ref="fileRef" multiple type="file" @change="onFileChange">
              <span v-if="title === '详情' && !ruleForm.minioFileName">无</span>
              <div v-else style="display: flex;">
                <show-photo :minio-file-name="ruleForm.minioFileName || ''" style="display: inline-block;" />
              </div>
              <el-button v-if="title !== '详情'" type="primary" :disabled="title === '详情'" @click="upload">
                {{ ruleForm.minioFileName ? '更换' : '上传' }}
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item v-if="ruleForm.minioFilePdfName" label="附件(pdf):" prop="minioFilePdfName">
              <span v-if="title === '详情' && !ruleForm.minioFilePdfName">无</span>
              <!-- <div v-if="ruleForm.minioFilePdfName" style="display: flex;">
                <show-photo :minio-file-name="ruleForm.minioFilePdfName" style="display: inline-block;" />
              </div> -->
              <span v-if="ruleForm.minioFilePdfName" class="minioFilePdfName" @click="handleClickFollowLink(ruleForm.minioFilePdfName)">{{ ruleForm.minioFilePdfName }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-page>
  </app-container>
  <file-preview-dialog ref="refFilePreviewDlg" />
</template>

<style lang="scss" scoped>
.minioFilePdfName {
  color: #3d7eff;
  cursor: pointer;
  text-decoration: underline;
}
</style>
