<!-- 印章管理登记详情 -->
<script name="SealInfoDetail" lang="ts" setup>
import type { UploadProps } from 'element-plus'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import FilterSysUser from '../../person/register/filterSysUser.vue'
import type { IDictType, ISealInfo } from './seal-info'
import { UploadFile } from '@/api/file'
import { addSealInfo, updateSealInfo } from '@/api/resource/seal'
import { getPhotoUrl } from '@/api/system/tool'

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

const route = useRoute()
const router = useRouter()
const title = ref('')

const basicFormRef = ref()
const refFilterDialog = ref()

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

const sealInfo = ref<ISealInfo>({
  id: '',
  sealNo: '',
  sealName: '',
  sealType: '',
  sealTypeName: '',
  status: '',
  statusName: '',
  applyTime: '',
  abandonTime: '',
  ratifyTime: '',
  createTime: '',
  approverId: '',
  approverName: '',
  minioFileName: '',
  minioFileUrl: '',
})

const sealInfoRules = ref({
  sealNo: [{ required: true, message: '印章编号不能为空', trigger: 'blur' }],
  sealName: [{ required: true, message: '印章名称不能为空', trigger: 'blur' }],
  sealType: [{ required: true, message: '印章类型不能为空，请选择', trigger: ['blur', 'change'] }],
  approverId: [{ required: true, message: '批准人不能为空', trigger: ['blur', 'change'] }],
  applyTime: [{ required: true, message: '申请时间不能为空，请选择', trigger: 'blur' }],
  ratifyTime: [{ required: true, message: '批准时间不能为空，请选择', trigger: 'blur' }],
  status: [{ required: true, message: '在用状态不能为空，请选择', trigger: ['blur', 'change'] }],
  minioFileName: [{ required: true, message: '图形不能为空，请选择一个文件上传', trigger: 'blur' }],
}) // 表单验证规则

const minioFileUrl = ref<string>('')

// 逻辑

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

// 添加
const saveSealInfoForm = () => {
  // 将创建时间改为提交的时间
  sealInfo.value.createTime = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')
  addSealInfo(sealInfo.value).then((res) => {
    if (res.code === 200) {
      // 提示保存成功
      ElMessage.success('保存成功')
      type.value = 'detail'
      title.value = '印章管理登记（详情）'
    }
    else {
      // 提示失败信息
      ElMessage.error(`保存失败：${res.message}`)
    }
  })
}
// 编辑
const updateSealInfoById = () => {
  updateSealInfo(sealInfo.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') {
          saveSealInfoForm()
        }
        else if (type.value === 'update') {
          updateSealInfoById()
        }
      })
    }
  })
}

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

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

// 上传之前的验证
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' && rawFile.type !== 'image/jpg') {
    ElMessage.error('只能上传png/jpeg/jpg格式的图片')
    return false
  }
  else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片不能大于2MB')
    return false
  }
  return true
}

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

// 从用户账号中筛选进行人员登记
const showFilterSysUser = () => {
  refFilterDialog.value.showOrHideFilterDialog(true)
}

const recordSelectedHandler = (row: any) => {
  refFilterDialog.value.showOrHideFilterDialog(false)
  sealInfo.value.approverName = row.name
  sealInfo.value.approverId = row.id
}

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

  switch (params.type) {
    case 'create' :
      title.value = '印章管理登记（新增）'

      // 创建时间设置默认值
      sealInfo.value.createTime = dayjs().format('YYYY-MM-DD HH:mm:ss')

      break
    case 'update':
      title.value = '印章管理登记（编辑）'
      id.value = params.id

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

      break
    case 'detail':
      title.value = '印章管理登记（详情）'
      id.value = params.id

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

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

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

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

watch(() => sealInfo.value.minioFileName, (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="sealInfo" :rules="sealInfoRules" label-position="right" label-width="110px" border stripe>
        <el-row :gutter="24">
          <!-- 第一行 第一列 -->
          <el-col :span="6">
            <el-form-item label="印章编号" prop="sealNo">
              <el-input v-model="sealInfo.sealNo" placeholder="请输入印章编号" :clearable="true" :disabled="type === 'detail'" />
            </el-form-item>

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

          <!-- 第一行 第二列 -->
          <el-col :span="6">
            <el-form-item label="印章名称" prop="sealName">
              <el-input v-model="sealInfo.sealName" :clearable="true" placeholder="请输入印章名称" :disabled="type === 'detail'" />
            </el-form-item>

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

          <!-- 第一行 第三列 -->
          <el-col :span="6">
            <el-form-item label="印章类型" prop="sealType">
              <el-select v-model="sealInfo.sealType" placeholder="请选择印章类型" style="width: 100%;" :clearable="true" :disabled="type === 'detail'">
                <el-option v-for="dict in sealTypeDict" :key="dict.id" :label="dict.name" :value="dict.value" />
              </el-select>
              <el-input v-model="sealInfo.sealTypeName" type="hidden" />
            </el-form-item>

            <el-form-item label="在用状态" prop="status">
              <el-select v-model="sealInfo.status" placeholder="请选择是否在用" style="width: 100%;" :clearable="true" :disabled="type === 'detail'">
                <el-option v-for="dict in sealStatusDict" :key="dict.id" :label="dict.name" :value="dict.value" />
              </el-select>
              <el-input v-model="sealInfo.statusName" type="hidden" />
            </el-form-item>
          </el-col>

          <!-- 第一行 第四列 -->
          <el-col :span="6">
            <el-form-item label="批准人" prop="approverId">
              <el-input v-model="sealInfo.approverName" :clearable="true" placeholder="请选择批准人" :disabled="type === 'detail'" @click="showFilterSysUser" />
              <el-input v-model="sealInfo.approverId" type="hidden" />
            </el-form-item>

            <el-form-item label="报废时间">
              <el-date-picker
                v-model="sealInfo.abandonTime" type="date"
                format="YYYY-MM-DD" value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择批准时间" :disabled="type === 'detail'" style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第四行 -->
        <el-row :gutter="24">
          <el-col :span="20">
            <el-form-item label="图形" prop="minioFileName">
              <el-input v-model="sealInfo.minioFileName" type="hidden" />

              <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                :http-request="uploadQuarterlyEvaluateFile"
                :before-upload="beforeAvatarUpload"
                accept="image/png, image/jpeg,image/jpg"
                style="width: 50%; margin-left: 20px;"
                :disabled="type === 'detail'"
              >
                <el-image v-if="sealInfo.minioFileName" :src="minioFileUrl" class="avatar" fit="contain" @click="previewSealImage" />
                <el-icon v-else class="avatar-uploader-icon">
                  <plus />
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-page>

    <filter-sys-user ref="refFilterDialog" @record-selected="recordSelectedHandler" />
  </app-container>
</template>

<style scoped>
.avatar-uploader .avatar {
  width: 190px;
  height: 250px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 190px;
  height: 250px;
  text-align: center;
}
</style>
