<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" placeholder="请选择问卷状态" @change="handleQuery">
              <el-option v-for="item in [{label:'已填写',value:1},{label:'未填写',value:0}]" :value="item.value"
                         :label="item.label"></el-option>
            </el-select>
            <!--            <el-input v-model="queryParams.examName" placeholder="请搜索状态" clearable-->
            <!--                      @keyup.enter.native="handleQuery">-->
            <!--            </el-input>-->
          </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-input v-model="queryParams.ryCtime" placeholder="请搜索时间" clearable-->
            <!--                      @keyup.enter.native="handleQuery">-->
            <!--            </el-input>-->
          </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"
                       v-hasPermi="['smart-campus:purchase:export']">导出
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="el-icon-close" size="mini" @click="closeCurrentTab"
                       v-hasPermi="['smart-campus:purchase:close']">关闭
            </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 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">
              <!--              <el-image v-if="scope.row[dynamicProp[index]]['type']==3"-->
              <!--                        :src="baseUrl+scope.row[dynamicProp[index]].datas"></el-image>-->
              <!--              <span v-else> {{ scope.row[dynamicProp[index]]['datas'] }}</span>-->
              <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>
        <!--导出选择选项对话框-->
        <!--        <el-dialog title="选择导出方式" :visible.sync="exportParam.open" width="400px" append-to-body>-->
        <!--          <el-form ref="form" :model="exportParam">-->
        <!--            <el-form-item prop="exportOption">-->
        <!--              <el-radio v-model="exportParam.option" label="0">导出当前页(不按筛选条件过滤)</el-radio>-->
        <!--              <br>-->
        <!--              <el-radio v-model="exportParam.option" label="1">根据筛选框内容导出</el-radio>-->
        <!--              <br>-->
        <!--              <el-radio v-model="exportParam.option" label="2">导出全部数据</el-radio>-->
        <!--            </el-form-item>-->
        <!--          </el-form>-->
        <!--          <div slot="footer" class="dialog-footer">-->
        <!--            <el-button type="primary" @click="handleExport">确 定</el-button>-->
        <!--            <el-button @click="exportParam.open = false">取 消</el-button>-->
        <!--          </div>-->
        <!--        </el-dialog>-->
      </el-tab-pane>
      <el-tab-pane label="统计">
        <el-card style="width: 900px; height: 900px; ">
          <div v-for="item in countList" style="height:270px ;width:800px;margin: 20px 0 0 0 ;">
            <span>{{ item.title }}</span>
            <el-table v-loading="loading" :data="item.detailsLit" :summary-method="getSummaries"
                      sum-text="本题有效填写人次" show-summary>
              <el-table-column label="选项" align="center" prop="selects"/>
              <el-table-column label="小计" align="center" prop="selectNum"/>
              <el-table-column label="比例" align="center" 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>


  </div>
</template>

<script>
import {activityTypesEnum, departmentEnum} from "@/enums/questionnaire/content";
import {getQuList, getCount} from "@/api/smartSchool/classAdviser/questionnaireManagement/ActivityResult/request.js";

import {closeCurrentTab} from "@/utils/utilLibrary/routerBatch/routerBatch.js";

export default {
  name: "ActivityResult",
  data() {
    this.activityTypes = activityTypesEnum
    this.departments = departmentEnum
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      // 日期范围
      dateRange: [],
      countList: [],
      //动态列
      dynamicProp: [],
      //动态标题
      dynamicTitle: [],
      statisticData: [],
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      // total: 0,
      // 办公申购表格数据
      activityList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //!!!==页面关键(传参)变量：dcwjId==!!!//
      dcwjId: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        examName: null,
        deptId: null,
        deptName: null,
        userId: null,
        name: null,
        answerTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // delFlag: [
        //   {required: true, message: "$comment不能为空", trigger: "blur"}
        // ]
      },
      // 用户导出选项
      exportParam: {
        open: false,
        option: "0",
      }
    };
  },
  created() {
    this.dcwjId = +this.$route.params.examId;
    this.form.dcwjId = this.dcwjId
    this.getList();
    this.getCountList();
  },
  methods: {
    // 路由工具库模块
    closeCurrentTab,
    /** 查询办公申购列表 */
    getList() {
      this.loading = true;
      getQuList(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
          }
        })
        console.log(this.dynamicTitle, 194)
//获取内容
        let num = this.dynamicTitle.length
        let prop = Object.keys(response.titles)
        for (let i = 0; i < num; i++) {
          this.dynamicProp.push(prop[i])
        }
        console.log(this.dynamicProp, 88888888)
        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;
      });
    },
    // formatPercent(percentage) {
    //   return percentage == 100 ? '满' : ${percentage};
    // },
    // 取消按钮
    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.download(`/dcwj/export/${this.dcwjId}`, {}, `问卷结果${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(`/dcwjAn/export/${allIds}`, {}, `问卷调查活动${Date.now()}.xlsx`);
          break;
        // 根据筛选框内容导出
        case "1":
          this.download(`/dcwjAn/export/${ids}`, this.queryParams, `问卷调查活动${Date.now()}.xlsx`);
          break;
        // 导出全部数据
        case "2":
          this.download('/dcwjAn/export', {}, `问卷调查活动${Date.now()}.xlsx`);
          break;
      }
    },
    getSummaries(param) {
      const {columns, data} = param;
      console.log(columns, 340)
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '本题有效填写人数';
          return;
        }
        if (index === 1) {
          sums[index] = this.countList[index].num;
          return;
        }
        if (index === 2) {
          sums[index] = ' ';
          return;
        }
        // const values = data.map(item => Number(item[column.property]));
        // if (!values.every(value => isNaN(value))) {
        //   sums[index] = values.reduce((prev, curr) => {
        //     const value = Number(curr);
        //     if (!isNaN(value)) {
        //       return prev + curr;
        //     } else {
        //       return prev;
        //     }
        //   }, 0);
        //   sums[index];
        // } else {
        //   sums[index] = ' ';
        // }
      });

      return sums;
    }
  }
}
</script>

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