<template>
  <div
    class="pb_content"
    style="
      margin: 20px;
      width: 98%;
      height: 95%;
      min-height: 750px;
      border-radius: 5px;
      min-width: 960px;
      background: unset;
      padding-top: 20px;
    "
  >
    <div
      class="pb_content_body"
      style="
        background: #fff;
        padding: 0px 25px;
        box-sizing: border-box;
        border-radius: 5px;
      "
    >
      <div class="pb_head">
        <span>问卷调查</span>
        <div class="askButton">
          <el-button type="primary" @click="createPop">创建问卷调查</el-button>
          <el-button
            type="primary"
            @click="goTo('/ask/askList?userid=' + userid)"
            >查看已提交问卷</el-button
          >
        </div>
      </div>
    </div>
    <div class="pb_content_body">
      <div class="student_table">
        <el-table
          ref="table"
          :data="tableData"
          border
          :height="tableHeight"
          :fit="true"
          v-loading="isLoading"
          style="width: 100%"
          :header-cell-style="{ background: '#f1f1f1', fontSize: '17px' }"
          :row-class-name="tableRowClassName"
        >
          <el-table-column
            prop="title"
            label="问卷调查标题"
            min-width="45"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="name"
            label="创建者"
            min-width="15"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="time"
            label="创建时间"
            min-width="15"
            align="center"
          >
          </el-table-column>
          <el-table-column label="操作" min-width="30">
            <template slot-scope="scope">
              <el-button @click="getPop(scope.row)" type="text" size="small"
                >查看</el-button
              >
              <el-button @click="staticsPop(scope.row)" type="text" size="small"
                >数据统计</el-button
              >
              <el-button @click="deleteAsk(scope.row.id)" type="text" size="small"
                >删除问卷</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="student_page">
        <el-pagination
          background
          layout="prev, pager, next"
          :page-size="10"
          :total="total"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog
      title="创建问卷调查"
      :visible.sync="dialogVisible"
      :append-to-body="true"
      width="800px"
      :before-close="handleClose"
      class="dialog_diy"
    >
      <div>
        <div
          class="a_add_title"
          style="
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: center;
          "
        >
          <div style="margin-right: 20px; font-size: 20px">问卷标题:</div>
          <el-input
            v-model="askTitle"
            placeholder="请输入问卷标题"
            style="width: 400px"
          ></el-input>
        </div>
        <div class="a_addBox">
          <div style="font-size: 16px; color: #c7c7c7">请输入问卷内容</div>
          <div
            class="a_add_box"
            v-for="(item, index) in itemCount"
            :key="index"
          >
            <div class="a_add_head">
              <div>
                {{ index + 1 + "、" }}
                <el-input
                  class="a_add_head_input"
                  v-model="askJson[index].askstitle"
                  placeholder="请输入问卷题目..."
                ></el-input>
              </div>
              <div class="a_add_head_div">
                <el-button type="primary" size="small" @click="addAskList()"
                  >添加</el-button
                >
                <el-button
                  type="primary"
                  size="small"
                  @click="deleteAskList()"
                  v-if="index != 0"
                  >删除</el-button
                >
              </div>
            </div>
            <div class="a_add_body">
              <div class="a_add_input">
                <el-input
                  v-for="(item, checkIndex) in askJson[index].askItem"
                  :key="checkIndex"
                  v-model="askJson[index].checkList[checkIndex]"
                  placeholder="请输入选项..."
                  style="width: 150px; margin: 10px 10px 0 0"
                ></el-input>
              </div>
              <div class="a_add_body_div">
                <el-button
                  style="margin: 10px 0px 0 0"
                  type="primary"
                  size="small"
                  @click="addcheckList(askJson[index])"
                  >添加</el-button
                >
                <el-button
                  type="primary"
                  size="small"
                  style="margin: 10px 0 0 0"
                  @click="deletecheckList(askJson[index])"
                  v-if="askJson[index].askItem != 1"
                  >删除</el-button
                >
              </div>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addAsk">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="查看"
      :visible.sync="dialogVisible1"
      :append-to-body="true"
      width="750px"
      :before-close="handleClose"
      class="dialog_diy"
    >
      <div>
        <div class="a_add_title">
          <!-- <el-input
            v-model="askTitle"
            placeholder="请输入问卷标题"
            style="width: 400px"
          ></el-input> -->
          <h1>{{ askTitle }}</h1>
        </div>
        <div class="a_addBox">
          <div
            class="a_add_box"
            v-for="(item, index) in itemCount"
            :key="index"
          >
            <div class="a_add_head">
              <div>
                <!-- {{ index + 1 + "、" }}
                <el-input
                  class="a_add_head_input"
                  v-model="askJson[index].askstitle"
                  placeholder="请输入问卷题目..."
                ></el-input> -->
                <span>{{ index + 1 + "、" + askJson[index].askstitle }}</span>
              </div>
            </div>
            <div class="a_add_body">
              <div class="a_add_input">
                <el-radio-group>
                  <el-radio
                    :label="item"
                    v-for="(item, checkIndex) in askJson[index].askItem"
                    style="width: 150px; margin: 10px 10px 0 0"
                    :key="checkIndex"
                    disabled
                    >{{ askJson[index].checkList[checkIndex] }}</el-radio
                  >
                </el-radio-group>
              </div>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible1 = false">关 闭</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="数据统计"
      :visible.sync="dialogVisible2"
      :append-to-body="true"
      width="750px"
      :before-close="handleClose"
      class="dialog_diy"
    >
      <div>
        <div class="a_add_title">
          <h1>{{ askTitle }}</h1>
        </div>
        <div class="a_addBox">
          <div
            class="a_add_box"
            v-for="(item, index) in itemCount"
            :key="index"
          >
            <div class="a_add_head">
              <div>
                <span>{{ index + 1 + "、" + askJson[index].askstitle }}</span>
              </div>
            </div>
            <div class="a_add_body">
              <div class="a_add_input width100">
                <div
                  class="a_add_persent a_add_persent_div a_add_persent_title"
                >
                  <span>选项</span><span>小计</span><span>比列</span>
                </div>
                <div class="a_add_persent">
                  <div
                    class="a_add_persent_div"
                    v-for="(item, checkIndex) in askJson[index].askItem"
                    :key="checkIndex"
                  >
                    <span>{{ askJson[index].checkList[checkIndex] }}</span>
                    <span>{{
                      checkJson[index].checkCount[checkIndex]
                        ? checkJson[index].checkCount[checkIndex]
                        : 0
                    }}</span>
                    <span>
                      <el-progress
                        :percentage="
                          checkJson[index].checkPerent[checkIndex]
                            ? checkJson[index].checkPerent[checkIndex]
                            : 0
                        "
                        :show-text="false"
                      ></el-progress>
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible2 = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tableData: [],
      userid: this.$route.query.userid,
      tableHeight: 500,
      isLoading: false,
      page: 1,
      total: 0,
      dialogVisible: false,
      itemCount: 1,
      askTitle: "",
      askJson: [{ askstitle: "", askItem: 1, checkList: [] }],
      dialogVisible1: false,
      dialogVisible2: false,
      checkJson: [{ checkCount: [], checkPerent: [] }],
    };
  },
  methods: {
    tableRowClassName({ row, rowIndex }) {
      if ((rowIndex + 1) % 2 === 0) {
        return "even_row";
      } else {
        return "";
      }
    },
    addAskList() {
      this.checkJson.push({ checkCount: [], checkPerent: [] });
      this.askJson.push({ askstitle: "", askItem: 1, checkList: [] });
      this.itemCount++;
    },
    addcheckList(json) {
      json.checkList.length++;
      json.askItem++;
    },
    deleteAskList() {
      this.askJson.splice(-1);
      this.itemCount--;
    },
    deletecheckList(json) {
      json.checkList.length--;
      json.askItem--;
    },
    handleClose(done) {
      done();
    },
    goTo(path) {
      this.$router.push(path);
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getAsk();
    },
    time() {
      if (!this.now) {
        this.now = new Date().getTime();
        return true;
      } else {
        let time = new Date().getTime();
        if (time - this.now > 3000) {
          this.now = time;
          return true;
        } else {
          return false;
        }
      }
    },
    changeHeight() {
      this.tableHeight =
        window.innerHeight - this.$refs.table.$el.offsetTop - 200;
      if (this.tableHeight <= 530) {
        this.tableHeight = 530;
      }
      // 监听窗口大小变化
      let self = this;
      window.onresize = function () {
        self.tableHeight =
          window.innerHeight - self.$refs.table.$el.offsetTop - 200;
        if (self.tableHeight <= 530) {
          self.tableHeight = 530;
        }
      };
      // this.$refs.table.$el.offsetTop：表格距离浏览器的高度 //200表示你想要调整的表格距离底部的高度（你可以自己随意调整），因为我们一般都有放分页组件的，所以需要给它留一个高度
    },
    init() {
      this.askTitle = "";
      this.itemCount = 1;
      this.askJson = [{ askstitle: "", askItem: 1, checkList: [] }];
    },
    createPop() {
      this.dialogVisible = true;
      this.askTitle = "";
      this.itemCount = 1;
      this.askJson = [{ askstitle: "", askItem: 1, checkList: [] }];
    },
    addAsk() {
      if (this.askTitle === "") {
        this.$message.error("问卷调查标题不能为空！");
        return;
      }
      var aj = this.askJson;
      var b = 1;
      for (var i = 0; i < aj.length; i++) {
        if (aj[i].askstitle === "") {
          var a = 1;
          for (let index = 0; index < aj[i].askItem; index++) {
            const element = aj[i].checkList[index]
              ? aj[i].checkList[index]
              : "";
            if (element != "") {
              b++;
              this.$message.error("填写了问卷调查选项，问卷调查题目不能为空！");
              return;
            } else {
              a++;
            }
          }
          if (b == 1) {
            this.$message.error("至少填写一个问题");
            return;
          }
          // if (a > 1) {
          //   aj.splice(i, 1);
          // }
        } else if (aj[i].askstitle != "") {
          for (let index = 0; index < aj[i].askItem; index++) {
            const element = aj[i].checkList[index]
              ? aj[i].checkList[index]
              : "";
            var index = 0;
            for (var z = 0; z < aj[i].checkList.length; z++) {
              var checkC = aj[i].checkList[z] ? aj[i].checkList[z] : "";
              if (checkC != "") {
                index++;
              } else {
                this.$message.error("问卷调查选项不能为空！");
                return;
              }
            }
            b++;
            if (index < 2) {
              this.$message.error(
                "填写了问卷调查的题目，问卷调查选项至少要有两项！"
              );
              return;
            }
            // if (element == "") {
            //   this.$message.error(
            //     "填写了问卷调查的题目，问卷调查选项不能为空！"
            //   );
            //   return;
            // }
          }
        }
      }
      this.askJson = this.askJson.filter((el) => {
        var elc = el.checkList.filter((element) => {
          return element != "";
        });
        return el.askstitle != "" && elc.length != 0;
      });
      let params = [
        {
          t: this.askTitle,
          c: JSON.stringify(this.askJson),
          cuser: this.userid,
        },
      ];
      if (this.time()) {
        this.ajax
          .post(this.$store.state.api + "addAsk", params)
          .then((res) => {
            this.$message({
              message: "添加成功",
              type: "success",
            });
            this.init();
            this.dialogVisible = false;
            this.getAsk();
          })
          .catch((err) => {
            this.dialogVisible = false;
            this.$message.error("添加失败");
            console.error(err);
          });
      }
    },
    //获取
    getAsk() {
      this.isLoading = true;
      let params = {
        uid: this.userid,
        page: this.page,
      };
      this.ajax
        .get(this.$store.state.api + "getAsk", params)
        .then((res) => {
          this.isLoading = false;
          this.total = res.data[0].length > 0 ? res.data[0][0].num : 0;
          this.tableData = res.data[0];
        })
        .catch((err) => {
          this.dialogVisible = false;
          console.error(err);
        });
    },
    getPop(res) {
      this.askTitle = res.title;
      this.askJson = JSON.parse(res.content);
      this.itemCount = this.askJson.length;
      for (var i = 0; i < this.askJson.length; i++) {
        this.checkJson.push({ checkCount: [], checkPerent: [] });
        for (var j = 0; j < this.askJson[i].askItem; j++) {
          this.checkJson[i].checkPerent.push(0);
          this.checkJson[i].checkCount.push(0);
        }
      }
      this.dialogVisible1 = true;
    },
    staticsPop(res) {
      this.askTitle = res.title;
      this.askJson = JSON.parse(res.content);
      this.itemCount = this.askJson.length;
      let params = {
        aid: res.id,
      };
      this.ajax
        .get(this.$store.state.api + "getAskListByAskid", params)
        .then((res) => {
          this.checkJson = [];
          if (res.data[0].length == 0) {
            for (var i = 0; i < this.askJson.length; i++) {
              this.checkJson.push({ checkCount: [], checkPerent: [] });
              for (var j = 0; j < this.askJson[i].askItem; j++) {
                this.checkJson[i].checkPerent.push(0);
                this.checkJson[i].checkCount.push(0);
              }
            }
          } else {
            for (var i = 0; i < res.data[0].length; i++) {
              var data = res.data[0][i];
              var checkL = data.content.split(",");
              for (var j = 0; j < checkL.length; j++) {
                this.checkJson.push({ checkCount: [], checkPerent: [] });
                if (!this.checkJson[j].checkCount) {
                  this.checkJson[j].checkCount = [];
                  this.checkJson[j].checkCount.length = this.askJson[j].askItem;
                }
                this.checkJson[j].checkCount[parseInt(checkL[j]) - 1]
                  ? this.checkJson[j].checkCount[parseInt(checkL[j]) - 1]++
                  : (this.checkJson[j].checkCount[parseInt(checkL[j]) - 1] = 1);
              }
            }
            for (var i = 0; i < this.checkJson.length; i++) {
              this.checkJson[i].checkPerent = [];
              for (var j = 0; j < this.checkJson[i].checkCount.length; j++) {
                this.checkJson[i].checkPerent.push(
                  Math.round(
                    (this.checkJson[i].checkCount[j] /
                      parseInt(res.data[0][0].num)) *
                      100
                  )
                );
              }
            }
          }
          console.log(res.data[0]);
          this.dialogVisible2 = true;
        })
        .catch((err) => {
          console.error(err);
        });
    },
    deleteAsk(id){
      let params = [{ id: id }];
      this.$confirm("确定删除此问卷吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.ajax
            .post(this.$store.state.api + "deleteAsk", params)
            .then((res) => {
              this.$message({
                message: "删除成功",
                type: "success",
              });
              if (this.page != 1 && this.tableData.length == 1) {
                this.page--;
              }
              this.getAsk();
            })
            .catch((err) => {
              this.$message.error("删除失败");
              console.error(err);
            });
        })
        .catch(() => {});
    }
  },
  created() {
    this.$nextTick(function () {
      this.page = 1;
      this.changeHeight();
      this.getAsk();
    });
  },
};
</script>

