<template>
  <div class="m-container">
    <h2>
      <el-page-header @back="onCancel" :content="titleName"></el-page-header>
    </h2>
    <div class="m-core">
      <el-form ref="form" :model="form" label-width="140px">
        <el-row>
          <el-col :xs="24" :sm="24" :md="24" :lg="18" :xl="18">
            <el-form-item
              label="问卷名称"
              prop="title"
              :rules="[
                { required: true, message: '请输入问卷名称', trigger: 'blur' },
              ]"
            >
              <el-input
                v-model="form.title"
                placeholder="请输入问卷名称"
                :disabled="disabled"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="12" :sm="12" :md="12" :lg="9" :xl="9">
            <el-form-item
              label="是否需要登录"
              prop="loginFlag"
              class="memoWrapItem"
              :rules="[
                {
                  required: true,
                  message: '请选择是否需要登录',
                  trigger: 'change',
                },
              ]"
            >
              <template slot="label">
                <p style="position: relative" class="titleCell">
                  <span style="color: #f56c6c; margin-right: 4px">*</span>
                  是否需要登录
                  <el-tooltip placement="top" popper-class="mTooltip">
                    <div slot="content">
                      若选"是"，学员登录才可填写问卷，提交详情中自动展示学员姓名、年龄、手机号信息
                    </div>
                    <i
                      class="el-icon-question"
                      style="
                        font-size: 18px;
                        color: #f56c6c;
                        position: relative;
                        top: 2px;
                      "
                    ></i>
                  </el-tooltip>
                </p>
              </template>
              <el-select
                v-model="form.loginFlag"
                placeholder="请选择是否需要登录"
                :disabled="disabled"
                @change="changeLoginFlag"
                style="width: 100% !important"
              >
                <el-option label="是" :value="1"></el-option>
                <el-option label="否" :value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col
            :xs="12"
            :sm="12"
            :md="12"
            :lg="9"
            :xl="9"
            v-if="form.loginFlag"
          >
            <el-form-item
              label="是否逐题提交"
              prop="commitType"
              class="memoWrapItem"
              :rules="[
                {
                  required: true,
                  message: '请选择是否逐题提交',
                  trigger: 'change',
                },
              ]"
            >
              <template slot="label">
                <p style="position: relative" class="titleCell">
                  <!-- <span style="color: #f56c6c; margin-right: 4px">*</span> -->
                  是否逐题提交
                  <el-tooltip placement="top" popper-class="mTooltip">
                    <div slot="content">逐题模式下，所有问题默认必填</div>
                    <i
                      class="el-icon-question"
                      style="
                        font-size: 18px;
                        color: #f56c6c;
                        position: relative;
                        top: 2px;
                      "
                    ></i>
                  </el-tooltip>
                </p>
              </template>
              <el-select
                v-model="form.commitType"
                placeholder="请选择是否逐题提交"
                :disabled="disabled"
                style="width: 100% !important"
              >
                <el-option label="是" :value="1"></el-option>
                <el-option label="否" :value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="24" :md="24" :lg="18" :xl="18">
            <el-form-item
              label="分享标题"
              prop="shareTitle"
              :rules="[
                { required: true, message: '请输入分享标题', trigger: 'blur' },
              ]"
            >
              <template slot="label">
                <p style="position: relative" class="titleCell">
                  <!-- <span style="color: #f56c6c; margin-right: 4px">*</span> -->
                  分享标题
                  <el-tooltip placement="top" popper-class="mTooltip">
                    <div slot="content">
                      问卷链接分享到微信时,显示的链接标题
                    </div>
                    <i
                      class="el-icon-question"
                      style="
                        font-size: 18px;
                        color: #f56c6c;
                        position: relative;
                        top: 2px;
                      "
                    ></i>
                  </el-tooltip>
                </p>
              </template>
              <el-input
                v-model="form.shareTitle"
                placeholder="请输入分享标题"
                :disabled="disabled"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="24" :md="24" :lg="18" :xl="18">
            <el-form-item
              label="分享描述"
              prop="shareDescribe"
              :rules="[
                { required: true, message: '请输入分享描述', trigger: 'blur' },
              ]"
            >
              <template slot="label">
                <p style="position: relative" class="titleCell">
                  <!-- <span style="color: #f56c6c; margin-right: 4px">*</span> -->
                  分享描述
                  <el-tooltip placement="top" popper-class="mTooltip">
                    <div slot="content">
                      问卷链接分享到微信时,显示的链接描述
                    </div>
                    <i
                      class="el-icon-question"
                      style="
                        font-size: 18px;
                        color: #f56c6c;
                        position: relative;
                        top: 2px;
                      "
                    ></i>
                  </el-tooltip>
                </p>
              </template>
              <el-input
                v-model="form.shareDescribe"
                placeholder="请输入分享描述"
                :disabled="disabled"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item
            label="问卷模板"
            prop="templateType"
            :rules="[{ required: true, message: '请选择问卷模板' }]"
          >
            <el-checkbox-group v-model="checkList" @change="bindCheckBox">
              <div class="chioseWrap">
                <div class="chioseItem" @click="settemplateType(1)">
                  <img src="./images/img1.png" alt="" />
                  <!--        v-model="form.templateType" -->
                  <div class="remberBox">
                    <div class="wrap"></div>
                    <el-checkbox
                      class="chioseBox"
                      :label="1"
                      :checked="form.templateType == 1"
                      :disabled="disabled"
                      ><br
                    /></el-checkbox>
                    <!-- <div
                    class="dotWrap"
                    :class="[form.templateType == 1 ? 'checked' : '']"
                  ></div> -->
                  </div>
                </div>
                <div class="chioseItem" @click="settemplateType(2)">
                  <img src="./images/img2.png" alt="" />
                  <div class="remberBox">
                    <!--  v-model="form.templateType" -->
                    <div class="wrap"></div>
                    <el-checkbox
                      name="2"
                      class="chioseBox"
                      :label="2"
                      :checked="form.templateType == 2"
                      :disabled="disabled"
                      ><br
                    /></el-checkbox>
                    <!-- <div
                    class="dotWrap"
                    :class="[form.templateType == 2 ? 'checked' : '']"
                  ></div> -->
                  </div>
                </div>
                <div class="chioseItem" @click="settemplateType(3)">
                  <img src="./images/img3.png" alt="" />
                  <div class="remberBox">
                    <div class="wrap"></div>
                    <el-checkbox
                      class="chioseBox"
                      :label="3"
                      :checked="form.templateType == 3"
                      :disabled="disabled"
                      ><br
                    /></el-checkbox>
                    <!-- <div
                    class="dotWrap"
                    :class="[form.templateType == 3 ? 'checked' : '']"
                  ></div> -->
                  </div>
                </div>
                <div class="chioseItem" @click="settemplateType(4)">
                  <img src="./images/img4.png" alt="" />
                  <div class="remberBox">
                    <div class="wrap"></div>
                    <el-checkbox
                      class="chioseBox"
                      :label="4"
                      :checked="form.templateType == 4"
                      :disabled="disabled"
                      ><br
                    /></el-checkbox>
                    <!-- <div
                    class="dotWrap"
                    :class="[form.templateType == 3 ? 'checked' : '']"
                  ></div> -->
                  </div>
                </div>
              </div>
            </el-checkbox-group>
          </el-form-item>
        </el-row>
      </el-form>

      <el-row>
        <el-col
          :xs="24"
          :sm="24"
          :md="24"
          :lg="18"
          :xl="18"
          v-for="(item, index) in form.questionnaireQuestionList"
          :key="index"
          style="
            padding: 15px 22px;
            background-color: #eef4f9;
            margin-bottom: 10px;
          "
        >
          <el-row
            type="flex"
            align="middle"
            style="flex: 1 auto; padding-bottom: 15px"
          >
            <el-col :span="12">
              <span
                style="
                  font-size: 18px;
                  width: 80px;
                  text-align: right;
                  display: inline-block;
                "
                >问题{{ index + 1 }}</span
              >
            </el-col>
            <el-col :span="12" style="text-align: right; padding-right: 15px">
              <el-tooltip
                key="moveDown"
                class="item"
                effect="dark"
                content="向下移动"
                placement="top"
              >
                <el-button
                  icon="el-icon-top"
                  circle
                  @click.stop="moveDown(form.questionnaireQuestionList, index)"
                  :disabled="index == 0 || disabled"
                ></el-button>
              </el-tooltip>
              <el-tooltip
                key="moveUp"
                class="item"
                effect="dark"
                content="向上移动"
                placement="top"
              >
                <el-button
                  icon="el-icon-bottom"
                  circle
                  @click.stop="moveUp(form.questionnaireQuestionList, index)"
                  :disabled="
                    form.questionnaireQuestionList.length <= 1 ||
                    form.questionnaireQuestionList.length == index + 1 ||
                    disabled
                  "
                ></el-button>
              </el-tooltip>
              <el-tooltip
                class="item"
                effect="dark"
                content="删除"
                placement="top"
              >
                <el-button
                  icon="el-icon-delete"
                  circle
                  @click.stop="onDelete(form.questionnaireQuestionList, index)"
                  :disabled="
                    form.questionnaireQuestionList.length <= 1 || disabled
                  "
                ></el-button>
              </el-tooltip>
            </el-col>
          </el-row>
          <question-list
            ref="questions"
            :type="type"
            :form="item"
            :commitType="form.commitType"
            :disabled="disabled"
          />
        </el-col>
        <!-- <el-collapse v-model="activeName">
                <el-col :xs="24" :sm="24" :md="24" :lg="18" :xl="18" v-for="(item, index) in form.questionnaireQuestionList" :key="index" style="padding: 15px 22px; background-color: #eef4f9; margin-bottom: 10px;">
                <el-collapse-item style="background-color: #eef4f9;" :name="index">
                    <template slot="title">
                        <el-row type="flex" align="middle" style="flex: 1 auto;">
                            <el-col :span="12">
                                <span style="font-size: 18px;width: 80px; text-align: right;display: inline-block;">问题{{ index + 1 }}</span>
                            </el-col>
                            <el-col :span="12" style="text-align: right; padding-right: 15px;">
                                <el-tooltip class="item" effect="dark" content="向下移动" placement="top">
                                    <el-button icon="el-icon-top" circle  @click.stop="moveDown(form.questionnaireQuestionList, index)" :disabled="index == 0"></el-button>
                                </el-tooltip>
                                <el-tooltip class="item" effect="dark" content="向下移动" placement="top">
                                    <el-button icon="el-icon-bottom" circle  @click.stop="moveUp(form.questionnaireQuestionList, index)" :disabled="form.questionnaireQuestionList.length <= 1 || form.questionnaireQuestionList.length == (index + 1)"></el-button>
                                </el-tooltip>
                                <el-tooltip class="item" effect="dark" content="删除" placement="top">
                                    <el-button icon="el-icon-delete" circle  @click.stop="onDelete(form.questionnaireQuestionList, index)" :disabled="form.questionnaireQuestionList.length <= 1"></el-button>
                                </el-tooltip>
                            </el-col>
                        </el-row>
                    </template>
                    <question-list ref="questions" :type="type" :form="item" />
                </el-collapse-item>
                </el-col>
            </el-collapse> -->
      </el-row>
      <el-row style="padding-bottom: 15px">
        <el-col
          :xs="24"
          :sm="24"
          :md="24"
          :lg="18"
          :xl="18"
          style="text-align: center"
        >
          <el-button
            style="width: 100%"
            type="default"
            :disabled="disabled"
            @click="addQuestionItem(form.questionnaireQuestionList)"
            icon="el-icon-plus"
            >新增问题</el-button
          >
        </el-col>
      </el-row>
      <el-row>
        <el-col :xs="24" :sm="24" :md="24" :lg="18" :xl="18">
          <el-alert
            v-if="disabled"
            style="margin: 10px 0"
            title="该问卷已存在提交数据，不可修改"
            :closable="false"
            type="error"
          >
          </el-alert>
        </el-col>
      </el-row>

      <el-button type="primary" :disabled="disabled" @click="onSubmit">{{
        type == "create" ? "生成问卷" : "修改问卷"
      }}</el-button>
      <el-button type="primary" @click="onPreview">预览</el-button>
      <el-button @click="onReset" :disabled="disabled">重置</el-button>

      <!--     -->
      <el-dialog
        title="问卷题目"
        :close-on-click-modal="false"
        :visible.sync="questionStatus"
        width="415px"
        v-if="questionStatus"
      >
        <questionManger :form="form" @close="questionStatus = false" />
        <!-- <iframe
          src="http://192.168.3.8:9001/#/question"
          width="375px"
          height="667px"
          frameborder="0"
          ref="question"
          @load="loadfrom"
        ></iframe> -->
      </el-dialog>
    </div>
  </div>
