<!--
 * @author: ym
 * @Date: 2021-10-16 12:58:57
 * @LastEditTime: 2022-09-06 10:58:59
 * @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="info" 
              @click="close">关闭</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'">
          <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="pageData.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 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: "/project/form/setting",
      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",
        },
      ],
      pageData: {
        formForm: [
          {
            type: "Select",
            label: "题目分类",
            prop: "itemType",
            rules: { required: true },
            default: false,
            options:this.commonConstants.courseType,
             change:(val)=>{
              this.$api.courseThemeAll({courseType:val}).then(res=>{
                this.pageData.formData.courseThemeId=''
                this.pageData.formForm[1].options=res.data.list.map(item=>{
                  return{label:item.themeName,value:item.courseThemeId}
                })
              })
            }
          },
          {
            type:'Select',
            label:'题目专题',
            prop:'courseThemeId',
            rules:{required:true},
            default:false,
            options:[]
          },
        ],
        //发布时间
        baseForm: [
        ],
        //查询表单内容 end
        //查询条件 start
        formData: {
          fileList: [],
          projectDTO: {},
          fileListVideo: [],
          videoUrl: "",
          isSubmit: false,
          courseThemeId:''
        },
        //查询条件 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));
      this.pageData.formData.fileList = [{ url: this.pageData.formData.image }];
      this.pageData.formData.fileListVideo = [
        { url: this.pageData.formData.videoUrl },
      ];
      console.log();
      this.$api.courseThemeAll({courseType:this.updateData.itemType})
      .then(res=>{
        this.pageData.formForm[1].options=res.data.list.map(item=>{
          return{label:item.themeName,value:String(item.courseThemeId)}
        })
        // console.log(this.pageData.formForm[3])
      })
      // this.updateData.expand=JSON.parse(this.updateData.expand)
      // this.updateData.regList=JSON.parse(this.updateData.regList)
      console.log( this.updateData);
      console.log(dbDataConvertForItemJson(this.updateData));
      this.drawingList = [dbDataConvertForItemJson(this.updateData)]
        
      // this.updateFormConf = {
      //   title: 'this.updateData.label',
      //   description: 'this.updateData.describe',
      //   score: 'this.updateData.score',
      // };
    }
  },
  watch: {
    "pageData.formData.isSubmit": {
      handler: function (val, oldval) {
        if (val && !oldval) {
          this.pageData.formForm.splice(3, 0, ...this.pageData.baseForm);
        } else if (!val && oldval) {
          this.pageData.formForm.splice(3, 1);
        }
      },
    },
    // 'isUpdate':{
    //   handler:function(val,oldval){
    //     if(val){
    //       pageData.formForm[2].disabled=true
    //     }
    //     else{
    //       pageData.formForm[2].disabled=false
    //     }
    //   }
    // }
  },
  computed: {
    // 预览数据
    drawingListPreView() {
      let list = JSON.parse(JSON.stringify(this.drawingList));
      list.forEach((item, index) => {
        list[index] = formItemConvertData(item, this.updateData.projectKey);
      });
      return list;
    },
  },
  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) {
          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;
          });


          this.pageData.formData.paperName = this.formConf.title;
          this.pageData.formData.projectDTO = {
            name: this.formConf.title,
            describe: this.formConf.description,
            score: this.formConf.score,
            list: list,
            key: this.updateData.projectKey,
          };
          let __data=this.pageData.formData.projectDTO.list.map(item=>{
            item.defaultValue=null;
            return {
              ...item,
              id:this.updateData.id,
              itemType:this.pageData.formData.itemType,
              courseThemeId:this.pageData.formData.courseThemeId
            }
          })
          console.log(__data);
          if (!this.isUpdate) {
            this.$api.service.addQuestionBatch(__data)
            .then((res) => {
              this.$emit("close");
            });
          } else {
            this.$api.service.editQuestion(__data[0])
            .then((res) => {
              this.$emit("close");
            });
          }
        } else {
           this.commonUtil.showMessage({
            message: "请填写题库基本信息",
            type: this.commonConstants.messageType.error,
          });
          return false;
        }
      });
    },
    //更改菜单
    changeOption(option) {
      this.menuOption = option;
    },
    //关闭弹窗
    close(){
      this.$emit("close")
    }
    // 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>
