<template>
  <div>
    <div
      class="questions"
      v-if="questionList.length > 0"
      v-show="!resultStatus"
    >
      <div class="top-tips">{{ form.title }}</div>

      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span class="questionName">{{
            questionList[currentIndex - 1]["content"]
          }}</span>
        </div>
        <el-radio-group
          v-model="check"
          v-if="questionList[currentIndex - 1]['type'] == 'radio'"
        >
          <div
            class=""
            v-for="item in questionList[currentIndex - 1][
              'questionnaireQuestionItemList'
            ]"
            :key="item.id"
          >
            <el-radio :label="item.id">{{ item.answerValue }}</el-radio>
          </div>
        </el-radio-group>
        <el-checkbox-group
          v-model="checkBox"
          v-if="questionList[currentIndex - 1]['type'] == 'checkbox'"
        >
          <el-checkbox
            v-for="item in questionList[currentIndex - 1][
              'questionnaireQuestionItemList'
            ]"
            :key="item.id"
            :label="item.id"
            >{{ item.answerValue }}</el-checkbox
          >
        </el-checkbox-group>
        <el-input
          v-if="questionList[currentIndex - 1]['type'] == 'textarea'"
          type="textarea"
          style="border: 0"
          :autosize="{ minRows: 3, maxRows: 6 }"
          placeholder="请输入其它意见"
          v-model="textarea"
        >
        </el-input>
        <!-- 图片或者文件 -->
        <el-upload
          v-if="
            questionList[currentIndex - 1]['type'] == 'image' ||
            questionList[currentIndex - 1]['type'] == 'file'
          "
          class="ivu-upload"
          :file-list="fileList"
          :show-file-list="true"
          :headers="headers"
          :on-remove="handleRemove"
          :accept="
            questionList[currentIndex - 1]['type'] == 'image'
              ? '.jpg, .jpeg, .png'
              : '.XLSX,.XLS,.DOCX,.PDF,.TXT,.PSD,.EPS'
          "
          :before-upload="
            (flie) => {
              return beforeUpload(flie, questionList[currentIndex - 1]['type']);
            }
          "
          :on-success="
            (response, file, list) => {
              handleUploadSuccess(
                response,
                file,
                list,
                questionList[currentIndex - 1]
              );
            }
          "
          :on-error="handleUploadError"
          :max-size="2048"
          multiple
          action="/api-web/uploadFile"
        >
          <div slot="trigger" class="el-upload el-upload--picture-card">
            <i class="el-icon-plus"></i>
          </div>
          <div
            slot="tip"
            v-if="questionList[currentIndex - 1]['type'] == 'image'"
            class="el-upload__tip"
          >
            只能上传JPG、PNG、JPEG、GIF文件，且不超过5MB
          </div>
          <div slot="tip" v-else class="el-upload__tip">
            只能上传XLSX、XLS、DOCX、PDF、TXT、PSD、EPS文件，且不超过5MB
          </div>
        </el-upload>
      </el-card>
      <el-button
        size="large"
        type="primary"
        v-if="questionList[currentIndex - 1]['type'] == 'radio'"
        block
        round
        class="btn-submit"
        color="#01C1B5"
        :disabled="!check && !!isRequire"
        @click="onSubmit"
        >提交</el-button
      >
      <el-button
        size="large"
        type="primary"
        v-if="questionList[currentIndex - 1]['type'] == 'checkbox'"
        block
        round
        class="btn-submit"
        color="#01C1B5"
        :disabled="checkBox.length <= 0 && !!isRequire"
        @click="onSubmit"
        >提交</el-button
      >
      <el-button
        size="large"
        type="primary"
        v-if="questionList[currentIndex - 1]['type'] == 'textarea'"
        block
        round
        class="btn-submit"
        color="#01C1B5"
        :disabled="!textarea && !!isRequire"
        @click="onSubmit"
        >提交</el-button
      >
            <el-button
        size="large"
        type="primary"
        v-if="questionList[currentIndex - 1]['type'] == 'image'"
        block
        round
        class="btn-submit"
        color="#01C1B5"
        :disabled="fileList.length <= 0 && !!isRequire"
        @click="onSubmit"
        >提交</el-button
      >
            <el-button
        size="large"
        type="primary"
        v-if="questionList[currentIndex - 1]['type'] == 'file'"
        block
        round
        class="btn-submit"
        color="#01C1B5"
        :disabled="fileList.length <= 0 && !!isRequire"
        @click="onSubmit"
        >提交</el-button
      >
    </div>

    <div class="resultModel" v-show="resultStatus">
      <img src="@/assets/images/pay_success.png" class="img" alt="" />
      <p class="content">感谢您的参与！</p>
      <el-button
        size="large"
        type="primary"
        round
        class="btn-submit"
        @click="onSubmitClose"
        >确认</el-button
      >
    </div>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
