<template>
  <el-drawer v-model="showDrawer" size="80%" :show-close="false" :close-on-click-modal="false"
    :close-on-press-escape="false">
    <template #header>
      <div class="flex justify-between items-center">
        <span class="text-lg">{{ !isEdit ? '添加' : '修改' }}院士</span>
        <div>
          <el-button type="primary" @click="handleFormSubmit">确 定</el-button>
          <el-button @click="handleFormClose">取 消</el-button>
        </div>
      </div>
    </template>
    <div v-loading="fullscreenLoading">
      <div v-if="showErrMessage != ''">
        {{ showErrMessage }}
      </div>
      <el-form v-else ref="editFormRef" label-position="top" :model="editForm" :rules="rules">
        <el-row :gutter="0">
          <el-col :span="16">
            <el-row :gutter="10">
              <el-col :span="12">
                <el-form-item label="姓名" prop="name" style="width: 100%">
                  <el-input v-model="editForm.name" autocomplete="off" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="首字母" prop="headChar" style="width: 100%">
                  <el-input v-model="editForm.headChar" :maxlength="1" autocomplete="off" style="width: 100%"
                    @change="toggleCase" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="职称" prop="title" style="width: 100%">
                  <el-input v-model="editForm.title" autocomplete="off" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="简介" prop="brief">
              <el-input v-model="editForm.brief" type="textarea" rows="5" :show-word-limit="true" style="width: 100%"
                maxlength="300" autocomplete="off" resize="none" />
            </el-form-item>
            <el-form-item label="个人详细介绍" prop="description">
              <div v-if="showDrawer">
                <RichEdit v-model="editForm.description" media-category="academician_dsc_imgs" style="height: 40rem;" />
              </div>
            </el-form-item>
            <el-form-item label="专家论文" prop="papers">
              <div v-if="showDrawer">
                <RichEdit v-model="editForm.papers" media-category="academician_papers" style="height: 30rem;" />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="1" align="center">
            <el-divider direction="vertical" style="height: 100%" />
          </el-col>
          <el-col :span="7">
            <el-form-item label="头像" prop="avatar" style="width: 100%">
              <el-alert type="info" :closable="false" style="margin-bottom: 10px;"
                :description="`类型为：${avatarInfo.mediaTypeInfo}, 大小不超过${avatarInfo.fileSizeInfo}, 宽*高: ${avatarInfo.mediaWidth}px*${avatarInfo.mediaHeight}px`" />
              <el-upload class="avatar-uploader"
                :action="`${imgUploadPath}/cms/mediaFile/upload?category=academician_avatar`" :show-file-list="false"
                :on-success="(res) => { uploadSuccess(res, 'avatar') }" :on-error="uploadFailure"
                :before-upload="(file) => { return beforeUpload(file, avatarInfo) }">
                <img v-if="editForm.avatar" :src="editForm.avatar" class="avatar" style="object-fit: cover;">
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
            <el-form-item label="介绍视频" prop="videoUrl" style="width: 100%">
              <el-alert type="info" :closable="false" style="margin-bottom: 10px;"
                :description="`类型为：${videoInfo.mediaTypeInfo}, 大小不超过${videoInfo.fileSizeInfo}, 宽*高: ${videoInfo.mediaWidth}px*${videoInfo.mediaHeight}px`" />
              <el-upload class="avatar-uploader"
                :action="`${imgUploadPath}/cms/mediaFile/upload?category=academician_video`" :show-file-list="false"
                :on-success="(res) => { uploadSuccess(res, 'video') }" :on-error="uploadFailure"
                :before-upload="(file) => { return beforeUpload(file, videoInfo) }">
                <el-button type="primary" plain icon="upload">上传</el-button>
              </el-upload>
              <video ref="videoRef" controls="controls" :width="300">
                <source src />
              </video>
            </el-form-item>
            <el-form-item label="企业二维码" prop="qrcodeUrl" style="width: 100%">
              <el-alert type="info" :closable="false" style="margin-bottom: 10px;"
                :title="`类型为：${qrcodeInfo.mediaTypeInfo}, 大小不超过${qrcodeInfo.fileSizeInfo}, 宽*高: ${qrcodeInfo.mediaWidth}px*${qrcodeInfo.mediaHeight}px`" />
              <el-upload class="avatar-uploader" style="width: 100px; height: 100px"
                :action="`${imgUploadPath}/cms/mediaFile/upload?category=academician_qrcode`" :show-file-list="false"
                :on-success="(res) => { uploadSuccess(res, 'qrcode') }" :on-error="uploadFailure"
                :before-upload="(file) => { return beforeUpload(file, qrcodeInfo) }">
                <img v-if="editForm.qrcodeUrl" :src="editForm.qrcodeUrl" class="avatar" style="object-fit: cover;">
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </el-drawer>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import RichEdit from '@/components/richtext/rich-edit.vue'
import { isImageMime, isVideoMime, isGifMime, checkImageWHEqual } from '@/utils/image'
import {
  addAcademician,
  updateAcademician,
  getAcademicianById,
} from '@/api/academician'

// 组件定义
defineOptions({
  name: 'AcademicianEdit',
})
const emit = defineEmits(['on-save', 'on-close'])
const props = defineProps({
  title: { type: String, default: '' }
})

const showDrawer = ref(false)
const showErrMessage = ref('')
const fullscreenLoading = ref(true)