<style scoped>
.dialog_diy >>> .el-dialog__header {
  background: #3d67bc !important;
  padding: 15px 20px;
}
.dialog_diy >>> .el-dialog__title {
  color: #fff;
}
.dialog_diy >>> .el-dialog__headerbtn {
  top: 19px;
}
.dialog_diy >>> .el-dialog__headerbtn .el-dialog__close {
  color: #fff;
}
.dialog_diy >>> .el-dialog__headerbtn .el-dialog__close:hover {
  color: #fff;
}
/* .dialog_diy >>> .el-dialog__body {
  max-height: 750px;
  overflow: auto;
} */
.dialog_diy >>> .el-dialog {
  background: #fafafa;
}
.pb_head {
  justify-content: space-between;
  display: flex;
  align-items: center;
}
.student_table {
  margin: 20px 0;
}

.a_add_title {
}
.a_addBox {
  margin: 10px 0;
  background: #fff;
  padding: 15px;
  max-height: 400px;
  overflow: auto;
}
.a_add_box {
  border-bottom: 2px solid #eee;
  padding-bottom: 10px;
}

.a_add_head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 10px 0;
  font-size: 18px;
}
.a_add_head .a_add_head_input {
  width: 300px;
}
.a_add_head .a_add_head_div {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.a_add_body {
  display: flex;
  align-items: center;
}
.a_add_input {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  /* flex-direction: column; */
  /* width: 100%; */
}
.width100 {
  width: 100%;
}
.a_add_input .a_add_persent {
  /* display: flex; */
  /* flex-direction: column; */
  width: 100%;
}
.a_add_persent_div {
  width: 100%;
  display: flex;
  align-items: center;
}
.a_add_persent_div span {
  margin: 5px 0;
}
.a_add_persent_div span:nth-child(1) {
  width: 30%;
}
.a_add_persent_div span:nth-child(2) {
  width: 7%;
}
.a_add_persent_div span:nth-child(3) {
  width: 40%;
}
.a_add_persent_title {
  /* margin-bottom: 10px; */
}
.a_add_body_div {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
.askButton > button {
  color: #fff;
  background: #2268bc;
  width: 105px;
  height: 40px;
  padding: 0 !important;
  font-size: 12px;
  line-height: 40px;
}
.student_table >>> .el-table--border td {
  border-right: 0px !important;
}
.el-table >>> .even_row {
  background-color: #f1f1f1 !important;
}
</style>