</template>
<script>
import questionList from "./components/questionList";
import {
  questionnaireTopicAdd,
  questionnaireTopicGetDetail,
  questionnaireTopicUpdate,
} from "./api";
import questionManger from "./questionManger";
import AnswerList from "./components/answerList";
export default {
  name: "operationQuestion",
  components: { questionList, AnswerList, questionManger },
  data() {
    let query = this.$route.query;
    let titleName = "问卷";
    if (query.type == "create") {
      titleName = "添加" + titleName;
    } else if (query.type == "update") {
      titleName = "修改" + titleName;
    } else if (query.type == "look") {
      titleName = "查看" + titleName;
    }
    return {
      type: query.type,
      titleName: titleName,
      id: query.id,
      questionList: [],
      activeName: [],
      form: {
        title: null,
        againCommitFlag: 1,
        questionnaireQuestionList: [{ questionnaireQuestionItemList: [{}] }],
        commitType: null,
      },
      disabled: false,
      questionStatus: false,
      checkList: [],
    };
  },
  async mounted() {
    if (this.type == "update" || this.type == "look") {
      try {
        let res = await questionnaireTopicGetDetail({ id: this.id });
        this.form = res.data;
        this.questionList = res.data;
        this.settemplateType(res.data.templateType);
        this.disabled = !res.data.modifyFlag;
        // let list = res.data.questionnaireQuestionList || []
        // list.forEach((item, index) => {
        //     this.activeName.push(index)
        // })
      } catch {
        //
      }
    }
  },
  methods: {
    getForms() {
      const { $refs: refs } = this;
      return [refs.form, ...(refs.questions || [])]
        .filter((item) => !!item)
        .map((item) => item.$refs.form || item);
    },
    setResultSort() {
      // 给问答结果排序
      let form = this.form;
      form.questionnaireQuestionList.forEach((item, index) => {
        item.sort = index;
        let itemList = item.questionnaireQuestionItemList;
        if (item.type != "textarea") {
          itemList.forEach((child, index) => {
            child.sort = index;
          });
        } else {
          itemList = [];
        }
      });
    },
    onSubmit() {
      const forms = this.getForms();
      Promise.all(forms.map(this.getFormPromise)).then(async (res) => {
        const validateResult = res.every((item) => !!item);
        console.log(validateResult);
        if (validateResult) {
          this.setResultSort();
          console.log(this.form);
          try {
            if (this.type == "create") {
              await questionnaireTopicAdd(this.form);
              this.$message.success("添加成功");
            } else {
              await questionnaireTopicUpdate(this.form);
              this.$message.success("修改成功");
            }
            this.onCancel();
          } catch {
            //
          }
        } else {
          this.$nextTick(() => {
            let isError = document.getElementsByClassName("is-error");
            isError[0].scrollIntoView({
              block: "center",
              behavior: "smooth",
            });
          });
          return false;
        }
      });
    },
    getFormPromise(form) {
      return new Promise((resolve) => {
        form.validate((res) => {
          resolve(res);
        });
      });
    },

    onPreview() {
      const forms = this.getForms();
      Promise.all(forms.map(this.getFormPromise)).then(async (res) => {
        const validateResult = res.every((item) => !!item);
        if (validateResult) {
          this.questionStatus = true;
          //  验证通过    我现在的问题是如何在h5 拿到题目 不然就得复制一套过来
        }
      });
    },
    onReset() {
      this.form = {
        title: null,
        questionnaireQuestionList: [{ questionnaireQuestionItemList: [{}] }],
      };
      setTimeout(() => {
        const forms = this.getForms();
        for (let form of forms) {
          form.clearValidate();
        }
      }, 30);
    },
    // 添加题目选项
    addQuestionItem(questionnaireQuestionList) {
      questionnaireQuestionList.push({ questionnaireQuestionItemList: [{}] });
    },
    // 向上移动
    moveUp(arr, index) {
      console.log("向上移动");
      arr.splice(index, 1, ...arr.splice(index + 1, 1, arr[index]));
    },
    // 向下移动
    moveDown(arr, index) {
      console.log("向下移动");
      arr.splice(index - 1, 1, ...arr.splice(index, 1, arr[index - 1]));
    },
    // 删除选项
    onDelete(arr, index) {
      if (!this.disabled) {
        if (this.form.delQuestionnaireQuestionIdList) {
          this.form.delQuestionnaireQuestionIdList.push(arr[index].id);
          console.log(this.form.delQuestionnaireQuestionIdList);
        } else {
          this.form.delQuestionnaireQuestionIdList = [arr[index].id];
          console.log(this.form.delQuestionnaireQuestionIdList);
        }
      }
      arr.splice(index, 1);
    },
    onCancel() {
      this.$store.dispatch("delVisitedViews", this.$route);
      this.$router.push({ path: "/operateManager/setQuestions" });
    },
    loadfrom() {
      let questWindow = this.$refs.question?.contentWindow;
      console.log(questWindow, "questWindow");
      questWindow.postMessage(
        {
          cmd: "getFormJson",
          data: { ...this.form },
        },
        "*"
      );
    },
    settemplateType(index) {
      if (this.disabled) return;
      this.$set(this.form, "templateType", index);
      if (this.checkList.indexOf(index) == -1) {
        this.checkList.push(index);
      } else {
        this.checkList.splice(this.checkList.indexOf(index), 1);
      }
      this.bindCheckBox();
    },

    bindCheckBox() {
      if (this.checkList.length > 1) {
        this.checkList.splice(0, 1);
      }
      this.$set(this.form, "templateType", this.checkList[0] || null);
    },
    changeLoginFlag(val) {
      if (!val) {
        this.form.commitType = 0;
      }
    },
  },
};
</script>
<style lang="scss" scoped>
/deep/.el-date-editor.el-input {
  width: 100% !important;
}
/deep/.el-select {
  width: 98% !important;
}
/deep/.el-collapse {
  border: 0;
}
/deep/.el-collapse-item__wrap,
/deep/.el-collapse-item__header {
  background-color: #eef4f9;
}
.titleCell {
  display: inline-block;
}
/deep/.memoWrapItem {
  label {
    &:before {
      display: none;
    }
  }
}