export default {
  name: "question",
  props: ["form", "close"],
  data() {
    return {
      currentIndex: 1,
      questionList: [],
      check: null,
      isRequire: 1,
      checkBox: [],
      textarea: null,
      checkList: [],
      fileList: [],

      resultStatus: false,
      headers: {
        Authorization: getToken(),
      },
    };
  },
  async mounted() {
    try {
      this.questionList = this.form.questionnaireQuestionList || [];
      console.log(this.questionList);
      this.isRequire = this.questionList[this.currentIndex - 1].isRequire;
    } catch {
      //
    }
  },
  methods: {
    toggle(index) {
      let selectList = this.questionList[this.currentIndex - 1];
      if (selectList.type == "radio") {
        this.check = index;
      } else if (selectList.type == "checkbox") {
        this.$refs.checkboxes[index].toggle();
      }
    },
    onSubmit() {
      let selectList = this.questionList[this.currentIndex - 1];
      if (selectList.type == "radio" && selectList.isRequire && !this.check) {
        this.$message.error("请回答当前问题");
        return;
      } else if (
        selectList.type == "checkbox" &&
        selectList.isRequire &&
        this.checkBox.length <= 0
      ) {
        this.$message.error("请回答当前问题");
        return;
      } else if (
        selectList.type == "textarea" &&
        selectList.isRequire &&
        !this.textarea
      ) {
        this.$message.error("请回答当前问题");
        return;
      } else if (
        selectList.type == "image" &&
        selectList.isRequire &&
        this.fileList.length <= 0
      ) {
        this.$message.error("请回答当前问题");
        return;
      } else if (
        selectList.type == "file" &&
        selectList.isRequire &&
        this.fileList.length <= 0
      ) {
        this.$message.error("请回答当前问题");
        return;
      }

      let answerList = selectList.questionnaireQuestionItemList || []; //当前题的选项
      let currentIsOver = 0; // 是否终止答题
      answerList.forEach((item) => {
        if (selectList.type == "radio" && this.check == item.id) {
          currentIsOver = item.isOver;
        } else if (
          selectList.type == "checkbox" &&
          this.checkBox.includes(item.id) &&
          !currentIsOver
        ) {
          currentIsOver = item.isOver;
        }
      });

      // 判断是否在题目列表里面
      if (this.currentIndex <= this.questionList.length) {
        if (selectList.type == "radio") {
          this.checkList[this.currentIndex - 1] = {
            questionnaireQuestionId: selectList.id,
            questionnaireQuestionItemIdList: this.check,
          };
          this.check = null;
        } else if (selectList.type == "checkbox") {
          this.checkList[this.currentIndex - 1] = {
            questionnaireQuestionId: selectList.id,
            questionnaireQuestionItemIdList: this.checkBox.join(","),
          };
          this.checkBox = [];
        } else if (selectList.type == "textarea") {
          this.checkList[this.currentIndex - 1] = {
            questionnaireQuestionId: selectList.id,
            additionalValue: this.textarea,
          };
          this.textarea = null;
        } else if (selectList.type == "image") {
          this.checkList[this.currentIndex - 1] = {
            questionnaireQuestionId: selectList.id,
            additionalValue: JSON.stringify(
              this.fileList.map((item) => {
                return {
                  name: item.name,
                  url: item.response.data.url,
                };
              })
            ),
          };
         this.fileList = [];
        } else if (selectList.type == "file") {
          this.checkList[this.currentIndex - 1] = {
            questionnaireQuestionId: selectList.id,
            additionalValue: JSON.stringify(
              this.fileList.map((item) => {
                return {
                  name: item.name,
                  url: item.response.data.url,
                };
              })
            ),
          };
         this.fileList = [];
        }

        // 1 为终止答题
        if (currentIsOver) {
          this.onConfirm();
          return;
        }

        this.check = null;
        if (this.currentIndex == this.questionList.length) {
          this.saveKey();
          return;
        }
        this.currentIndex++;
      }
    },
    saveKey() {
      // this.$message.info('谢谢参与')
      this.resultStatus = true;
    },
    async onConfirm() {
      // this.$message.info('谢谢参与')
      this.resultStatus = true;
    },
    onSubmitClose() {
      this.close();
    },
    beforeUpload(file, type) {
      // const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 5;
      const imgType = ["JPG", "PNG", "JPEG", "GIF"];
        const testType = ["XLSX", "XLS", "DOCX", "PDF", "TXT","PSD","EPS"];
      const fileExtension = file.name.split(".").pop().toUpperCase();
      console.log(
        type,
        fileExtension,
        testType,
        testType.indexOf(fileExtension) != -1
      );
      let fileType = false;
      if (type == "file") {
        if (testType.indexOf(fileExtension) != -1) {
          fileType = true;
        } else {
          this.$message.error("请上传正确的附件!");
          return false;
        }
      } else if ((type = "image")) {
        if (imgType.indexOf(fileExtension) != -1) {
          fileType = true;
        } else {
          this.$message.error("请上传正确的附件!");
          return false;
        }
      }
      //   if (!isJPG) {
      //     this.$message.error('上传头像图片只能是 JPG 格式!');
      //   }
      if (!isLt2M) {
        this.$message.error("上传附件大小不能超过 5MB!");
      }
      this.uploadLoading = true;
      return isLt2M && fileType;
    },
    handleUploadError(file) {
      this.uploadLoading = false;
      this.$message.error("上传附件失败");
    },
    handleUploadSuccess(response, file, list, question) {
      this.uploadLoading = false;
      this.$message.success("上传附件成功");
      this.fileList = [...list];
      console.log(this.fileList);
      // this.fileList.push(file)
    },
    handleRemove(file, list) {
      this.fileList = [...list];
      console.log(this.fileList);
    },
  },
};
</script>

