<!--
 * @author: ym
 * @Date: 2021-10-16 12:58:57
 * @LastEditTime: 2022-09-21 16:17:53
 * @LastEditors: chenkangxu
 * @Description: 
 * @FilePath: \background-front-end\src\components\common\content-editor\content-editor.vue
-->
<template>
  <div class="form-index-container">
    <!-- <div class="header-container">
      <el-row align="middle" type="flex" :gutter="5">
        <i class="el-icon-back" @click="$router.back(-1)" />
        <el-col />
      </el-row>
    </div> -->
    <div class="main-container">
      <div class="left-menu-container">
        <el-menu
          :collapse="isCollapse"
          :default-active="defaultActiveMenu"
          class="el-menu-vertical"
        >
          <!-- <el-menu-item>
            <el-button type="primary" @click="previewDialogVisible = true">
              预览
            </el-button></el-menu-item
          > -->
          <el-menu-item>
            <el-button type="success" @click="saveProjectAsTemplateHandle"
              >保存</el-button
            ></el-menu-item
          >
          <el-menu-item
            v-for="menuItem in menuItemList"
            :key="menuItem.route"
            :index="menuItem.route"
            @click="changeOption(menuItem.option)"
          >
            <i :class="menuItem.icon" />
            <span slot="title">{{ menuItem.title }}</span>
          </el-menu-item>
        </el-menu>
      </div>
      <div class="right-content-container">
        <div v-show="menuOption == 'editor'">
          <!-- 当使用powerpaste从word粘贴图文到富文本里时会粘贴到所有实例上 -->
          <editor
            :drawingList="drawingList"
            :updateFormConf="updateFormConf"
            :isUpdate="isUpdate"
            @changeFormConf="changeFormConf"
          ></editor>
        </div>
        <el-row>
          <el-col :span="16"
            ><div v-show="menuOption == 'info'">
              <objForm
                ref="formFormRef"
                :formConfig="pageData.formConfig"
                :formForm="formForm"
                :formData="pageData.formData"
                :formHandles="pageData.formHandles"
                :inline="false"
              >
              </objForm></div
          ></el-col>
        </el-row>
      </div>
    </div>
    <el-dialog :visible.sync="previewDialogVisible" destroy-on-close fullscreen>
      <pre-view
        v-if="previewDialogVisible"
        :drawingList="drawingListPreView"
        :key="previewKey"
        :preview-qrcode="true"
      />
    </el-dialog>
  </div>
</template>

