<!--  -->
<template>
  <div class="m-container">
    <h2>
      <div class="squrt"></div>服务指标
    </h2>
    <div class="m-core">
      <el-form :inline="true"
               :model="searchForm">
        <el-form-item>
          <el-input v-model.trim="searchForm.search"
                    @keyup.enter.native="search"
                    placeholder="学生姓名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-select placeholder="指导老师"
                     v-model="searchForm.teacherId"
                     clearable
                     filterable>
            <el-option v-for="(item,index) in teacherList"
                       :label="item.realName"
                       :value="item.id"
                       :key="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="organId">
          <el-select class="multiple"
                     v-model.trim="searchForm.organIdList"
                     filterable
                     clearable
                     placeholder="请选择分部">
            <el-option v-for="(item,index) in organList"
                       :key="index"
                       :label="item.name"
                       :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item>
          <el-select placeholder="当前有VIP课" v-model="searchForm.existVipCourse" clearable>
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item>
          <el-select placeholder="实际安排"
                     v-model="searchForm.actualExercisesNumIsAchieve"
                     clearable>
            <el-option label="符合预期"
                       value="1"></el-option>
            <el-option label="不符合预期"
                       value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select placeholder="提交次数"
                     v-model="searchForm.exercisesReplyNumIsAchieve"
                     clearable>
            <el-option label="符合预期"
                       value="1"></el-option>
            <el-option label="不符合预期"
                       value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select placeholder="评价次数"
                     v-model="searchForm.exercisesMessageNumIsAchieve"
                     clearable>
            <el-option label="符合预期"
                       value="1"></el-option>
            <el-option label="不符合预期"
                       value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select placeholder="及时评价"
                     v-model="searchForm.exercisesMessageTimelyNumIsAchieve"
                     clearable>
            <el-option label="符合预期"
                       value="1"></el-option>
            <el-option label="不符合预期"
                       value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select placeholder="是否有VIP课"
                     v-model="searchForm.existVipCourse"
                     clearable>
            <el-option label="是"
                       value="1"></el-option>
            <el-option label="否"
                       value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select placeholder="是否有付费网管课"
                     v-model="searchForm.existPracticeCourse"
                     clearable>
            <el-option label="是"
                       value="1"></el-option>
            <el-option label="否"
                       value="0"></el-option>
          </el-select>
        </el-form-item>
        <br>
        <el-form-item label="周次选择">
          <el-date-picker v-model.trim="searchForm.timer"
                          style="width:400px;"
                          type="daterange"
                          :picker-options="{
        firstDayOfWeek: 1
    }"
                          value-format="yyyy-MM-dd"
                          range-separator="至"
                          start-placeholder="周次开始日期"
                          end-placeholder="周次结束日期"
                          @change="getWeekTime"></el-date-picker>
        </el-form-item>
        <el-form-item label="作业提交时间">
          <el-date-picker v-model.trim="searchForm.workTimer"
                          style="width:400px;"
                          type="daterange"
                          :picker-options="{
        firstDayOfWeek: 1
    }"
                          value-format="yyyy-MM-dd"
                          range-separator="至"
                          start-placeholder="提交开始日期"
                          end-placeholder="提交结束日期"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="danger"
                     @click="search">搜索</el-button>
          <el-button @click="onReSet"
                     type="primary">重置</el-button>
          <el-button @click="onExport"
                     type="primary"
                     v-permission="'export/exercisesSituations'"
                     style=" background: #14928a; border:1px solid #14928a;">导出</el-button>
        </el-form-item>
      </el-form>
      <div class="tableWrap">
        <el-table style="width: 100%"
                  :header-cell-style="{background:'#EDEEF0',color:'#444'}"
                  :data="tableList">
          <el-table-column align="center"
                           prop="studentId"
                           label="学员编号"></el-table-column>
          <el-table-column align="center"
                           prop="studentName"
                           label="学生姓名"></el-table-column>
          <el-table-column align="center"
                           prop="organName"
                           label="所属分部"></el-table-column>
          <el-table-column align="center"
                           prop="groupNames"
                           label="乐团名称"></el-table-column>
          <el-table-column align="center"
                           prop="teacherName"
                           label="指导老师"></el-table-column>
          <el-table-column align="center"
                           prop="educationalTeacherName"
                           label="乐团主管"></el-table-column>
          <el-table-column align="center"
                           prop="courseIds"
                           width="100"
                           label="服务课程">
                           <template slot-scope="scope">
                              <copy-text>{{scope.row.courseIds || '课外训练'}}</copy-text>
                            </template>
          </el-table-column>
          <!-- <el-table-column align="center" label="当前有VIP课" width="100" >
            <template slot-scope="scope">
              <div>{{scope.row.existVipCourse?'是':'否'}}</div>
            </template>
          </el-table-column> -->
          <el-table-column align="center"
                           label="预期安排">

            <template slot-scope="scope">
              <div>{{scope.row.expectExercisesNum+'次'}}</div>
            </template>
          </el-table-column>
          <el-table-column align="center"
                           width="120"
                           prop>
            <template slot="header"
                      slot-scope="scope">

              <p style="position: relative; "> 实际安排 <el-tooltip placement="top"
                            popper-class="mTooltip">
                  <div slot="content">
                    以周为单位，实际发生一次课外训练或网管课作业布置，记一次，一周只统计一次
                  </div>
                  <!-- <img :src="imageIcon"
                       class="micon el-tooltip"
                       style="width:8px height:8px"
                       alt /> -->
                  <i class="el-icon-question"
                     style="font-size: 18px; color: #F56C6C"></i>
                </el-tooltip>
              </p>

            </template>
            <template slot-scope="scope">
              <div>{{scope.row.actualExercisesNum+'次'}}</div>
            </template>
          </el-table-column>
          <el-table-column align="center"
                           prop
                           label="提交次数">
            <template slot-scope="scope">
              <div>{{scope.row.exercisesReplyNum+'次'}}</div>
            </template>
          </el-table-column>
          <el-table-column align="center"
                           prop
                           label="评价次数">
            <template slot-scope="scope">
              <div>{{scope.row.exercisesMessageNum+'次'}}</div>
            </template>
          </el-table-column>
          <el-table-column align="center"
                           prop
                           label="及时评价次数">
            <template slot-scope="scope">
              <div>{{scope.row.exercisesMessageTimelyNum+'次'}}</div>
            </template>
          </el-table-column>
          <el-table-column align="center"
                           label="VIP课">
            <template slot-scope="scope">
              <div>{{scope.row.existVipCourse + '节'}}</div>
            </template>
          </el-table-column>
          <el-table-column align="center"
                           label="付费网管课">
            <template slot-scope="scope">
              <div>{{scope.row.existPracticeCourse+ '节'}}</div>
            </template>
          </el-table-column>
          <el-table-column align="center"
                           label="作业提交时间">
            <template slot-scope="scope">
              <div>{{scope.row.lastSubmitTime}}</div>
            </template>
          </el-table-column>
          <el-table-column align="center"
                           width="120"
                           label="服务周期">
            <template slot-scope="scope">
              <div>{{dayjs(scope.row.monday).format('YYYY-MM-DD')}}</div>
              <div>{{dayjs(scope.row.sunday).format('YYYY-MM-DD')}}</div>
            </template>
          </el-table-column>
          <el-table-column align="center"
                           label="操作">
            <!--  -->
            <template slot-scope="scope">
              <div v-if="scope.row.actualExercisesNum >0">
                <el-button type="text"
                           @click="lookDetail(scope.row)">查看</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <pagination :total="rules.total"
                    :page.sync="rules.page"
                    :limit.sync="rules.limit"
                    :page-sizes="rules.page_size"
                    @pagination="getList" />
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { getToken } from "@/utils/auth";
import pagination from "@/components/Pagination/index";
import load from "@/utils/loading";
import dayjs from 'dayjs'
import { getEmployeeOrgan, getTeacher } from "@/api/buildTeam";
import { findStudentExtracurricularExercisesSituations } from "@/api/afterSchool";
// findStudentExtracurricularExercisesSituations
let nowTime = new Date();
nowTime =
  nowTime.getFullYear() +
  "-" +
  (nowTime.getMonth() + 1) +
  "-" +
  nowTime.getDate();