<style lang="less" scoped>
.top-tips {
  color: #808080;
  font-size: 14px;
  padding: 0 0 10px;
}

.btn-submit {
  width: 90%;
  margin: 20px 5%;
}

.form-info {
  margin: 10px;
  width: auto;
  border-radius: 5px;
}
.questionName {
  padding-top: 5px;
  font-size: 16px;
  color: #444;
  font-weight: 500;
  line-height: 1.5;
}
/deep/.el-radio-group,
/deep/.el-checkbox-group {
  width: 100%;
}
/deep/.el-radio__input.is-checked + .el-radio__label {
  color: #606266;
}
/deep/.el-radio,
/deep/.el-checkbox {
  width: 100%;
  display: flex;
  justify-content: space-between;
  flex-direction: row-reverse;
  padding: 10px 0;
  .el-radio__label,
  .el-checkbox__label {
    padding-left: 0;
  }
}
/deep/.el-button--primary {
  background: #01c1b5 !important;
  border-color: #01c1b5 !important;
}
/deep/.el-upload {
  display: block;
}
/deep/.el-upload--picture-card {
  width: 100%;
  height: 100px;
  align-items: center;
  display: flex;
  flex-direction: row;
  justify-content: center;
}

.resultModel {
  .img {
    width: 145px;
    margin: 0 auto;
    display: block;
    // padding-top: 50px;
  }
  .content {
    font-size: 20px;
    color: #1a1a1a;
    text-align: center;
    font-weight: 500;
    padding-bottom: 30px;
  }
}
</style>
