<template>
  <div class="context">
    <div class="panel">
      <h5>教练课时</h5>
      <div class="panel-body">
        <div class="panel_control">
          <el-row :gutter="20">
            <el-col :span="5">
              <em>店面:</em>
              <el-select v-model="panel.shopId">
                <el-option
                    v-for="item in panel.options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                >
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="5">
              <em>课程:</em>
              <el-select v-model="panel.classId">
                <el-option
                    v-for="item in panel.classOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                >
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="7">
              <em>时间:</em>
              <el-date-picker
                  v-model="panel.timeScope"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
              >
              </el-date-picker>
            </el-col>
            <el-col :span="5">
              <em>教练:</em>
              <el-input v-model="panel.teacherName" placeholder="请输入教练"></el-input>

              <!--							<el-select v-model="panel.teacherName">-->
              <!--								<el-option-->
              <!--									v-for="item in panel.TeacherOptions"-->
              <!--									:key="item.Id"-->
              <!--									:label="item.Name"-->
              <!--									:value="item.Name"-->
              <!--								>-->
              <!--								</el-option>-->
              <!--							</el-select>-->
            </el-col>
            <el-col :span="1">
              <el-button
                  size=""
                  type="primary"
                  @click="query"
                  plain
                  :disabled="serachBtnStatus"
              >查询
              </el-button>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>
    <div class="table">
      <el-table
          :data="tableData"
          border
          is-horizontal-resize
          :default-sort="{ prop: 'date', order: 'descending' }"
          element-loading-background="rgba(0, 0, 0, 0.8)"
          class=""
          @selection-change="handleSelectionChange"
          @current-change="clickChange"
          show-summary
          :summary-method="getSummaries"
      >
        >
        <el-table-column label="序号" type="index" width="50" align="center">
          <template scope="scope">
            <span>{{ start + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column
            prop="ShopName"
            label="店面"
            sortable
        ></el-table-column>
        <el-table-column prop="TeacherName" label="教练" sortable>
          <template scope="scope">
            <span v-if="scope.row.TeacherName == ''">未知</span>
            <span v-if="scope.row.TeacherName != ''">{{
                scope.row.TeacherName
              }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="ClassName" label="课程" sortable>
          <template slot-scope="scope">
						<span
                class="lessonSpan"
                :style="{ background: scope.row.ClassColor }"
            >{{ scope.row.ClassName }}</span
            >
          </template>
        </el-table-column>
        <el-table-column
            prop="CurrentDate"
            label="上课日期"
            width="120px"
            sortable
        ></el-table-column>
        <el-table-column
            prop="WeekDay"
            width="60px"
            label="星期"
        ></el-table-column>
        <el-table-column
            prop="BeginStr"
            label="开始"
            sortable
        ></el-table-column>
        <el-table-column prop="EndStr" label="结束" sortable></el-table-column>
        <el-table-column
            prop="ConsumeHour"
            label="课时"
            sortable
        ></el-table-column>
        <el-table-column
            prop="UserNum"
            label="实际上课人"
            sortable
        ></el-table-column>
        <el-table-column
            prop="SumConsumeHour"
            label="消耗课时"
            sortable
        ></el-table-column>
      </el-table>
      <br/>
      <el-pagination
          background
          :total="pageination.total"
          :page-size="pageination.pageItem"
          @current-change="pageChange"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import Global from "../Global.js";
import {
  ShopAdd,
  ShopDetailQuery,
  ShopEdit,
  ShopListQuery,
  ShopStatusEdit,
  TeacherConsumeQuery,
  testTable,
  testSelect,
  ShopManagerListQuery, ClassSimpleQuery
} from "../api/getApiRes";

let qs = require("qs");
export default {
  data() {
    return {
      dialogVisible: false,
      dialogTitle: "新增店面",
      start: 0,
      draw: 1,
      // panel 配置项目
      panel: {
        shopName: "",
        classId: "",
        contacts: "",
        phone: "",
        userCode: "",
        tel: "",
        teacherName: "",
        shopId: "",
        shopList: 0,
        options: [],
        draw: 1,
        start: 0,
        recordsTotal: 0,
        tableData: [],
        allTableData: [],
        limit: "10",
        multipleSort: false,
        loading: false,
        fileList: [],
        TeacherOptions: [],
        multipleSelection: [],
        classOptions: [],
        detectedmac: "",
        time1: globalBt(),
        timeScope: globalBt2(7),
      },
      multipleSelection: [],
      pageination: {
        pageItem: 100,
        pageoptions: pageOptions(),
        total: 100,
        pageIndex: 1,
      },
      form: {
        shopName: "",
        addr: "",
        name: "",
        contacts: "",
        phone: "",
        userCode: "",
        shopId: "",
        btnState: 0,
        maxOrderLim: 0,
        maxCancelOrderLim: 0,
        isBcPunish: "0",
      },
      shops: [],
      tableData: [],
      tableRadio: [],
      serachBtnStatus: false,
    };
  },
  mounted() {
    this.getShopListSelect();
    this.teacherSelect();
    this.panelSelect();
    this.getTableQuery();
  },
  watch: {
    $route(to) {
      if (to.name == "shopManage") {
        this.getTableQuery();
      }
    },
  },
  methods: {
    panelSelect() {
      let that = this;
      let param = {
        token: localStorage.token,
      };
      let postdata = qs.stringify(param);
      ClassSimpleQuery(postdata).then(res => {
        // ClassListQuery(postdata).then(res => {
        let json = res;
        if (json.Code == 0) {
          if (json.Rs == null) return false;
          that.panel.classOptions = turnClassResToOption(json.Rs);
          that.panel.classOptions.unshift({value: '', label: '全部'})
        } else {
          that.$message.error(json.Memo + ' 错误码：' + json.Code);
        }
      })
    },
    teacherSelect() {
      let that = this;
      let param = {
        token: localStorage.token,
        start: 1,
        tableMax: 999,
      };
      let postdata = qs.stringify(param);
      ShopManagerListQuery(postdata).then((res) => {
        let json = res;
        if (json.Code == 0) {
          that.panel.TeacherOptions = json.Rs;
          that.panel.TeacherOptions.unshift({Id: "0", Name: "未知"});
          that.panel.TeacherOptions.unshift({Id: "", Name: "全部"});
        } else {
          that.$message.error(json.Memo + " 错误码：" + json.Code);
        }
      });
    },
    // 获取店面列表
    getShopListSelect() {
      let that = this;
      let param = {
        token: localStorage.token,
      };
      let postdata = qs.stringify(param);
      ShopListQuery(postdata).then((res) => {
        let json = res;
        if (json.Code == 0) {
          if (json.Rs == "") {
            that.$message.error(
                "当前没有可选的店铺，请先在店面管理中添加店铺!"
            );
            return false;
          }
          that.panel.options = turnShopResToOption(json.Rs);
          that.panel.options.unshift({value: "", label: "全部"});
        } else {
          that.$message.error(json.Memo + " 错误码：" + json.Code);
        }
      });
    },
    clickChange(item) {
      this.tableRadio = item;
    },
    // 新增 确认提交
    confirmAdmin() {
      let that = this;
      // checkNum
      if (!that.form.shopName) {
        this.$message.error("错了哦，店面名称不能为空");
        return false;
      }
      if (that.form.shopName.length > 18) {
        this.$message.error("错了哦，姓名字数超过18个字");
        return false;
      }
      if (!that.form.addr) {
        this.$message.error("错了哦，位置不能为空");
        return false;
      }
      if (that.form.addr.length > 38) {
        this.$message.error("错了哦，位置字数超过38个字");
        return false;
      }
      if (!that.form.contacts) {
        this.$message.error("错了哦，负责人不能为空");
        return false;
      }
      if (that.form.contacts.length > 8) {
        this.$message.error("错了哦，负责人字数超过8个字");
        return false;
      }
      if (!that.form.phone) {
        this.$message.error("错了哦，联系电话不能为空");
        return false;
      }
      if (!that.form.maxOrderLim) {
        this.$message.error("错了哦，用户预约限制时间不能为空");
        return false;
      }
      if (that.form.maxOrderLim < 0) {
        this.$message.error("错了哦，用户预约限制时间不能为负数");
        return false;
      }
      if (!that.form.maxCancelOrderLim) {
        this.$message.error("错了哦，用户取消预约限制不能为空");
        return false;
      }
      if (that.form.maxCancelOrderLim < 0) {
        this.$message.error("错了哦，用户取消预约限制不能为负数");
        return false;
      }
      // if (!globalCheckPhone(that.form.phone)) {
      //   this.$message.error('错了哦，联系电话格式不正确');
      //   return false
      // }
      let param = {
        token: localStorage.token,
        shopName: that.form.shopName,
        addr: that.form.addr,
        contacts: that.form.contacts,
        phone: that.form.phone,
        shopid: that.form.shopid,
        maxOrderLim: that.form.maxOrderLim,
        maxCancelOrderLim: that.form.maxCancelOrderLim,
        isBcPunish: that.form.isBcPunish,
      };
      let postdata = qs.stringify(param);
      ShopAdd(postdata).then((res) => {
        let json = res;
        if (json.Code == 0) {
          // 关闭弹窗
          that.dialogVisible = false;
          // 重载列表
          that.getTableQuery();
          that.$message({
            showClose: true,
            message: "店面添加成功！",
            type: "success",
          });
        } else {
          that.$message.error(json.Memo + " 错误码：" + json.Code);
        }
      });
    },
    // 修改
    confirmEdite() {
      let that = this;
      // checkNum
      if (!that.form.shopName) {
        this.$message.error("错了哦，店面名称不能为空");
        return false;
      }
      if (that.form.shopName.length > 18) {
        this.$message.error("错了哦，姓名字数超过18个字");
        return false;
      }
      if (!that.form.addr) {
        this.$message.error("错了哦，位置不能为空");
        return false;
      }
      if (that.form.addr.length > 38) {
        this.$message.error("错了哦，位置字数超过38个字");
        return false;
      }
      if (!that.form.contacts) {
        this.$message.error("错了哦，负责人不能为空");
        return false;
      }
      if (that.form.contacts.length > 8) {
        this.$message.error("错了哦，负责人字数超过8个字");
        return false;
      }
      if (!that.form.phone) {
        this.$message.error("错了哦，联系电话不能为空");
        return false;
      }
      if (!that.form.maxOrderLim) {
        this.$message.error("错了哦，用户预约限制时间不能为空");
        return false;
      }
      if (that.form.maxOrderLim < 0) {
        this.$message.error("错了哦，用户预约限制时间不能为负数");
        return false;
      }
      if (!that.form.maxCancelOrderLim) {
        this.$message.error("错了哦，用户取消预约限制不能为空");
        return false;
      }
      if (that.form.maxCancelOrderLim < 0) {
        this.$message.error("错了哦，用户取消预约限制不能为负数");
        return false;
      }
      // if (!globalCheckPhone(that.form.phone)) {
      //   this.$message.error('错了哦，联系电话格式不正确');
      //   return false
      // }
      let param = {
        token: localStorage.token,
        shopName: that.form.shopName,
        addr: that.form.addr,
        contacts: that.form.contacts,
        phone: that.form.phone,
        shopId: that.form.shopId,
        maxOrderLim: that.form.maxOrderLim,
        maxCancelOrderLim: that.form.maxCancelOrderLim,
        isBcPunish: that.form.isBcPunish,
      };
      let postdata = qs.stringify(param);
      ShopEdit(postdata).then((res) => {
        let json = res;
        if (json.Code == 0) {
          // 关闭弹窗
          that.dialogVisible = false;

          // 重载列表
          that.getTableQuery();
          that.$message({
            showClose: true,
            message: "店面编辑成功！",
            type: "success",
          });
        } else {
          that.$message.error(json.Memo + " 错误码：" + json.Code);
        }
      });
    },
    // 删除
    delList() {
      let that = this;
      if (this.tableRadio.length == 0) {
        this.$message.error("请先选中一条记录");
        return false;
      }
      let ShopID = this.tableRadio.ShopID;

      let param = {
        token: localStorage.token,
        shopId: ShopID,
        status: 9, //0禁用1启用9删除
      };
      let postdata = qs.stringify(param);

      this.$confirm("此操作将永久删除该店面, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
          .then(() => {
            ShopStatusEdit(postdata).then((res) => {
              let json = res;
              if (json.Code == 0) {
                that.$message({
                  showClose: true,
                  message: "选中的店面已删除！",
                  type: "success",
                });
                // 重载列表
                that.getTableQuery();
              } else {
                that.$message.error(json.Memo + " 错误码：" + json.Code);
              }
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
    },
    clearForm() {
      // clear
      this.form.shopName = "";
      this.form.addr = "";
      this.form.name = "";
      this.form.userCode = "";
      this.form.shopId = "";
      this.form.phone = "";
      this.form.contacts = "";
    },
    // 新增店面
    addAdmin() {
      this.clearForm();
      this.dialogVisible = true;
      this.dialogTitle = "新增店面";
      this.form.btnState = 0; //新增
    },
    // 编辑店面
    editList() {
      let that = this;
      // checkNum
      this.clearForm();
      this.form.btnState = 1; //编辑
      if (this.tableRadio.length == 0) {
        this.$message.error("请先选中一条记录");
        return false;
      }
      let row = this.tableRadio;
      this.form.shopId = row.ShopID;
      this.form.shopName = row.ShopName;
      this.form.addr = row.Addr;
      this.form.contacts = row.Contacts;
      this.form.phone = row.Phone;
      this.form.maxOrderLim = row.MaxOrderLim;
      this.form.maxCancelOrderLim = row.MaxCancelOrderLim;
      this.form.isBcPunish = row.IsBcPunish.toString();

      this.dialogVisible = true;
      this.dialogTitle = "编辑店面";
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 查询按钮
    query() {
      // 按钮倒计时
      let that = this;
      that.serachBtnStatus = true;
      let totalTime = 2;
      let clock = window.setInterval(() => {
        totalTime--;
        if (totalTime < 0) {
          totalTime = 2;
          that.serachBtnStatus = false;
        }
      }, 1000);

      this.getTableQuery();
      this.$message.success("查询完毕");
    },
    // 页面数据查询
    getTableQuery() {
      let that = this;
      that.loading = true;
      let teacherName = '';
      if (this.panel.teacherName == '全部') {
        teacherName = '';
      } else {
        teacherName = this.panel.teacherName;
      }
      // 查询检测设备。上级区域id，区域id必传。regionid传0，查询supregionid对应所有子区域的检测设备。 如果supregionid，regionid都传0，默认查询企业ID下所有检测设备
      let param = {
        token: localStorage.token,
        shopId: this.panel.shopId, //
        classId: this.panel.classId, //
        name: teacherName, //
        bt: nonTfmtDatetoLength(that.panel.timeScope[0], 10) + " 00:00:00",
        et: nonTfmtDatetoLength(that.panel.timeScope[1], 10) + " 23:59:59",
        start: 1, //
        tableMax: 9999, //
      };
      let postdata = qs.stringify(param);
      TeacherConsumeQuery(postdata).then((res) => {
        let json = res;
        if (json.Code == 0) {
          that.loading = false;
          if (json.Rs) {
            that.allTableData = json.Rs;
            that.recordsTotal = json.Rs.length;
          } else {
            that.allTableData = [];
            that.recordsTotal = 0;
          }
          // 设置分页数据
          that.setPaginations();
        } else {
          that.$message.error(json.Memo + " 错误码：" + json.Code);
        }
      });
    },
    // 设置分页数据
    setPaginations() {
      // 分页属性
      let that = this;
      that.pageination.total = that.recordsTotal;
      // 默认分页
      that.tableData = that.allTableData.filter((item, index) => {
        return index < that.pageination.pageItem;
      });
    },
    // 每页显示数量
    handleSizeChange() {
      let that = this;
      that.tableData = that.allTableData.filter((item, index) => {
        return index < that.pageination.pageItem;
      });
      that.draw = that.pageination.pageItem;
      that.getTableQuery();
    },
    // 翻页
    pageChange(pageIndex) {
      let that = this;
      // 获取当前页
      let index = that.pageination.pageItem * (pageIndex - 1);
      // 数据总数
      let nums = that.pageination.pageItem * pageIndex;
      // 容器
      let tables = [];
      for (var i = index; i < nums; i++) {
        if (that.allTableData[i]) {
          tables.push(that.allTableData[i]);
        }
        this.tableData = tables;
      }
      that.start = index * that.draw;
      // that.getTableQuery();
    },
    // 自动排序
    sortChange(params) {
      console.log(params);
    },
    // 过滤时间
    filterFmtDate(value, row, column) {
      let that = this;
      return nonTfmtDate(column, 11);
    },
    // 过滤金额
    filterMoney(value, row, column) {
      let that = this;
      return parseFloat(column).toFixed(2);
    },
    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value)) && index != 0 && index != 1 && index != 2 && index != 4 && index != 5) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] += '';
          sums[index] = parseInt(sums[index]);
        } else {
          sums[index] = '';
        }
      });
      return sums;
    }
  },
};
</script>

<style scoped>
@import "../assets/css/panel.css";

.context {
  /* height: 770px; */
  overflow-y: scroll;

  display: block;
  margin: 0 auto;
  background-color: #fff !important;
  padding: 30px;
  padding-bottom: 60px;
}

.panel-body {
  padding: 20px;
  background: #f0f2f5;
}

.change {
  width: 100%;
  overflow: hidden;
  display: block;
  margin: 0 auto;
  padding-top: 10px;
  padding-bottom: 10px;
}

.change button {
  float: left;
}

.change button.pull-right {
  float: right;
}

.dialogTitle {
  width: 100%;
  overflow: hidden;
  display: block;
  margin: 0 auto;
  color: #000000;
  font-size: 18px;
  text-align: center;
}

.dialogTitle em {
  float: none;
  font-style: normal;
  color: #3799ff;
  margin: 0;
}

/deep/ .el-transfer-panel__item .el-checkbox__input {
  left: 40px;
}

.dialogFooter {
  width: 90%;
  overflow: hidden;
  display: block;
  margin: 0 auto;
  margin-top: 10px;
}

.dialogFooter button {
  float: right;
  margin-left: 10px;
}

.panel /deep/ .el-date-editor .el-range-separator {
  line-height: 22px;
}

.el-input {
  width: 70%;
}

.panel .panel_control em {
  line-height: 35px;
}

/*ipad only*/
@media only screen and (max-width: 1366px) {
  .panel /deep/ .el-date-editor--daterange {
    width: 100%;
  }

  .el-input {
    width: 100%;
  }
}
</style>
