<!--  -->
<template>
  <div>
    <save-form :inline="true" class="searchForm" save-key="accompanyBuys" @submit="search" @reset="onReSet"
      :model.sync="searchForm">
      <!-- 状态 指导老师 活动方案-->
      <el-form-item>
        <el-input v-model.trim="searchForm.search" clearable placeholder="学员编号/学员名称"></el-input>
      </el-form-item>
      <el-form-item>
        <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>
      <!-- statusList -->
      <el-form-item prop="buy">
        <el-select class="multiple" v-model.trim="searchForm.buy" filterable clearable placeholder="购买网管课">
          <el-option label="是" value="true"></el-option>
          <el-option label="否" value="false"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button native-type="submit" type="danger">搜索</el-button>
        <el-button native-type="reset" type="primary">重置</el-button>
      </el-form-item>
      <el-form-item>
        <!-- <div class="newBand" @click="onExport">导出</div> -->
        <el-button @click="onExport" type="primary" v-permission="'export/studentBuyPractice'">导出</el-button>
      </el-form-item>
    </save-form>
    <div class="tableWrap">
      <el-table style="width: 100%" :header-cell-style="{ background: '#EDEEF0', color: '#444' }" :data="tableData">
        <el-table-column align="center" prop="studentId" label="学员编号">
          <template slot-scope="scope">
            <copy-text>{{ scope.row.studentId }}</copy-text>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="studentName" label="学员名称">
          <template slot-scope="scope">
            <copy-text>{{ scope.row.studentName }}</copy-text>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="organName" label="所属分部">
          <template slot-scope="scope">
            <copy-text>{{ scope.row.organName }}</copy-text>
          </template>
        </el-table-column>
        <!-- educationalTeacherId -->
        <el-table-column align="center" prop="phone" label="手机号"></el-table-column>
        <el-table-column align="center" label="是否购买">
          <template slot-scope="scope">
            <div>
              <p>{{ scope.row.buyPractice ? "是" : "否" }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="lastClassDate" label="结束日期">
          <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>
              <p>{{ scope.row.lastClassDate | formatTimer }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="firstBuyTime" label="购买日期">
          <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>
              <p>{{ scope.row.firstBuyTime | formatTimer }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="intervalDay" label="时间差">
          <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>
              <p>{{ scope.row.intervalDay + "天" }}</p>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination sync :total.sync="rules.total" save-key="accompanyBuys" :page.sync="rules.page"
        :limit.sync="rules.limit" :page-sizes="rules.page_size" @pagination="getList" />
    </div>
  </div>
</template>

<script>
import {
  practiceGroupManageStudentBuys,
  getEmployeeOrgan,
} from "@/api/buildTeam";
import pagination from "@/components/Pagination/index";
import axios from "axios";
import { getToken, getTenantId } from "@/utils/auth";
import load from "@/utils/loading";
import qs from "qs";
export default {
  components: { pagination },
  data() {
    return {
      searchForm: {
        search: null,
        buy: null,
        organIdList: null,
      },
      tableData: [],
      organList: [],
      rules: {
        // 分页规则
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 40, 50], // 选择限制显示条数
      },
    };
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() { },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.init();
  },
  activated() {
    this.init();
  },
  computed: {
    saveKey() {
      return this.$route.path + "/2";
    },
  },
  methods: {
    init() {
      // 获取分部
      this.$store.dispatch("setBranchs");
      // getEmployeeOrgan().then(res => {
      //   if (res.code == 200) {
      //     this.organList = res.data;
      //   }
      // });
      this.getList();
    },
    getList() {
      let obj = {
        page: this.rules.page,
        rows: this.rules.limit,
      };
      this.searchForm.search ? (obj.search = this.searchForm.search) : null;
      this.searchForm.buy ? (obj.buyPractice = this.searchForm.buy) : null;
      this.searchForm.organIdList
        ? (obj.organId = this.searchForm.organIdList)
        : null;
      practiceGroupManageStudentBuys(obj).then((res) => {
        if (res.code == 200) {
          this.tableData = res.data.rows;
          this.rules.total = res.data.total;
        }
      });
    },
    search() {
      this.rules.page = 1;
      this.getList();
    },
    onReSet() {
      this.searchForm = {
        search: null,
        buy: null,
        organIdList: null,
      };
      this.search();
    },
    // 导出
    onExport() {
      let searchForm = this.searchForm;
      let data = {
        buyPractice: searchForm.buy || null,
        organId: searchForm.organIdList || null,
        search: searchForm.search || null,
      };
      let url = "/api-web/export/studentBuyPractice";
      const options = {
        method: "POST",
        headers: {
          Authorization: getToken(),
          tenantId: getTenantId()
        },
        params: data,
        url,
        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);
                  if (json.code == 403) {
                    this.$message.error(`登录过期，请重新登录！`)
                    setTimeout(() => {
                      this.$store.dispatch('user/resetToken').then(() => {
                        location.reload()
                      })
                    }, 1000);
                    return
                  }
                  this.$message.error(json.msg);
                } else {
                  let objectUrl = URL.createObjectURL(blob);
                  let link = document.createElement("a");
                  let fname = "网管课购买" + new Date().getTime() + '.xls'; //下载文件的名字
                  link.href = objectUrl;
                  link.setAttribute("download", fname);
                  document.body.appendChild(link);
                  link.click();
                }
              });
              load.endLoading();
            })
            .catch((error) => {
              this.$message.error("导出数据失败，请联系管理员");
              load.endLoading();
            });
        })
        .catch(() => { });
    },
  },
};
</script>
<style lang='scss' scoped></style>
