<template>
  <div>
    <div class="header">
      <el-page-header @back="goBack">
        <template #content>
          <span class="text-large font-600 mr-3"> 课程详情 </span>
        </template>
      </el-page-header>
    </div>

    <div class="content">
      <el-form ref="learningActivityFormRef" :model="form" :rules="formRules" label-width="10vw">
        <el-form-item label="活动名称" prop="activityName">
          <el-input v-model="form.activityName" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="活动分类" prop="activityClassify">
          <el-select v-model="form.activityClassify" placeholder="请选择活动分类">
            <el-option v-for="dict in acvitity_classify" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="活动开始时间" prop="activityStartTime">
          <el-date-picker clearable v-model="form.activityStartTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择活动时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="活动结束时间" prop="activityEndTime">
          <el-date-picker clearable v-model="form.activityEndTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择活动时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="活动地点" prop="activityAddress">
          <el-input v-model="form.activityAddress" placeholder="请输入活动地点" />
        </el-form-item>
        <el-form-item label="活动数量" prop="activityNum">
          <el-input type="number" min="1" v-model="form.activityNum" placeholder="请输入活动数量" />
        </el-form-item>
        <el-form-item label="封面图" prop="activityPic">
          <el-upload :limit="1"
                     ref="coursePicRef"
                     accept=".png, .jpg"
                     class="avatar-uploader"
                     :action="upload.url"
                     :headers="upload.headers"
                     :show-file-list="false"
                     :on-success="handleAvatarSuccess"
                     :on-exceed="handleExceedPicSuccess"
                     :on-error="handleUploadError"
                     :before-upload="beforeAvatarUpload">
            <img v-if="form.activityPic" :src="form.activityPic" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
            <template #tip>
              <div class="text-left el-upload__tip">
                <span>请选择图片上传：大小128 * 180像素，支持jpg、png等格式，图片需小于10M，仅一张。</span>
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="活动内容" prop="activityContent">
          <editor v-model="form.activityContent" :min-height="192" />
        </el-form-item>
<!--    <el-form-item v-if="type != 'add' && type != 'edit'" label="发布状态" prop="status">
          <el-select v-model="form.status" placeholder="此处选择发布类型" clearable>
            <el-option v-for="dict in is_publish" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item> -->


        <div v-if="type != 'add' && type != 'edit'">

          <el-form-item v-if="form.userName" label="操作人：">
            <span>{{ form.userName }}</span>
          </el-form-item>

          <el-form-item v-if="form.createTime" label="创建时间：">
            <span>{{ form.createTime }}</span>
          </el-form-item>

          <el-form-item v-if="form.status != '1' && (form.takedownTime || form.createTime)"
            :label="form.status == '2' ? '发布时间：' : form.status == '3' ? '撤销时间：' : ''">
            <span v-if="form.takedownTime">{{ form.takedownTime }}</span>
            <span v-else>{{ form.createTime }}</span>
          </el-form-item>

        </div>

        <div class="btn">
          <el-button v-if="type == 'edit' || type == 'add'" :loading="buttonLoading" type="primary"
            @click="submitForm">提交</el-button>
          <el-button type="danger" @click="cancel">取消</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import FileOrImage from '@/components/FileOrImage/index.vue';
import { getLearningActivity, updateLearningActivity, addLearningActivity } from '@/api/study/activity';
import { globalHeaders } from '@/utils/request';
import {genFileId, UploadProps, UploadRawFile} from "element-plus";
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { is_publish, acvitity_classify } = toRefs<any>(proxy?.useDict('is_publish', 'acvitity_classify'));
const type = computed(() => proxy.$route.query.type);
const _id = computed(() => proxy.$route.query.id);
const buttonLoading = ref(false)
const router = useRouter();
const route = useRoute();
const coursePicRef = ref<ElUploadInstance>()
const upload = reactive<UploadOption>({
  headers: globalHeaders(),
  url: import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload'
});
const goBack = () => {
  router.back();
}
const learningActivityFormRef = ref<ElFormInstance>();
const initForm = {
  id: undefined,
  activityName: undefined,
  activityClassify: undefined,
  activityTime: undefined,
  activityStartTime: undefined,
  activityEndTime: undefined,
  activityAddress: undefined,
  activityNum: undefined,
  activityPic: undefined,
  activityContent: undefined,
  isPublic: undefined,
  status: undefined,
  remark: undefined,
  userName: undefined,
  takedownTime: undefined,
  createTime: undefined,
}
const form = ref({ ...initForm });
//提交
const submitForm = async () => {

  ElMessageBox.confirm('确认提交以上信息吗', {
    title: '系统确认',
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  }).then(() => {
    learningActivityFormRef.value?.validate(async (valid: boolean) => {

      if (valid) {
        buttonLoading.value = true;
        if (type.value == 'add') {

          form.value.status = '1';

          const res = await addLearningActivity(form.value).finally(() => { buttonLoading.value = false })
          if (res.code == 200) {
            proxy?.$modal.msgSuccess("提交成功");
            router.back();
          }

        } else if (type.value == 'edit') {
          const res = await updateLearningActivity(form.value).finally(() => { buttonLoading.value = false })
          if (res.code == 200) {
            proxy?.$modal.msgSuccess("修改成功");
            router.back();
          }
        }
        // const res = await addExpertRecommend(form.value).finally(() => { buttonLoading.value = false });
        // if (res.code == 200) {
        //   proxy?.$modal.msgSuccess("提交成功");
        //   router.back();
        // }
        reset();

      }

    });
  }).catch(() => {

  })
}
const handleExceedPicSuccess: UploadProps['onExceed'] = (files) => {
  coursePicRef.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  coursePicRef.value!.handleStart(file)
  coursePicRef.value!.submit()
}
//上传成功
const handleAvatarSuccess = (res: any) => {
  console.log(`handleAvatarSuccess..`, res);

  // 如果上传成功
  if (res.code === 200) {
    form.value.activityPic = res.data.url;
    proxy?.$modal.closeLoading();
  } else {
    proxy?.$modal.msgError('图片插入失败');
    proxy?.$modal.closeLoading();
  }
}

