<template>
  <div class="questionnaire-cont app-container">
    <el-card :style="{height: scrollHeight} ">
      <div style="display: flex; justify-content: center; font-size: 30px; font-weight: 700" class="mt20, title">
        调查问卷——{{ questionnaireTitle }}
      </div>
      <el-row :gutter="10" class="mb8">
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
      <el-table v-loading="loading" :data="activityList" @selection-change="handleSelectionChange">
        <el-table-column label="排序" sortable prop="nrPx" min-width="50px" align="center"/>
        <el-table-column label="标题" min-width="150px" align="center" prop="nrBt" show-overflow-tooltip/>
        <el-table-column label="题型" min-width="100px" align="center" prop="nrLx">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.quiz_type" :value="scope.row.nrLx"/>
          </template>
        </el-table-column>
        <el-table-column label="是否必填" min-width="50px" align="center" prop="nrSfbt" width="100">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.is_required" :value="scope.row.nrSfbt"/>
          </template>
        </el-table-column>
        <el-table-column key="option" width="200px" label="选项 ( 点击查看 )" type="expand" align="center" prop="nr">
          <template slot-scope="scope">
            <div v-for="item in opinionList[scope.$index]"
                 style="font-size: 15px;margin-top: 10px; margin-left: 15px">
              <span style="font-weight: bold">{{ item[0] }} ：</span><span>{{ item[1] }}</span>
            </div>
          </template>
        </el-table-column>
        <!--      <el-table-column key="option" min-width="250px" label="选项" align="center" prop="nr" show-overflow-tooltip/>-->
      </el-table>
      <ExPagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改问卷调查内容对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" :disabled="isDisabled" label-width="80px">
        <el-row>
          <el-form-item label="排序" prop="nrPx">
            <el-input-number v-model="form.nrPx" :min="1" :max="100" label="排序"></el-input-number>
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="题型" prop="nrLx">
              <el-select v-model="form.nrLx" placeholder="请选择题目类型" style="width: 100%;">
                <el-option :label="dict.label" :value="dict.value" v-for="dict in dict.type.quiz_type"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :offset="2" :span="11">
            <el-form-item label="是否必填" prop="nrSfbt">
              <el-select v-model="form.nrSfbt" placeholder="请选择题目是否必填" style="width: 100%;">
                <el-option :label="dict.label" :value="dict.value" v-for="dict in dict.type.is_required"></el-option>
              </el-select>
              <!--<el-input v-model="form.sort" placeholder="请输入序号"/>-->
              <!--              <el-input-number :min="0" v-model="form.sort" controls-position="right"-->
              <!--                               style="width: 100%;"></el-input-number>-->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="标题" prop="nrBt">
              <el-input type="textarea" v-model="form.nrBt" placeholder="请输入题目标题"/>
            </el-form-item>
          </el-col>
        </el-row>
        <div v-show="form.nrLx==0 || form.nrLx==1">
          <el-row>
            <el-col :span="24">
              <el-form-item label="选项A" prop="nrA">
                <el-input v-model="form.nrA" placeholder=""/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="选项B" prop="nrB">
                <el-input v-model="form.nrB" placeholder=""/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="选项C" prop="nrC">
                <el-input v-model="form.nrC" placeholder=""/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="选项D" prop="nrD">
                <el-input v-model="form.nrD" placeholder=""/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="选项E" prop="nrE">
                <el-input v-model="form.nrE" placeholder=""/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="选项F" prop="nrF">
                <el-input v-model="form.nrF" placeholder=""/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="选项G" prop="nrG">
                <el-input v-model="form.nrG" placeholder=""/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="选项H" prop="nrH">
                <el-input v-model="form.nrH" placeholder=""/>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-show="!isDisabled" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">{{ isDisabled ? '退 出' : '取 消' }}</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框相关 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        accept=".xlsx, .xls"
        :limit="1"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :headers="upload.headers"
        :http-request="excelFileUploadMain"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!--            <div class="el-upload__tip" slot="tip">-->
          <!--              <el-checkbox v-model="upload.updateSupport"/>-->
          <!--              是否更新已经存在的用户数据-->
          <!--            </div>-->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
          >下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!--    </div>-->
    <!--    <div v-else>-->
    <!--      <div style="display: flex; justify-content: center; font-size: 30px; font-weight: 300" class="mb20">调查问卷——{{-->
    <!--          questionnaireTitle-->
    <!--        }}-->
    <!--      </div>-->
    <!--      <el-row :gutter="10" class="mb8">-->
    <!--        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
    <!--      </el-row>-->
    <!--      <el-table v-loading="loading" :data="activityList" @selection-change="handleSelectionChange">-->
    <!--        <el-table-column label="排序" sortable prop="nrPx" min-width="50px" align="center"/>-->
    <!--        <el-table-column label="标题" min-width="150px" align="center" prop="nrBt" show-overflow-tooltip/>-->
    <!--        <el-table-column label="题型" min-width="100px" align="center" prop="nrLx">-->
    <!--          <template slot-scope="scope">-->
    <!--            <dict-tag :options="dict.type.quiz_type" :value="scope.row.nrLx"/>-->
    <!--          </template>-->
    <!--        </el-table-column>-->
    <!--        <el-table-column label="是否必填" min-width="50px" align="center" prop="nrSfbt" width="100">-->
    <!--          <template slot-scope="scope">-->
    <!--            <dict-tag :options="dict.type.is_required" :value="scope.row.nrSfbt"/>-->
    <!--          </template>-->
    <!--        </el-table-column>-->
    <!--        <el-table-column key="option" width="200px" label="选项(点击可查看)" type="expand" align="center" prop="nr"-->
    <!--                         show-overflow-tooltip>-->
    <!--          <template slot-scope="scope">-->
    <!--            {{ scope.row.nr }}-->
    <!--          </template>-->
    <!--        </el-table-column>-->

    <!--      </el-table>-->

    <!--      <ExPagination-->
    <!--        v-show="total>0"-->
    <!--        :total="total"-->
    <!--        :page.sync="queryParams.pageNum"-->
    <!--        :limit.sync="queryParams.pageSize"-->
    <!--        @pagination="getList"-->
    <!--      />-->

    <!--    </div>-->
  </div>
