<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="10">
                <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="10">
                <el-form-item label="企业名称" prop="enterprise" style="width: 100%">
                  <el-input v-model="editForm.enterprise" 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="entrepreneur_imgs" style="height: 30rem;" />
              </div>
            </el-form-item>
            <el-form-item label="企业详细介绍" prop="enterpriseDsc">
              <div v-if="showDrawer">
                <RichEdit v-model="editForm.enterpriseDsc" media-category="entrepreneur_imgs" 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`" />
              <div class="gva-btn-list" style="width: 100%;">
                <el-upload :action="`${imgUploadPath}/cms/mediaFile/upload?category=entrepreneur_imgs`"
                  style="height: 32px;" :show-file-list="false" :on-success="(res) => { uploadSuccess(res, 'avatar') }"
                  :on-error="uploadFailure" :before-upload="(file) => { return beforeUpload(file, avatarInfo) }">
                  <el-button type="default" plain icon="upload">直接上传</el-button>
                </el-upload>
                <CropperImg name="avatar" :img-width="avatarInfo.mediaWidth" :img-height="avatarInfo.mediaHeight"
                  category="entrepreneur_imgs" @on-success="(res) => { uploadSuccess(res, 'avatar') }" />
              </div>
              <div>
                <img v-if="editForm.avatar" :src="editForm.avatar" class="avatar"
                  :style="`width:${avatarInfo.mediaWidth}px;height:${avatarInfo.mediaHeight}px`">
              </div>
            </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`" />
              <div class="gva-btn-list" style="width: 100%;">
                <el-upload :action="`${imgUploadPath}/cms/mediaFile/upload?category=entrepreneur_imgs`"
                  style="height: 32px;" :show-file-list="false" :on-success="(res) => { uploadSuccess(res, 'video') }"
                  :on-error="uploadFailure" :before-upload="(file) => { return beforeUpload(file, videoInfo) }">
                  <el-button type="default" plain icon="upload">上传</el-button>
                </el-upload>
              </div>
              <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`" />
              <div class="gva-btn-list" style="width: 100%;">
                <el-upload :action="`${imgUploadPath}/cms/mediaFile/upload?category=entrepreneur_imgs`"
                  style="height: 32px;" :show-file-list="false" :on-success="(res) => { uploadSuccess(res, 'qrcode') }"
                  :on-error="uploadFailure" :before-upload="(file) => { return beforeUpload(file, qrcodeInfo) }">
                  <el-button type="default" plain icon="upload">直接上传</el-button>
                </el-upload>
                <CropperImg name="qrcode" :img-width="qrcodeInfo.mediaWidth" :img-height="qrcodeInfo.mediaHeight"
                  category="entrepreneur_imgs" @on-success="(res) => { uploadSuccess(res, 'qrcode') }" />
              </div>
              <div>
                <img v-if="editForm.qrcodeUrl" :src="editForm.qrcodeUrl" class="avatar"
                  :style="`width:${qrcodeInfo.mediaWidth}px;height:${qrcodeInfo.mediaHeight}px`">
              </div>
            </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 CropperImg from '@/components/upload/cropperImg.vue'
import {
  addEntrepreneur,
  updateEntrepreneur,
  getEntrepreneurById,
} from '@/api/entrepreneur'

// 组件定义
defineOptions({
  name: 'EntrepreneurEdit',
})
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' }
  ],
  enterprise: [
    { 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,
    headChar: '',
    name: '',
    enterprise: '',
    avatar: '',
    brief: '',
    description: '',
    enterpriseDsc: '',
    videoUrl: '',
    qrcodeUrl: '',
  }
}
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 updateEntrepreneur(editForm.value)
    } else {
      res = await addEntrepreneur(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: 240,
}
const videoInfo = {
  mediaType: 'video',
  mediaTypeInfo: 'mp4,webm',
  fileSize: 5000,
  fileSizeInfo: '5M',
  mediaWidth: 380,
  mediaHeight: 214,
}
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 getEntrepreneurById({ id: ID })
  if (res.code === 0) {
    // 初始化表单数据
    editForm.value = res.data.entrepreneur
    fullscreenLoading.value = false
  } else {
    ElMessage({
      type: 'error',
      message: '获取数据失败'
    })
    showErrMessage.value = '获取数据失败'
  }
  fullscreenLoading.value = false
}

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

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