export default {
  components: { pagination },
  data () {
    return {
      tableList: [],
      searchForm: {
        timer: [],
        search: null,
        organIdList: null,
        actualExercisesNumIsAchieve: null, // 训练次数
        exercisesMessageNumIsAchieve: null, //评价
        exercisesMessageTimelyNumIsAchieve: null, //及时评价
        exercisesReplyNumIsAchieve: null, // 提交次数
        teacherId: null,
        existVipCourse: null,
        existPracticeCourse: null,
        workTimer: []
      },
      organList: [],
      teacherList: [],
      rules: {
        // 分页规则
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 40, 50] // 选择限制显示条数
      },
      // imageIcon: require("@/assets/images/base/warning.png"),
    };
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created () {
    // 设置默认为当前周
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {
    this.searchForm.timer = [];
    this.searchForm.timer.push(this.getNowDateAndMonday(nowTime));
    this.searchForm.timer.push(this.getNowDateAndSunday(nowTime));
    getTeacher().then(res => {
      if (res.code == 200) {
        this.teacherList = res.data;
      }
    });

    getEmployeeOrgan().then(res => {
      if (res.code == 200) {
        this.organList = res.data;
      }
    });
    // 获取分部  老师
    this.init();
  },
  activated () {
    this.init();
  },
  methods: {
    dayjs,
    init () {
      if (this.$route.query.teacherId) {
        this.searchForm.teacherId = this.$route.query.teacherId * 1;
      }
      if (this.$route.query.search) {
        this.$route.query.search instanceof Object ? this.topForm = this.$route.query.search : this.topForm = JSON.parse(this.$route.query.search);
      }
      if (this.$route.query.rules) {
        this.$route.query.rules instanceof Object ? this.rules = this.$route.query.rules : this.rules = JSON.parse(this.$route.query.rules);
      }
      this.getList();
    },
    getDate () {
      let obj = {
        search: this.searchForm.search || null,
        actualExercisesNumIsAchieve:
          this.searchForm.actualExercisesNumIsAchieve || null, // 训练次数
        exercisesMessageNumIsAchieve:
          this.searchForm.exercisesMessageNumIsAchieve || null, //评价
        exercisesMessageTimelyNumIsAchieve:
          this.searchForm.exercisesMessageTimelyNumIsAchieve || null, //及时评价
        exercisesReplyNumIsAchieve:
          this.searchForm.exercisesReplyNumIsAchieve || null, // 提交次数
        organIdList: this.searchForm.organIdList || null,
        teacherId: this.searchForm.teacherId,
        page: this.rules.page,
        rows: this.rules.limit,
        existVipCourse: this.searchForm.existVipCourse || null,
        existPracticeCourse: this.searchForm.existPracticeCourse || null,
      };
      if (this.searchForm.timer && this.searchForm.timer.length > 0) {
        obj.monday = this.searchForm.timer[0];
        obj.sunday = this.searchForm.timer[1];
      } else {
        this.$message.error("请选择时间段");
        return false;
      }
      if (this.searchForm.workTimer && this.searchForm.workTimer.length > 0) {
        obj.submitStartDate = this.searchForm.workTimer[0];
        obj.submitEndDate = this.searchForm.workTimer[1];
      }

      return obj;
    },
    getList () {
      let obj = this.getDate();
      if (!obj) return;
      findStudentExtracurricularExercisesSituations(obj).then(res => {
        if (res.code == 200) {
          this.tableList = res.data.rows;
          this.rules.total = res.data.total;
        }
      });
    },

    onReSet () {
      this.searchForm = {
        timer: [],
        search: null,
        actualExercisesNumIsAchieve: null, // 训练次数
        exercisesMessageNumIsAchieve: null, //评价
        exercisesMessageTimelyNumIsAchieve: null, //及时评价
        exercisesReplyNumIsAchieve: null, // 提交次数
        teacherId: null,
        existVipCourse: null
      };
      this.search();
    },

    onExport () {
      let url = "/api-web/export/exercisesSituations";
      let obj = this.getDate();
      const options = {
        method: "get",
        headers: {
          Authorization: getToken()
        },
        url,
        params: obj,
        responseType: "blob"
      };

      this.$confirm("您确定导出列表?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          load.startLoading();
          axios(options)
            .then(res => {
              let blob = new Blob([res.data], {
                // type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8',
                type: "application/vnd.ms-excel;charset=utf-8"
                // word文档为application/msword,pdf文档为application/pdf,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8
              });
              let text = new Response(blob).text();
              text.then(res => {
                // 判断是否报错
                if (res.indexOf("code") != -1) {
                  let json = JSON.parse(res);
                  this.$message.error(json.msg);
                } else {
                  let objectUrl = URL.createObjectURL(blob);
                  let link = document.createElement("a");
                  let nowTime = new Date();
                  let ymd =
                    nowTime.getFullYear() +
                    "" +
                    (nowTime.getMonth() + 1) +
                    "" +
                    nowTime.getDate() +
                    "" +
                    nowTime.getHours() +
                    "" +
                    nowTime.getMinutes();
                  let fname = ymd + "服务指标";
                  link.href = objectUrl;
                  link.setAttribute("download", fname);
                  document.body.appendChild(link);
                  link.click();
                }
              });

              load.endLoading();
            })
            .catch(error => {
              this.$message.error("导出数据失败，请联系管理员");
              load.endLoading();
            });
        })
        .catch(() => { });
    },
    search () {
      this.rules.page = 1;
      this.getList();
    },
    getNowDateAndMonday (time) {
      let timestamp = new Date(time.replace(/-/g, "/")).getTime();
      let serverDate = new Date(time);
      if (serverDate.getDay() == 0) {
        timestamp -= 7 * 24 * 60 * 60 * 1000;
      }
      let mondayTime =
        timestamp - (serverDate.getDay() - 1) * 24 * 60 * 60 * 1000;

      let mondayData = new Date(mondayTime);
      //年
      let mondayY = mondayData.getFullYear();
      //月
      let mondayM =
        mondayData.getMonth() + 1 < 10
          ? "0" + (mondayData.getMonth() + 1)
          : mondayData.getMonth() + 1;
      //日
      let mondayD =
        mondayData.getDate() < 10
          ? "0" + mondayData.getDate()
          : mondayData.getDate();

      let str = mondayY + "-" + mondayM + "-" + mondayD;
      return str;
    },
    getNowDateAndSunday (time) {
      let timestamp = new Date(time.replace(/-/g, "/")).getTime();
      let serverDate = new Date(time);

      let num = 7 - serverDate.getDay();
      if (num == 7) {
        num = 0;
      }
      let sundayTiem = timestamp + num * 24 * 60 * 60 * 1000;
      let SundayData = new Date(sundayTiem);
      //年
      let tomorrowY = SundayData.getFullYear(); //月
      let tomorrowM =
        SundayData.getMonth() + 1 < 10
          ? "0" + (SundayData.getMonth() + 1)
          : SundayData.getMonth() + 1;
      //日
      let tomorrowD =
        SundayData.getDate() < 10
          ? "0" + SundayData.getDate()
          : SundayData.getDate();
      let str = tomorrowY + "-" + tomorrowM + "-" + tomorrowD;
      return str;
    },
    getWeekTime (val) {
      if (val && val.length > 0) {
        let start = this.getNowDateAndMonday(val[0]);
        let end = this.getNowDateAndSunday(val[1]);
        this.searchForm.timer.splice(0, 1, start);
        this.searchForm.timer.splice(1, 1, end);
      }
    },
    lookDetail (row) {
      // this.afterSchoolVisible = true;

      let rules = JSON.stringify(this.rules);
      let searchForm = JSON.stringify(this.searchForm);
      this.$router.push({
        path: "/operateManager/serverIndexDetail",
        query: {
          studentId: row.studentId,
          studentName: row.studentName,
          rules,
          searchForm,
          title: row.studentName,
          extracurricularExercisesId: "yes",
          startTime: this.searchForm.timer[0],
          endTime: this.searchForm.timer[1]
        }
      });
    }
  }
};
</script>
<style lang='scss' scoped>
.micon {
  position: absolute;
  top: 3px;
  right: 2px;
}
</style>