// ------ 以下为form表单相关 ------
const editFormRef = ref(null)
const editForm = ref({})
const checkFlag = ref(false)
const isEdit = ref(false)
const rules = reactive({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  headChar: [
    { required: true, message: '请输入首字母', trigger: 'blur' }
  ],
  title: [
    { required: true, message: '请输入职称', trigger: 'blur' }
  ],
  brief: [
    { required: true, message: '请输入简介', trigger: 'blur' }
  ],
  avatar: [
    { required: true, message: '请选择头像', trigger: 'blur' },
  ],
})
// 初始化弹窗内表格方法
const emptyForm = () => {
  checkFlag.value = false
  editForm.value = {
    ID: 0,
    name: '',
    headChar: '',
    title: '',
    avatar: '',
    brief: '',
    description: '',
    videoUrl: '',
    qrcodeUrl: '',
    papers: '',
    projects: '',
    lectures: '',
  }
}
const toggleCase = (value) => {
  const newVal = value.split('').map(char => {
    if (char.match(/[a-z]/)) {
      return char.toUpperCase();
    } else if (char.match(/[A-Z]/)) {
      return char.toLowerCase();
    }
    return char;
  }).join('');
  editForm.value.headChar = newVal
}

// 关闭弹窗
const handleFormClose = () => {
  showDrawer.value = false
  emit('on-close')
}

// 提交表单
const handleFormSubmit = async () => {
  editFormRef.value.validate(async valid => {
    if (!valid) {
      return
    }
    let res
    if (isEdit.value) {
      res = await updateAcademician(editForm.value)
    } else {
      res = await addAcademician(editForm.value)
    }
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: isEdit.value ? '编辑成功' : '添加成功!'
      })
      showDrawer.value = false
      emit('on-save')
    }
  })
}

// ----- 以下为图片操作 -----
const avatarInfo = {
  mediaType: 'pic',
  mediaTypeInfo: 'jpg,png,webp,svg',
  fileSize: 500,
  fileSizeInfo: '500K',
  mediaWidth: 180,
  mediaHeight: 235,
}
const videoInfo = {
  mediaType: 'video',
  mediaTypeInfo: 'mp4,webm',
  fileSize: 5000,
  fileSizeInfo: '5M',
  mediaWidth: 214,
  mediaHeight: 380,
}
const qrcodeInfo = {
  mediaType: 'pic',
  mediaTypeInfo: 'jpg,png,webp,svg',
  fileSize: 500,
  fileSizeInfo: '500K',
  mediaWidth: 120,
  mediaHeight: 120,
}
const videoRef = ref(null)
const imgUploadPath = import.meta.env.VITE_BASE_API
const beforeUpload = (file, info) => {
  const isLtSize = file.size / 1024 < info.fileSize
  const isVideo = isVideoMime(file.type)
  const isImage = isImageMime(file.type)
  const isGif = isGifMime(file.type)
  if (info.mediaType === 'pic' && !isImage) {
    ElMessage.error('上传文件只能是 ' + info.mediaTypeInfo + ' 格式')
    return false
  }
  if (info.mediaType === 'video' && !isVideo) {
    ElMessage.error('上传文件只能是 ' + info.mediaTypeInfo + ' 格式')
    return false
  }
  if (info.mediaType === 'gif' && !isGif) {
    ElMessage.error('上传文件只能是 ' + info.mediaTypeInfo + ' 格式')
    return false
  }
  if (!isLtSize) {
    ElMessage.error('上传文件大小不能超过 ' + info.fileSizeInfo)
    return false
  }

  if (info.mediaType === 'pic') {
    const isSize = checkImageWHEqual(
      file, info.mediaWidth, info.mediaHeight
    ).then(
      () => {
        return file
      },
      () => {
        ElMessage.error('上传文件宽*高必须为: ' + info.mediaWidth + 'px*' + info.mediaHeight + 'px')
        return Promise.reject()
      })
    return isSize
  } else {
    return true
  }
}

const uploadSuccess = (res, field) => {
  const { code, data, msg } = res
  if (code !== 0) {
    ElMessage({ type: 'error', message: msg })
    return
  }
  if (!data.mediaFile) {
    ElMessage({ type: 'error', message: '返回错误，上传失败' })
    return
  }
  if (field === 'avatar') {
    editForm.value.avatar = data.mediaFile.url
  } else if (field === 'video') {
    editForm.value.videUrl = data.mediaFile.url
    videoRef.value.src = data.mediaFile.url
  } else if (field === 'qrcode') {
    editForm.value.qrcodeUrl = data.mediaFile.url
  }
}

const uploadFailure = () => {
  ElMessage({
    type: 'error',
    message: '上传失败'
  })
}

// 初始化方法
const openPage = async (params) => {
  fullscreenLoading.value = true
  showDrawer.value = true
  isEdit.value = false
  emptyForm()

  // 建议通过url传参获取目标数据ID 调用 find方法进行查询数据操作 从而决定本页面是create还是update 以下为id作为url参数示例
  if (params.ID && params.ID > 0) {
    // 编辑
    isEdit.value = true
    initFormById(params.ID)
  } else {
    // 新建
    fullscreenLoading.value = false
  }
}

const initFormById = async (ID) => {
  const res = await getAcademicianById({ ID: ID })
  if (res.code === 0) {
    // 初始化表单数据
    editForm.value = res.data.academician
    fullscreenLoading.value = false
  } else {
    ElMessage({
      type: 'error',
      message: '获取数据失败'
    })
    showErrMessage.value = '获取数据失败'
  }
  fullscreenLoading.value = false
}

// 对外暴露方法
defineExpose({ openPage })
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 100%;
  height: 100%;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px solid 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: 150px;
  height: 150px;
  text-align: center;
}

.el-form-item__content .el-alert__description {
  line-height: 22px;
}
</style>
