<template>
  <div>
    <back-box>
      <template slot="title">
        <span>发卡记录</span>
      </template>
    </back-box>

    <div class="page-content">
      <div class="answer-header">
        <div class="sel-box">
          <!-- <template v-if="role == 'ROLE_XUEXIAO'">
            <el-cascader
              @change="(page = 1), _QueryData(1)"
              size="small"
              class="sel"
              clearable
              placeholder="选择班级"
              v-model="query.classId"
              :options="gradeList"
              :props="props"
              :show-all-levels="false"
            ></el-cascader>
          </template> -->
          <template v-if="role == 'ROLE_JITUAN'">
            <el-select class="sel2" v-model="query.schoolId" placeholder="选择学校" @change="(page = 1), _QueryData(1)">
              <el-option v-for="item in schoolList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </template>
          <el-select class="sel sel3" v-model="query.operationType" placeholder="选择类型"
            @change="(page = 1), _QueryData(1)">
            <el-option label="全部" value=""></el-option>
            <el-option label="发卡" :value="0"></el-option>
            <el-option label="补卡" :value="1"></el-option>
            <el-option label="换班" :value="2"></el-option>
          </el-select>
          <div class="d1">
            <el-date-picker style="width: 40%;" v-model="query.startDay" type="date" @change="handleChangeTimeStart" placeholder="选择日期时间"
              value-format="yyyy-MM-dd">
            </el-date-picker>
            ~
            <el-date-picker style="width: 40%;" v-model="query.endDay" type="date" placeholder="选择日期时间" @change="handleChangeTimeEnd"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </div>
          <template v-if="role == 'ROLE_XUEXIAO'">
            <el-input placeholder="请输入学生姓名" v-model="query.studentName" class="input-with-select sel"
              @keyup.enter.native="(page = 1), _QueryData(2)">
              <el-button slot="append" icon="el-icon-search" @click="(page = 1), _QueryData(2)"></el-button>
            </el-input>
            <el-input placeholder="请输入学生学号" v-model="query.studentCode" class="input-with-select sel"
              @keyup.enter.native="(page = 1), _QueryData(3)">
              <el-button slot="append" icon="el-icon-search" @click="(page = 1), _QueryData(3)"></el-button>
            </el-input>
          </template>
          <el-button type="primary" round @click="(page = 1), _QueryData(4)">筛选</el-button>
        </div>
      </div>
      <el-empty :image-size="100" v-if="!tableData.length && !loading" description="暂无数据"></el-empty>
      <div v-else class="table-box" v-loading="loading">
        <el-table :data="tableData" border style="width: 100%">
          <el-table-column align="center" label="答题器编码" prop="clickerSn"></el-table-column>
          <el-table-column align="center" label="年级">
            <template slot-scope="scope">
              <span>{{ scope.row.classList[0]?.gradeName }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="班级">
            <template slot-scope="scope">
              <span v-for="(item, index) in scope.row.classList" :key="item.classCode">{{ (index == 0 ? "" : "、") +
                item.className }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="学生姓名" prop="studentName"></el-table-column>
          <el-table-column align="center" label="学号" prop="studentCode"></el-table-column>
          <el-table-column align="center" label="类型">
            <template slot-scope="scope">
              {{
                scope.row.operationType == 0
                ? "发卡"
                : scope.row.operationType == 1
                  ? "补卡"
                  : "换班"
              }}
            </template></el-table-column>
          <el-table-column align="center" label="操作次数" prop="operations"></el-table-column>
          <el-table-column align="center" label="描述">
            <template slot-scope="scope">
              {{
                scope.row.operationType == 0
                ? "--"
                : scope.row.reason == 0
                  ? "丢失"
                  : scope.row.reason == 1 ? "损坏" : "换班"
              }}
            </template></el-table-column>
          <el-table-column align="center" label="操作时间" prop="modifiedTime" width="160"></el-table-column>
        </el-table>
        <div class="pagination-box">
          <el-pagination small="" layout="total,prev, pager, next" :hide-on-single-page="true" :total="total"
            @current-change="changePage" :current-page="page" :page-size="size">
          </el-pagination>
        </div>
      </div>
      <p class="down" v-if="tableData.length">
        <el-button type="primary" plain round icon="fa fa-cloud-download" @click="downExl">导出报表</el-button>
      </p>
    </div>
  </div>
</template>

<script>
import { downloadFile, formatDate } from "utils";
const defauleQuery = {
  classId: "",
  studentName: "",
  studentCode: "",
  operationType: "",
  startDay: "",
  endDay: "",
};
export default {
  data() {
    return {
      role: "",
      loading: false,
      props: { multiple: false },
      query: {
        classId: "",
        studentName: "",
        studentCode: "",
        operationType: "",
        schoolId: "",
        startDay: "",
        endDay: "",
      },
      schoolList: [],
      gradeList: [],
      tableData: [],
      page: 1,
      size: 20,
      total: 0,
    };
  },
  async created() {
    this.role =
      this.$store.getters.info.showRole ||
      this.$store.getters.info.permissions[0].role;
    this.loading = true;
    if (this.role == "ROLE_XUEXIAO") {
      this._QueryGradeList();
    } else if (this.role == "ROLE_JITUAN") {
      await this._QuerySchool();
    }

    this._QueryData();
  },
  methods: {
    handleChangeTimeStart(val) {
      if (this.query.endDay) {
        if (new Date(val).getTime() > new Date(this.query.endDay).getTime()) {
          this.$message.error("任务结束时间不能任务开始时间前面，请重新设置");
          this.query.startDay = "";
        }
      }
    },
    handleChangeTimeEnd(val) {
      if (this.query.startDay) {
        if (new Date(val).getTime() < new Date(this.query.startDay).getTime()) {
          this.$message.error("任务结束时间不能任务开始时间前面，请重新设置");
          this.query.endDay = "";
        }
      }
    },
    // 查找班级
    async _QueryGradeList() {
      this.loading = true;
      const { data, status, info } = await this.$request.gradeList();
      if (status === 0) {
        if (!!data.list) {
          this.gradeList =
            data.list?.map((item) => {
              let gradeList = {
                value: item.grade,
                label: item.gradeName,
              };
              gradeList.children =
                item.classList?.map((items) => {
                  return {
                    value: items.id,
                    label: items.className,
                  };
                }) || [];
              return gradeList;
            }) || [];
        }
      } else {
        this.$message.error(info);
      }
    },
    changePage(page) {
      this.page = page;
      this._QueryData(4);
    },
    async _QuerySchool() {
      const { data, status, info } = await this.$request.schoolList();
      if (status === 0) {
        this.schoolList =
          data.list?.map((item) => {
            return {
              label: item.schoolName,
              value: item.id,
            };
          }) || [];
        this.schoolList.unshift({
          label: "全部",
          value: "",
        });
        this.query.schoolId = this.schoolList[0].value || "";
      } else {
        this.$message.error(info);
      }
    },
    serQuery(type) {
      let query = {};
      if (this.role == "ROLE_XUEXIAO") {
        delete query.schoolId;
        if (type == 1) {
          this.query.studentCode = "";
          this.query.studentName = "";
          query = { ...this.query };
          query.classId = this.query.classId[1] ? this.query.classId[1] : "";
        } else if (type == 2) {
          this.query = { ...defauleQuery, studentName: this.query.studentName };
          query = { ...this.query };
        } else if (type == 3) {
          this.query = { ...defauleQuery, studentCode: this.query.studentCode };
          query = { ...this.query };
        } else {
          query = { ...this.query };
          query.classId = this.query.classId[1] ? this.query.classId[1] : "";
        }
      } else if (this.role == "ROLE_JITUAN") {
        query.schoolId = this.query.schoolId;
        query.operationType = this.query.operationType;
        query.startDay = this.query.startDay;
        query.endDay = this.query.endDay;
      }
      return query;
    },
    async _QueryData(type) {
      if (this.role == "ROLE_XUEXIAO") {
        if (type == 2) {
          if (!this.query.studentName) {
            this.$message.warning("输入学生姓名～");
            return;
          }
        } else if (type == 3) {
          if (!this.query.studentCode) {
            this.$message.warning("输入学生学号～");
            return;
          }
        }
      }
      let query = this.serQuery(type);
      this.loading = true;
      const { data, status, info } = await this.$request.cardList({
        ...query,
        page: this.page,
        size: 20,
      });
      this.loading = false;
      if (status === 0) {
        this.tableData = data.list || [];
        this.total = data.count;
      } else {
        this.$message.error(info);
      }
    },
    async downExl() {
      let query = { ...this.query };
      if (this.role == "ROLE_XUEXIAO") {
        query.classId = this.query.classId[1] ? this.query.classId[1] : "";
        delete query.schoolId;
      } else if (this.role == "ROLE_JITUAN") {
        delete query.classId;
        delete query.studentName;
        delete query.studentCode;
      }
      //报表导出
      if (this.exportLoading == true) return;
      this.exportLoading = true;
      const data = await this.$request.exportClickersLog({
        ...query,
      });
      this.exportLoading = false;
      if (data && !data.code) {
        let blob = new Blob([data], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        });
        let date = formatDate(new Date().getTime(), "yyyy-MM-dd");
        let name = `发卡记录_${date}.xlsx`;
        downloadFile(name, blob);
      } else {
        this.$message.error(data.info);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.table-box {
  padding: 0 20px;
}

.down {
  padding: 16px 20px;
}

.answer-header {
  .sel-box {
    .sel {
      margin-right: 20px;
      min-width: 120px;
    }

    .sel2 {
      width: 200px;
      margin-right: 20px;
    }

    .sel3 {
      min-width: 80px;
    }

    .d1 {
      margin-right: 20px;
    }
  }
}
</style>