</template>

<script>
import {
  getList,
  findOne,
  addToList,
  editOnList,
  deleteData,
  handleImport,
} from "@/api/smartSchool/questionnaireManagement/QuestionnaireContent/request.js";

import {getToken} from "@/utils/auth";
import {isValidNum, ordinaryValidator} from "@/utils/utilLibrary/jaytherValidate";
import {closeCurrentTab} from "@/utils/utilLibrary/routerBatch/routerBatch";
import {QUESTION_STATE} from "@/enums/questionnaire/content";

export default {
  name: "ClassAdviserQuestionnaireContent",
  dicts: ["quiz_type", "is_required"],
  data() {
    this.isValidNum = ordinaryValidator(isValidNum, '请填写数字', true)
    return {
      scrollHeight: document.body.scrollHeight + 'px',
      opinionList: "",
      questionnaireTitle: "",
      QUESTION_STATE,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 问卷调查内容表格数据
      activityList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //!!!==页面关键(传参)变量：examId==!!!//
      examId: null,
      // 问卷调查状态
      state: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nrBt: null,
      },
      // 表单参数

      form: {
        nrPx: "8",
        nrLx: null,
        nrSfbt: null,
        nrBt: null,
        id: null,
        nrA: null,
        nrB: null,
        nrC: null,
        nrD: null,
        nrE: null,
        nrF: null,
        nrG: null,
        nrH: null,
        nrI: null,
      },
      // 表单校验
      rules: {
        nrPx: [
          {required: true, message: "排序不能为空", trigger: "blur"}
        ],
        nrLx: [
          {required: true, message: "题型不能为空", trigger: "blur"}
        ],
        nrSfbt: [
          {required: true, message: "是否必填不能为空", trigger: "blur"}
        ],
        nrBt: [
          {required: true, message: "标题不能为空", trigger: "blur"}
        ]
        // nrBt: [
        //   {validator: this.isValidNum, message: "请输入数字", trigger: "blur"}
        // ]
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + `/dcwjNr/importData/${this.examId}`,
      },
      // 用户导出选项
      exportParam: {
        open: false,
        option: "0",
      },
      // 是否禁用表单
      isDisabled: false
    };
  },
  created() {
    // 获取问卷id
    this.examId = +this.$route.params.examId;
    // 获取当前问卷调查的状态
    this.state = this.$route.query && this.$route.query.state;
    // 获取当前问卷调查名称
    this.questionnaireTitle = this.$route.query && this.$route.query.title;
    this.form.examId = this.examId;
    this.getList();
  },
  methods: {
    // 路由工具库模块
    closeCurrentTab,
    /** 查询问卷调查内容列表 */
    getList() {
      this.loading = true;
      getList({...this.queryParams, dcwjId: this.examId}).then(response => {
        this.activityList = response.rows

        /** 处理选项内容开始 */
        let arr = response.rows.map((item) => {
          return item.nr
        })
        arr = arr.map((item) => {
          return item.split(";")
        })
        arr = arr.map((item) => {
          item.pop()
          return item
        })
        this.opinionList = arr.map((item) => {
          item = item.map((items) => {
            return items.split(":")
          })
          return item
        })
        /** 处理选项内容结束 */
        this.total = response.total;
        this.loading = false;
      }).catch(error => {
        console.error(error);
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        examId: this.examId,
        id: null,
        sort: null,
        quizTitle: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.isDisabled = false;
      this.title = "添加问卷调查内容";
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids[0]
      let response = await findOne(id)
      if (response) {
        this.form = response.data;
        this.open = true;
        this.isDisabled = false;
        this.title = "修改问卷调查内容";
      }
    },
    /** 查看详情按钮 */
    async handleDetail(row) {
      this.reset();
      const id = row.id || this.ids[0]
      let response = await findOne(id)
      if (response) {
        this.form = response.data;
        this.open = true;
        this.isDisabled = true;
        this.title = "查看问卷调查内容";
      }
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.loading = true
          let submitData = this.form
          if (this.form.nrLx == 0 || this.form.nrLx == 1) {

          } else {
            this.form.nrA = null,
              this.form.nrB = null,
              this.form.nrC = null,
              this.form.nrD = null,
              this.form.nrE = null,
              this.form.nrF = null,
              this.form.nrG = null,
              this.form.nrH = null,
              this.form.nrI = null
          }
          if (this.form.id != null) {
            editOnList(submitData, this.examId).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.loading = false
              this.open = false;
              this.getList();
            });
          } else {
            addToList(submitData, this.examId).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.loading = false
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除所选的调查问卷题目？').then(function () {
        return deleteData(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch((err) => {
        console.error(err)
      });
    },
    /** 导出按钮操作 */
    handleOpenExport() {
      this.download(`/dcwjNr/export/${this.examId}`, {
      }, `问卷内容${Date.now()}.xlsx`)
    },
    /** 主导出操作 */
    handleExport() {
      const allIds = this.activityList.map(item => item.id)
      const ids = (JSON.stringify(this.ids) !== '[]') ? this.ids : allIds
      switch (this.exportParam.option) {
        // 导出当前页(不按筛选条件过滤)
        case "0":
          this.download(`/dcwjNr/export/${allIds}`, {}, `问卷调查活动${Date.now()}.xlsx`);
          break;
        // 根据筛选框内容导出
        case "1":
          this.download(`/dcwjNr/export/${ids}`, this.queryParams, `问卷调查活动${Date.now()}.xlsx`);
          break;
        // 导出全部数据
        case "2":
          this.download('/dcwjNr/export', {}, `问卷调查活动${Date.now()}.xlsx`);
          break;
      }
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
      // console.log(event, file, fileList);
    },
    // // 文件上传自定义函数
    async excelFileUploadMain(fileObj) {
      //将文件放进表单对象进行上传
      let res;
      let fd = new FormData();
      fd.append("file", fileObj.file);
      try {
        // res = (await handleImport(fd)).data;
        res = await handleImport(fd, this.examId);
        console.log(res,540);
        //沿袭文件上传成功时的响应函数
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert(
          "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          res.msg +
          "</div>",
          "导入结果",
          {dangerouslyUseHTMLString: true}
        );
        this.getList();
      } catch (error) {
        console.error(error);
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$message.error(res.msg);
      }
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    importTemplate() {
      this.download(
        "/dcwjNr/importTemplate",
        {},
        `问卷调查内容模板_${Date.now()}.xlsx`
      );
    }
  }
}
</script>

<style scoped lang="scss">
.title {
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
}
</style>