.chioseWrap {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  .chioseItem {
    border-radius: 4px;
    overflow: hidden;
    position: relative;
    margin-right: 10px;
    width: 188px;
    height: 188px;
    cursor: pointer;
    img {
      width: 100%;
    }
    .remberBox {
      .wrap {
        width: 100px;
        height: 100px;
        z-index: 100;
        position: absolute;
        // background-color: red;
      }
      display: flex;
      flex-direction: row;
      justify-content: flex-start;
      margin-bottom: 30px;
      padding-top: 10px;
      align-items: center;
      position: relative;
      color: #6d7278;
      font-size: 16px;
      position: absolute;
      top: 1px;
      right: 1px;
      .chioseBox {
        /deep/.el-checkbox__inner {
          width: 20px;
          height: 20px;
          border-radius: 50%;
          &::after {
            height: 8px;
            left: 6px;
            position: absolute;
            top: 3px;
            width: 4px;
          }
        }
      }
      .dotWrap {
        width: 21px;
        height: 21px;
        background: url("../../assets/images/icon_checkbox_default.png")
          no-repeat center;
        background-size: contain;
        margin-right: 8px;
        position: relative;
        overflow: hidden;
        &.checked {
          background: url("../../assets/images/icon_checkbox.png") no-repeat
            center;
          background-size: contain;
        }
      }
    }
  }
}
</style>