//上传失败
const handleUploadError = (err: any) => {
  proxy?.$modal.msgError('上传文件失败');
};
//上传之前
const beforeAvatarUpload = (file: any) => {
  const type = ['image/jpeg', 'image/jpg', 'image/png', 'image/svg'];
  const isJPG = type.includes(file.type);
  //检验文件格式
  if (!isJPG) {
    proxy?.$modal.msgError(`图片格式错误!`);
    return false;
  }
  // 校检文件大小
  const isLt = file.size / 1024 / 1024 < 10;
  if (!isLt) {
    proxy?.$modal.msgError(`上传图片大小不能超过 10 MB!`);
    return false;
  }
  proxy?.$modal.loading('正在上传文件，请稍候...');
  return true;
}
//重置表单
const reset = () => {
  form.value = { ...initForm };
  learningActivityFormRef.value?.resetFields();
}
//取消
const cancel = () => {
  router.back();
  reset();
}
//获取数据详情
const getData = async () => {
  if (_id.value.toString() == '' || null) {
    return
  }
  const res = await getLearningActivity(_id.value.toString());
  if (res.data.activityPic) {
    form.value.activityPic = res.data.activityPic;
  }
  console.log(`rresssss`, res);
  Object.assign(form.value, res.data);

}
/** 附件上传成功处理 */
const handleUpload = (response: any, file: UploadFile, uploadFiles: UploadFiles) => {

  // form.value.courseAttachment = response.data.url;

  ElMessageBox.alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '上传论文结果', {
    dangerouslyUseHTMLString: true
  });
};
onActivated(() => {
  if (type.value == 'add') {
    reset();
    return
  }
  getData();

})
onMounted(() => {
  if (type.value == 'add') {
    reset();
    return
  }
  getData();
})

const formRules = {
  activityName: [
    { required: true, message: "活动名称不能为空", trigger: "blur" }
  ],
  activityClassify: [
    { required: true, message: "活动分类不能为空", trigger: "change" }
  ],
  activityTime: [
    { required: true, message: "活动时间不能为空", trigger: "blur" }
  ],
  activityStartTime: [
    { required: true, message: "活动时间不能为空", trigger: "blur" }
  ],
  activityEndTime: [
    { required: true, message: "活动时间不能为空", trigger: "blur" }
  ],
  activityAddress: [
    { required: true, message: "活动地点不能为空", trigger: "blur" }
  ],
  activityNum: [
    { required: true, message: "活动数量不能为空", trigger: "blur" }
  ],
  activityPic: [
    { required: true, message: "封面图不能为空", trigger: "blur" }
  ],
  activityContent: [
    { required: true, message: "活动内容不能为空", trigger: "blur" }
  ],
  isPublic: [
    { required: true, message: "是否发布不能为空", trigger: "blur" }
  ],
  status: [
    { required: true, message: "状态不能为空", trigger: "change" }
  ],
  remark: [
    { required: true, message: "备注不能为空", trigger: "blur" }
  ],
}
</script>

<style lang="scss" scoped>
.header {
  margin: 1vh 0 0 2vw;
}

.el-form {
  margin-top: 2vh;
  margin-left: 2vw;
  width: 40%;
}

.btn {
  width: 60%;
  margin: 20px auto;
  display: flex;
  justify-content: space-evenly;

  .el-button {
    width: 30%;
  }
}

.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: 178px;
  height: 178px;
  text-align: center;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

:deep(.el-upload) {
  border: 1px dashed #3d3d3d;
  //border-radius: 1vw;
}

.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: 178px;
  height: 178px;
  text-align: center;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

:deep(.el-upload) {
  border: 1px dashed #3d3d3d;
  //border-radius: 1vw;
}
</style>
