<!--  -->
<template>
  <div class="m-container">
    <h2>
      <div class="titleWrap">
        <div class="squrt"></div>
        服务指标
      </div>

      <el-button
        type="text"
        icon="el-icon-question"
        @click="lookServerDetail"
        style="color: red"
        >服务指标规则</el-button
      >
    </h2>
    <div class="m-core">
      <save-form
      ref='searchForm'
        :inline="true"
        :model="searchForm"
        @submit="search"
        @reset="onReSet"
      >
        <el-form-item>
          <remote-search
            :commit="'setTeachers'"
            v-model="searchForm.teacherId"
          />
        </el-form-item>
        <el-form-item>
          <el-input
            v-model.trim="searchForm.search"
            @keyup.enter.native="search"
            clearable
            placeholder="学生姓名"
          ></el-input>
        </el-form-item>

        <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>
          <el-button
             :type="isSearch ? 'primary' : 'info'"
            icon="el-icon-circle-plus-outline"
            @click="showMove = true"
            >更多选项</el-button
          >
          <el-button type="danger" native-type="submit">搜索</el-button>
          <el-button native-type="reset" 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>
      </save-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="学员编号">
            <template slot-scope="scope">
              <div>
                <copy-text>{{ scope.row.studentId }}</copy-text>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="studentName" label="学生姓名">
            <template slot-scope="scope">
              <div>
                <copy-text>{{ scope.row.studentName }}</copy-text>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="organName" label="所属分部">
            <template slot-scope="scope">
              <div>
                <copy-text>{{ scope.row.organName }}</copy-text>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="groupNames" label="乐团名称">
            <template slot-scope="scope">
              <overflow-text
                width="100%"
                :text="scope.row.groupNames"
              ></overflow-text>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="teacherName" label="指导老师">
            <template slot-scope="scope">
              <div>
                <copy-text>{{ scope.row.teacherName }}</copy-text>
              </div>
            </template>
          </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="预期安排">
            <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
          sync
          :total.sync="rules.total"
          :page.sync="rules.page"
          :limit.sync="rules.limit"
          :page-sizes="rules.page_size"
          @pagination="getList"
        />
      </div>
    </div>
    <el-dialog title="服务指标规则说明" :visible.sync="lookServer">
      <div class="serverInfo">
        <p>作业布置&服务指标优先级：<span>声部课>VIP课>合奏课>网管课</span></p>
        <p>
          每
          <span>周一凌晨</span> 系统根据学员的排课情况生成布置作业路径及服务指标
        </p>
        <p>
          <span>多次课程</span>
          只布置一次作业、统计一次服务指标（多乐团、多组VIP网管课除外）
        </p>
        <el-table
          border
          style="margin-top: 30px"
          :data="infoList"
          :header-cell-style="{ background: '#EDEEF0', color: '#444' }"
          :span-method="arraySpanMethod"
        >
          <el-table-column
            align="center"
            prop="row1"
            label="总体课程情况"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="row2"
            label="本周课程情况"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="row3"
            label="作业布置路径"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="row4"
            label="服务指标统计"
          ></el-table-column>
        </el-table>
        <div class="infoWrap">
          <h4>其他情况：</h4>
          <p>
            1.学员在 <span>多个乐团时</span> ，剩余课程中
            <span>本周有声部课</span> 的乐团布置作业，
            <span>都有</span> 则都布置，
            <span>都没有</span> 则根据表格中的逻辑布置
          </p>
          <p>
            2.学员存在 <span>多组VIP课</span> 时，若课程组
            <span>老师相同</span> ，则仅布置一次作业（网管课同理）
          </p>
          <p>
            3.学员存在 <span>多组VIP课</span> 时，若课程组
            <span>老师不同，本周有课</span>
            的VIP课程组布置作业，多个课程组本周都有课则布置多次（网管课同理）
          </p>
          <p>
            4.学员存在 <span>多组VIP课</span> 时，若课程组
            <span>老师不同，本周都没有课</span> ，则所有VIP老师
            <span>都布置</span> 课外训练， <span>都统计</span> 服务指标
          </p>
        </div>
        <div class="infoWrap">
          <h4>课程调整:</h4>
          <p>
            本周 <span>课程调整时</span> ，重新根据该学员的
            <span>本周课程情况更新</span> 作业布置路径及服务指标
            则根据表格中的逻辑布置
          </p>
        </div>
        <div class="infoWrap">
          <h4>服务指标:</h4>
          <p>服务指标按 <span>周为单位</span> 统计</p>
          <p>
            <span>周六周日</span> 的服务指标
            <span>延迟到下周二更新</span>
            实际安排数据（即周日的作业课程，在周二23:59:59时前布置作业都算一次实际安排）
          </p>
        </div>
        <div class="infoWrap">
          <h4>服务指标开启/关闭:</h4>
          <p>学员新增课程时，自动开启服务指标，</p>
          <p>手动关闭服务指标的学员新增课程时，不会自动开启服务指标</p>
          <p>
            学员退团、乐团关闭、VIP课程组结束、网管课课程组结束时，若学员不在任何【进行中】乐团【在读】，且无任何未开始课程（乐团课、VIP课、网管课），则关闭服务指标
          </p>
        </div>
        <div class="infoWrap">
          <h4>服务指标解释：</h4>
          <p><span>若本周学员有多次服务指标则生成多条数据</span></p>
          <p>
            预期安排：本周内服务指标次数（即本周应该给该学员布置的作业次数）
          </p>
          <p>实际安排：本周通过服务指标作业布置路径给该学员布置作业的次数</p>
          <p>提交次数：本周学员按照作业布置路径提交作业的次数</p>
          <p>评价次数：本周老师评价通过作业布置路径提交的作业的次数</p>
          <p>及时评价次数：学员提交作业后24小时内进行评价的次数</p>
          <p>VIP课：本周VIP课程课时数</p>
          <p>付费网管课：本周付费网管课课时数</p>
          <p>作业提交时间：学员提交作业的时间</p>
          <p>服务周期：本服务周期时间段</p>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      title="更多选项"
      :visible.sync="showMove"
      v-if="showMove"
      width="700px"
    >
      <el-form
        :inline="true"
        class="searchForm"
        @submit="search"
        @reset="onReSet"
        ref="searchForm2"
        :model.sync="searchForm"
        label-width="120px"
      >
        <el-form-item prop="organId" label="分部">
          <el-select
            class="multiple"
            v-model.trim="searchForm.organIdList"
            filterable
            clearable
            placeholder="请选择分部"
          >
            <el-option
              v-for="(item, index) in selects.branchs"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="实际安排">
          <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 label="提交次数">
          <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 label="评价次数">
          <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 label="及时评价">
          <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 label="是否有VIP课">
          <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 label="有付费网管课">
          <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>
        <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>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancleMore">取 消</el-button>
        <el-button type="primary" @click="okMore">确 定</el-button>
      </span>
    </el-dialog>
  </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 { infoList } from "./modals/infoList";
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], // 选择限制显示条数
      },
      lookServer: false,
      infoList: infoList,
      showMove: false,
      // imageIcon: require("@/assets/images/base/warning.png"),
    };
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    // 设置默认为当前周
    this.searchForm.timer = [];
    this.searchForm.timer.push(this.getNowDateAndMonday(nowTime));
    this.searchForm.timer.push(this.getNowDateAndSunday(nowTime));
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.$store.dispatch("setBranchs");
    // 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.searchForm.timer = [];
      this.searchForm.timer.push(this.getNowDateAndMonday(nowTime));
      this.searchForm.timer.push(this.getNowDateAndSunday(nowTime));
      this.search();
    },
    cancleMore() {
      // this.$refs.searchForm2.resetFields()
      this.showMove = false;
    },
    okMore() {
      this.getList();
      this.showMove = false;
    },

    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 + "服务指标.xls";
                  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.$refs.searchForm.save(this.searchForm);
      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: "/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],
        },
      });
    },
    lookServerDetail() {
      this.lookServer = true;
    },
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        if (rowIndex % 2 === 0) {
          return {
            rowspan: 2,
            colspan: 1,
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0,
          };
        }
      }
    },
  },
  computed:{
    isSearch(){
      return  this.searchForm.organIdList ||
        this.searchForm.actualExercisesNumIsAchieve ||
        this.searchForm.exercisesReplyNumIsAchieve ||
        this.searchForm.exercisesMessageNumIsAchieve ||
        this.searchForm.exercisesMessageTimelyNumIsAchieve ||
        this.searchForm.existVipCourse||
        this.searchForm.existPracticeCourse||
        this.searchForm.workTimer?.length>0
    }
  }
};
</script>
<style lang='scss' scoped>
.micon {
  position: absolute;
  top: 3px;
  right: 2px;
}
.serverInfo {
  line-height: 30px;
  span {
    color: #333;
    font-weight: bold;
  }
}
.infoWrap {
  margin-top: 30px;
  span {
    color: red;
    font-weight: normal;
  }
}
.titleWrap {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
}
.m-container {
  h2 {
    justify-content: space-between;
  }
}
</style>
