<template>
  <div class="activity-result app-container">
    <el-tabs tab-position="left" style="height: 100%;">
      <el-tab-pane label="明细数据">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="80px">
          <el-form-item label="姓名" prop="studentName">
            <el-input v-model="queryParams.studentName" placeholder="请输入姓名" clearable
                      @keyup.enter.native="handleQuery">
            </el-input>
          </el-form-item>
          <el-form-item label="填写状态" prop="ryZdzt">
            <el-select v-model="queryParams.ryZdzt" style="width: 100%" placeholder="请选择问卷填写状态">
              <el-option
                v-for="dict in dict.type.quiz_txzt"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="填写时间">
            <el-date-picker
              v-model="dateRange"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleOpenExport">导出
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="el-icon-close" size="mini" @click="closeCurrentTab">关闭
            </el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
        <el-table v-loading="loading" :data="activityList" @selection-change="handleSelectionChange">
          <el-table-column type="index" label="序号" width="55" align="center"/>
          <el-table-column v-if="pubType==0" label="班级" align="center" prop="classAlias"/>
          <el-table-column label="姓名" align="center" prop="studentName"/>
          <el-table-column label="填写状态" align="center" prop="ryZdzt">
            <template slot-scope="scope">
              <span>{{ scope.row.ryZdzt == 0 ? '未填写' : '已填写' }} </span>
            </template>
          </el-table-column>
          <el-table-column label="填写时间" align="center" min-width="120px" prop="ryCtime"/>
          <el-table-column v-for="(item,index) in dynamicTitle" :label="item" min-width="150px" align="center">
            <template slot-scope="scope">
              <ListImage v-if="scope.row[dynamicProp[index]] && scope.row[dynamicProp[index]].type==3"
                         :image-url=" scope.row[dynamicProp[index]] && baseUrl+scope.row[dynamicProp[index]].datas"
                         style="height: 50px"></ListImage>
              <span v-else> {{ scope.row[dynamicProp[index]] && scope.row[dynamicProp[index]].datas }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" min-width="80" key="operate">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="handleDetail(scope.row)"
              >查看
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="统计">
        <el-card style="width: 900px; height: 900px; margin:auto">
          <div v-if="countList.length!=0" v-for="(item,index) in countList" :key="item.title"
               style="height:270px ;width:800px;margin: 20px 0 0 0 ;">
            <b>{{ item.title }}</b>
            <br/> <br/>
            <el-table v-loading="loading" :data="item.detailsLit"
                      :summary-method="(res)=>getSummaries(res,index )" show-summary
            >
              <el-table-column label="选项" align="center" prop="selects"/>
              <el-table-column label="小计" align="center" prop="selectNum"/>
              <el-table-column label="比例" align="center" sortable prop="proportion">
                <template slot-scope="scope">
                  <el-progress :percentage="scope.row.proportion"></el-progress>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>

      </el-tab-pane>
    </el-tabs>

    <el-dialog title="调查问卷" :visible.sync="dialogQuestionire" width="860" append-to-body>
      <el-form ref="form" disabled label-width="90px"
               style="width: 100%; margin: auto">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="班级">
              <el-input v-model="formFix.classAlias"></el-input>
            </el-form-item>
            <el-form-item label="填写状态" prop="ryZdzt">
              <el-select v-model="formFix.ryZdzt" style="width: 100%" placeholder="请选择问卷填写状态">
                <el-option
                  v-for="dict in dict.type.quiz_txzt"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="studentName">
              <el-input :value="formFix.studentName"/>
            </el-form-item>
            <el-form-item label="填写时间">
              <el-date-picker
                v-model="formFix.ryCtime"
                style="width: 100%"
                value-format="yyyy-MM-dd HH:mm"
                type="date"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <h2 style="text-align: center">问卷内容</h2>
        <el-divider></el-divider>
        <el-row v-for="item in formFlex ">
          (
          <dict-tag style="display: inline-block; font-weight: bold" :options="dict.type.quiz_type"
                    :value="item.type"></dict-tag>
          )
          <b>{{ item.title }}</b>
          <br/><br/>
          <el-image v-if="item.type==3" :src="baseUrl+item.datas"></el-image>
          <b v-else>{{ item.datas }}</b>
          <el-divider></el-divider>
        </el-row>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
import {activityTypesEnum, departmentEnum} from "@/enums/questionnaire/content";
import {
  getList,
  getCount,
  getQuestionResultQueryOne
} from "@/api/smartSchool/teachAffairAdministration/questionnaireManagement/ActivityResult/request.js";
import {closeCurrentTab} from "@/utils/utilLibrary/routerBatch/routerBatch.js";

export default {
  name: "QuestionnaireResult",
  dicts: ['quiz_txzt', 'quiz_type'],
  data() {
    this.activityTypes = activityTypesEnum
    this.departments = departmentEnum
    return {
      pubType: "",
      baseUrl: process.env.VUE_APP_BASE_API,
      // 日期范围
      dateRange: [],
      countList: [],
      dialogQuestionire: false,
      //动态列
      dynamicProp: [],
      //动态标题
      dynamicTitle: [],
      statisticData: [],
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      // total: 0,
      // 办公申购表格数据
      activityList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      dcwjId: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        studentName: undefined,
        ryZdzt: undefined,
      },
      // 固定表单参数
      formFix: {},
      // 不固定表单参数
      formFlex: {},
      // 表单校验
      rules: {},
      // 用户导出选项
      exportParam: {
        open: false,
        option: "0",
      }
    };
  },
  created() {
    this.dcwjId = +this.$route?.query?.examId;
    this.pubType = +this.$route?.query?.pubType;

    this.getList();
    this.getCountList();
  },

  activated() {
    this.dcwjId = +this.$route?.query?.examId;
    this.pubType = +this.$route?.query?.pubType;

    this.getList();
    this.getCountList();
  },
  methods: {
    // 路由工具库模块
    closeCurrentTab,
    getList() {
      this.loading = true;
      getList(this.addDateRange(this.queryParams, this.dateRange), this.dcwjId).then(response => {
        this.activityList = response.data
        //获取标题
        let title = Object.values(response.titles)
        this.dynamicTitle = title.filter((item) => {
          if (item != null) {
            return true
          }
        })
        let num = this.dynamicTitle.length
        let prop = Object.keys(response.titles)
        for (let i = 0; i < num; i++) {
          this.dynamicProp.push(prop[i])
        }
        this.loading = false;
      }).catch(error => {
        this.loading = false;
      });
    },
    /** 查询统计数据*/
    getCountList() {
      this.loading = true;
      getCount(this.dcwjId).then(response => {
        this.countList = response.data
        this.loading = false;
      }).catch(error => {
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        activityTitle: null,
        department: null,
        user: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleCreate() {
      this.reset();
      this.open = true;
      this.title = "添加活动结果";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPurchase(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改活动结果";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.loading = true
          if (this.form.id != null) {
            updatePurchase(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.loading = false
              this.open = false;
              this.getList();
            });
          } else {
            addPurchase(this.form).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 delPurchase(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleOpenExport() {
      // this.exportParam.open = true;
      this.download(`/dcwj/senateExport/${this.dcwjId}`, {
        // ...this.queryParams
      }, `问卷结果.xlsx`)
    },
    //查看按钮
    handleDetail(row) {
      this.dialogQuestionire = true
      let {classAlias, ryZdzt, studentName, ryCtime} = row
      this.formFix.classAlias = classAlias
      this.formFix.ryZdzt = ryZdzt
      this.formFix.studentName = studentName
      this.formFix.ryCtime = ryCtime
      getQuestionResultQueryOne(row.id).then((res) => {
        this.formFlex = res.data
      })

    },
    /** 主导出操作 */
    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(`/dcwjAn/export/${allIds}`, {}, `问卷调查活动${new Date().getTime()}.xlsx`);
          break;
        // 根据筛选框内容导出
        case "1":
          this.download(`/dcwjAn/export/${ids}`, this.queryParams, `问卷调查活动${new Date().getTime()}.xlsx`);
          break;
        // 导出全部数据
        case "2":
          this.download('/dcwjAn/export', {}, `问卷调查活动${new Date().getTime()}.xlsx`);
          break;
      }
    },
    getSummaries(param, index) {
      // console.log(index,778)
      const {columns, data} = param;
      const sums = [];
      columns.forEach((column, columnIndex) => {
        if (columnIndex === 0) {
          sums[columnIndex] = '本题有效填写人数';
          return;
        }
        if (columnIndex === 1) {
          sums[columnIndex] = this.countList[index].num;
          return;
        }
      });
      return sums;
    }
  }
}
</script>

<style scoped lang="scss">
div.activity-result {
}
</style>