<script>
import { formConf } from "@/components/generator/config";
import preView from "@/components/common/content-editor/preview";
import editor from "./editor/index.vue";
import objForm from "@/components/common/form/form.vue";
import { dbDataConvertForItemJson, formItemConvertData } from "@/utils/convert";
export default {
  components: { editor, objForm, preView },
  props: {
    isUpdate: {
      type: Boolean,
    },
    updateData: {
      type: Object,
    },
  },
  data() {
    return {
      // 试卷基本数据
      formConf,
      updateFormConf: {},
      // 表单项列表
      drawingList: [],
      menuOption: "info",
      previewKey: +new Date(),
      projectKey: null,
      previewDialogVisible: false,
      defaultActiveMenu: "editor",
      isCollapse: false,

      menuItemList: [
        {
          title: "信息",
          icon: "el-icon-info",
          route: "/project/form/setting",
          option: "info",
        },
        {
          title: "编辑",
          icon: "el-icon-edit",
          route: "/project/form/editor",
          option: "editor",
        },
        // {
        //   title: "设置",
        //   icon: "el-icon-setting",
        //   route: "/project/form/setting",
        //   option: "setting",
        // },
        // {
        //   title: "逻辑",
        //   icon: "el-icon-menu",
        //   route: "/project/form/logic",
        // },
        // {
        //   title: "外观",
        //   icon: "el-icon-view",
        //   route: "/project/form/theme",
        // },
        // {
        //   title: "发布",
        //   icon: "el-icon-video-play",
        //   route: "/project/form/publish",
        // },
        // {
        //   title: "统计",
        //   icon: "el-icon-data-line",
        //   route: "/project/form/statistics",
        // },
      ],
      pageData: {
        courseThemeIdOptions: [],
        //发布时间
        baseForm: [
          {
            type: "Date",
            label: "发布时间",
            prop: "releaseTime",
            rules: { required: true },
          },
        ],
        //查询表单内容 end
        //查询条件 start
        formData: {
          fileList: [],
          fileListVideo: [],
          fileListPPT: [],
          fileListAudio: [],
          projectDTO: {},
          courseType: "",
          courseThemeId: "",
          isSubmit: false,
          ppt: "",
          videoUrl: "",
          audioUrl: "",
          imageUrl: "",
        },
        //查询条件 end
        //查询表单按钮start
        formHandles: [
          {
            label: "下一步编辑试卷",
            type: "primary",
            handle: () => this.goEditor(),
          },
        ],
      },
      //查询表单按钮end
    };
  },
  created() {
    // this.projectKey = this.$route.query.key
    // this.defaultActiveMenu = this.$route.path
    // this.isCollapse = this.$store.state.form.isCollapse
  },
  beforeMount() {
    // 如果是编辑
    // console.log(11)
    if (this.isUpdate) {
      console.log("editor", this.updateData);
      this.pageData.formData = JSON.parse(JSON.stringify(this.updateData));
      if (this.pageData.formData.image) {
        this.pageData.formData.fileList = [
          { url: this.pageData.formData.image },
        ];
      }
      if (this.pageData.formData.videoUrl) {
        this.pageData.formData.fileListVideo = [
          { url: this.pageData.formData.videoUrl },
        ];
      }
      if (this.pageData.formData.audioUrl) {
        this.pageData.formData.fileListAudio = [
          { name: "音频文件", url: this.pageData.formData.audioUrl },
        ];
      }
      if (this.pageData.formData.ppt) {
        console.log(this.pageData.formData.ppt);
        this.pageData.formData.fileListPPT = [
          { name: "ppt文件", url: this.pageData.formData.ppt },
        ];
      }
      // this.pageData.formData.fileList = [{ url: this.pageData.formData.image }];
      // this.pageData.formData.fileListVideo = [
      //   { url: this.pageData.formData.videoUrl },
      // ];
      this.$api
        .courseThemeAll({ courseType: this.updateData.courseType })
        .then((res) => {
          // this.pageData.formForm[3].options = res.data.list.map((item) => {
          //   return { label: item.themeName, value: item.courseThemeId };
          // });
          // console.log(this.pageData.formForm[3]);
          this.pageData.courseThemeIdOptions = res.data.list.map((item) => {
            return { label: item.themeName, value: item.courseThemeId };
          });
        });

      this.drawingList = this.updateData.projectDTO.list.map((item) =>
        dbDataConvertForItemJson(item)
      );
      this.updateFormConf = {
        title: this.updateData.projectDTO.name,
        description: this.updateData.projectDTO.describe,
        score: this.updateData.projectDTO.score,
        customScore: this.updateData.projectDTO.customScore,
      };
    }
  },
  watch: {
    "pageData.formData.isSubmit": {
      handler: function (val, oldval) {
        if (val && !oldval) {
          this.pageData.formForm&&this.pageData.formForm.splice(6, 0, ...this.pageData.baseForm);
        } else if (!val && oldval) {
          this.pageData.formForm&&this.pageData.formForm.splice(6, 1);
        }
      },
    },
  },
  computed: {
    // 预览数据
    drawingListPreView() {
      let list = JSON.parse(JSON.stringify(this.drawingList));
      list.forEach((item, index) => {
        list[index] = formItemConvertData(item, this.updateData.projectKey);
      });
      return list;
    },
    formForm() {
      return [
        {
          type: "Input",
          label: "课程标题",
          prop: "title",
          rules: { required: true, maxLength: 100 },
        },
        {
          type: "Tinymce",
          label: "课程描述",
          prop: "content",
          rules: { required: true },
        },
        {
          type: "Select",
          label: "课程分类",
          prop: "courseType",
          rules: { required: true },
          default: false,
          options: this.commonConstants.courseType,
          change: (val) => {
            this.$api.courseThemeAll({ courseType: val }).then((res) => {
              this.pageData.formData.courseThemeId = "";
              this.pageData.courseThemeIdOptions = res.data.list.map((item) => {
                return { label: item.themeName, value: item.courseThemeId };
              });
            });
          },
        },
        {
          type: "Select",
          label: "课程专题",
          prop: "courseThemeId",
          rules: { required: true },
          default: false,
          options: this.pageData.courseThemeIdOptions,
        },
        {
          type: "Select",
          label: "课程年级",
          prop: "courseGrade",
          default: false,
          rules: { required: true },
          if: this.pageData.formData.courseType != "我的学习",
          options: [
            // { label: "一年级", value: 1 },
            { label: "低年级", value: 2 },
            { label: "中年级", value: 3 },
            // { label: "四年级", value: 4 },
            { label: "高年级", value: 5 },
            // { label: "六年级", value: 6 },
            // { label: "七年级", value: 7 },
            // { label: "八年级", value: 8 },
            // { label: "九年级", value: 9 },
          ],
        },
        {
          //是否立即发布
          label: "立即发布",
          type: "Switch",
          prop: "isSubmit",
          disabled: () => {
            return this.isUpdate;
          },
        },
        // {
        //   type: "Input",
        //   label: "试卷名称",
        //   prop: "paperName",
        //   rules: { required: true, maxLength: 100 },
        // },
        {
          type: "Upload",
          label: "课程封面",
          fileUrl: "image",
          prop: "fileList",
          accept: ".jpg,.jpeg,.png,.JPG,.JPEG",
          width: "300px",
          drag: true,
          // rules: { required: true },
        },

        {
          type: "Upload",
          label: "音频",
          fileUrl: "audioUrl",
          prop: "fileListAudio",
          listType: "text",
          // rules: { required: true },
          width: "300px",
          filesize: 20,
          accept:
            ".MP3,.WAV,.WMA,.Flac,.MIDI,.RA,.APE,.AAC,.CDA,.MOV,.mp3.wav,.wma.flac,.midi.ra,.ape,.aac,.cda,.mov,.m4a,.M4A",
          tips: "请上传音频文件",
          drag: true,
        },
        {
          type: "Upload",
          label: "视频",
          fileUrl: "videoUrl",
          prop: "fileListVideo",
          listType: "text",
          // rules: { required: true },
          width: "300px",
          isVideo: true,
          accept: ".mp4,.avi,.mov,.rmvb,.flv,.MP4,.AVI,.MOV,.RMVB,.FLV",
          tips: "请上传视频文件",
          drag: true,
        },
        {
          type: "Upload",
          label: "课程PPT",
          fileUrl: "ppt",
          prop: "fileListPPT",
          listType: "text",
          // rules: { required: true },
          width: "300px",
          accept: ".pptx,.ppt,.PPTX,.PPT",
          tips: "请上传PPT文件",
          drag: true,
        },
      ];
    },
  },
  methods: {
    changeDrawingList(val) {
      this.drawingList = val;
    },
    changeFormConf(val) {
      this.formConf = val;
    },
    openPreviewHandle() {
      // this.previewKey = +new Date()
      // this.previewDialogVisible = true
    },
    goEditor() {
      this.changeOption("editor");
      // this.$refs["formFormRef"].$refs["formFormRef"].validate((valid) => {
      //   if (valid) {
      //     // let content = this.pageData.modalData;
      //     // if (
      //     //   this.pageData.modalConfig.type ==
      //     //   this.commonConstants.modalType.insert
      //     // ) {
      //     //   this.$api.saveNewContent(content).then((res) => {
      //     //     this.searchTableList();
      //     //   });
      //     // } else {
      //     //   this.$api.updateRedContentInfo(content).then((res) => {
      //     //     this.searchTableList();
      //     //   });
      //     // }
      //     this.changeOption("editor");
      //   } else {
      //     this.commonUtil.showMessage({
      //       message: "请填写课程基本信息",
      //       type: this.commonConstants.messageType.error,
      //     });
      //   }
      // });
    },
    saveProjectAsTemplateHandle() {
      this.$refs.formFormRef.$refs.formFormRef.validate((valid) => {
        if (valid) {
          console.log(this.pageData.formData);
          let totalScore = 0;
          let list = JSON.parse(JSON.stringify(this.drawingList));
          list.forEach((item, index) => {
            // let index1=1;
            // // console.log(item.__config__.formId)
            // if(item.__config__.formId===null){
            //     console.log(111)
            //     item.__config__.formId=index1++;
            // }
            list[index] = formItemConvertData(item, this.updateData.projectKey);
          });
          list.forEach((item) => {
            totalScore += item.score;
          });
          console.log(totalScore, this.formConf.score);
          if (this.formConf.customScore) {
            if (list.length != 0 && totalScore != this.formConf.score) {
              return this.$message({
                type: "warning",
                message:
                  totalScore < this.formConf.score
                    ? "题目分数不满总分！"
                    : "题目分数高于总分！",
              });
            }
          } else {
            var baseNum = Math.floor(this.formConf.score / list.length);
            // 多出来的螺丝个数
            var leftNum = this.formConf.score % list.length;
            // 放螺丝
            var newArr = [];
            newArr.length = list.length;
            newArr.fill(baseNum);
            // 放剩余的螺丝
            for (var i = 0; i < leftNum; i++) {
              newArr[i]++;
            }
            newArr.forEach((item, index) => {
              list[index].score = item;
            });
          }

          this.pageData.formData.paperName = this.formConf.title;
          this.pageData.formData.projectDTO = {
            name: this.formConf.title,
            describe: this.formConf.description,
            score: this.formConf.score,
            customScore: this.formConf.customScore,
            list: list && list.length == 0 ? null : list,
            key: this.updateData.projectKey,
          };
          console.log("projectDTO", this.pageData.formData.projectDTO);
          console.log(JSON.stringify(this.pageData.formData));
          //如果是我的学习分类，就设置为低年级
          if (this.pageData.formData.courseType == "我的学习") {
            this.pageData.formData.courseGrade = 2;
          }
          if (!this.isUpdate) {
            this.$api.saveNewCourse(this.pageData.formData).then((res) => {
              this.$emit("close");
            });
          } else {
            this.$api.updateRedCourse(this.pageData.formData).then((res) => {
              this.$emit("close");
            });
          }
        } else {
          this.commonUtil.showMessage({
            message: "请填写课程基本信息",
            type: this.commonConstants.messageType.error,
          });
          return false;
        }
      });
    },
    //更改菜单
    changeOption(option) {
      this.menuOption = option;
    },
    save() {
      this.pageData.modalData.userId = this.$store.state.user.id;
      this.$refs["modalRef"].$refs["modalFormRef"].validate((valid) => {
        if (valid) {
          let content = this.pageData.modalData;
          if (
            this.pageData.modalConfig.type ==
            this.commonConstants.modalType.insert
          ) {
            this.$api.saveNewContent(content).then((res) => {
              this.searchTableList();
            });
          } else {
            this.$api.updateRedContentInfo(content).then((res) => {
              this.searchTableList();
            });
          }
          this.closeModal();
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.form-index-container {
  height: 100%;
  width: 100%;
}

::v-deep .el-card__body {
  padding: 0;
}

::v-deep .el-menu {
  border: none;
  background-color: transparent;
}

.header-container {
  width: 100%;
  height: 50px;
  padding: 0 20px;

  .el-icon-back {
    font-size: 22px;
    font-weight: 550;
    cursor: pointer;
    color: #000;
    margin-right: 75px;

    &:hover {
      color: rgb(32, 160, 255);
    }
  }

  .header-logo {
    height: 45px;
    width: 200px;
  }
}

.main-container {
  height: calc(100vh - 60px);
  display: flex;
  flex-direction: row;

  .right-content-container {
    width: calc(100vw - 100px);
    height: calc(100vh - 60px);
    overflow-x: hidden;
  }
}

.left-menu-container {
  max-width: 100px;
  text-align: center;
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  border-right: solid 1px #e6e6e6;

  .el-menu-vertical:not(.el-menu--collapse) {
    width: 100px;
    min-height: 400px;
  }

  .el-icon-d-arrow-left,
  .el-icon-d-arrow-right {
    font-size: 19px;
    cursor: pointer;
    font-weight: 550;
    color: #000;
    margin-bottom: 100px;

    &:hover {
      color: rgb(32, 160, 255);
    }
  }
}

::v-deep.preview-container {
  background-color: #ffffff;
}
</style>
