<template>
  <div class="context">
    <div class="panel">
      <h5>{{ pageTitle }}</h5>
    </div>
    <div class="panel-body">
      <div class="panel_control">
        <el-row :gutter="20">
          <el-col :span="9">
            <em> <span style="color: red">*</span>课程表模板名称:</em>
            <el-input v-model="panel.name" placeholder="请输入课程表模板名称"></el-input>
          </el-col>
          <!--默认不通用-->
          <!--<el-button class="seeTemp" @click.native="seeWeekTemp">预览模板</el-button>-->
          <el-button type="default" class="seeTemp" @click="$router.push('/lessonTableTemplate')">返回课程表模板</el-button>
        </el-row>
      </div>
    </div>
    <br>
    <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
      <el-tab-pane label="星期一" name="1"></el-tab-pane>
      <el-tab-pane label="星期二" name="2"></el-tab-pane>
      <el-tab-pane label="星期三" name="3"></el-tab-pane>
      <el-tab-pane label="星期四" name="4"></el-tab-pane>
      <el-tab-pane label="星期五" name="5"></el-tab-pane>
      <el-tab-pane label="星期六" name="6"></el-tab-pane>
      <el-tab-pane label="星期天" name="7"></el-tab-pane>
    </el-tabs>

    <div class="table">
      <el-table
          v-for="tab in tabs"
          :data="tab.tableData"
          v-if="tab.days == activeName"
          border
          is-horizontal-resize
          :default-sort="{prop: 'date', order: 'descending'}"
          element-loading-background="rgba(0, 0, 0, 0.8)"
          class=""
          @selection-change="handleSelectionChange"
      >
        <el-table-column
            prop="timeScope"
            label="时间"
            width="260px"
            align="center"
        >
          <template slot-scope="scope">
            <el-time-picker
                is-range
                v-model="scope.row.timeLong"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                placeholder="选择时间范围"
            >
            </el-time-picker>
          </template>
        </el-table-column>
        <el-table-column
            prop="class_id"
            label="课程"
            align="center"
        >
          <template slot-scope="scope">
            <el-select v-model="scope.row.class_id" @change="getLessonTopMember(scope.row)">
              <el-option
                  v-for="item in panel.options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
            prop="top_limit"
            label="预约名额"
            align="center"
        >
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.top_limit" :min="1" :max="9999" label=""></el-input-number>
          </template>
        </el-table-column>
        <el-table-column
            prop="consume_hour"
            label="消耗课时"
            align="center"
        >
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.consume_hour" :min="0" :max="9999"
                             label=""></el-input-number>
          </template>
        </el-table-column>
        <el-table-column
            prop="Status"
            label="操作"
            width="100px"
            align="center"
        >
          <template slot-scope="scope">
            <el-button type="text" class="red" @click="delRow(scope)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="rowBottom">
        <el-button type="default" @click="$router.push('/lessonTableTemplate')">返回课程表模板</el-button>
        <!--ID为0是新建,不为0是修改-->
        <el-button type="primary" class="pull-right" @click="confirmLessonTemplateAdd"
                   v-if="this.$route.query.id == 0" :disabled="serachBtnStatus">提交
        </el-button>
        <el-button type="primary" class="pull-right" @click="confirmLessonTableEdit"
                   v-if="this.$route.query.id != 0" :disabled="serachBtnStatus">提交
        </el-button>
        <el-button type="primary" class="pull-right" @click="addRow">新增课程</el-button>
      </div>
      <div>
        <br>
        <em class="red wrning">
          *所有操作提交后生效
        </em>
      </div>
    </div>
    <br>
    <el-dialog title="预览" :visible.sync="previewShow" width="1200px">
      <preview :preview-date="previewDate" :big-title="BigTitle" :small-title="smallTitle"></preview>
      <div class="dialogFooter">
        <el-button @click="previewShow = false" size="small">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Global from '../../Global.js'
import preview from '@/components/preview.vue'

import {
  StandardRequest
} from "@/grpc/base_pb";

let qs = require('qs');
export default {
  data() {
    return {
      previewShow: false,
      previewDate: {},
      BigTitle: '',
      smallTitle: '',
      pageTitle: '新增课程表模板',
      dialogVisible: false,
      dialogdata: [],
      dialogValue: [],
      temId: '',
      activeName: '1',
      tableData: [],
      // panel 配置项目
      panel: {
        name: '',
        usercode: '',
        username: '',
        compname: '',
        keyword: '',
        USERCODE: '',
        taskstatus: 99,
        draw: 1,
        start: 0,
        recordsTotal: 0,
        tableData: [],
        allTableData: [],
        limit: '10',
        multipleSort: false,
        loading: false,
        fileList: [],
        multipleSelection: [],
        detectedmac: '',
        options: [],
        time1: globalBt(),
      },
      multipleSelection: [],
      pageination: {
        pageItem: 10,
        pageoptions: pageOptions(),
        total: 100,
        pageIndex: 1,
      },
      testRow: {
        timeLong: [new Date(2016, 9, 10, 8, 40), new Date(2016, 9, 10, 23, 59)],
        begin_str: '08:30',
        end_str: '23:59',
        class_id: '',
        top_limit: 1,
        consume_hour: 0,
      },
      tabs: [
        {
          tableData: [], days: '1'
        },
        {
          tableData: [], days: '2'
        },
        {
          tableData: [], days: '3'
        },
        {
          tableData: [], days: '4'
        },
        {
          tableData: [], days: '5'
        },
        {
          tableData: [], days: '6'
        },
        {
          tableData: [], days: '7'
        },
      ],
      DataAssemblyRs: [],
      serachBtnStatus: false,
    }
  },
  mounted() {
    // 加载课程选项
    this.panelSelect();
    if (this.$route.query.id == 0) {
      this.panel.name = '';
      this.pageTitle = '新增课程表模板'
      this.deepValue();
    } else {
      this.pageTitle = '编辑课程表模板'
      this.getTableQuery();
    }
  },
  methods: {
    // 加载选项
    panelSelect() {
      let that = this;
      const jsonStr = {
        shopId: localStorage.shopId,
        classType: 1,
        start: 1,
        tableMax: 9999,
      };

      let paraRequest = new StandardRequest();
      paraRequest.setShopid(localStorage.shopId);
      paraRequest.setJsonstr(JSON.stringify(jsonStr));
      paraRequest.setSign(getSignStr(jsonStr));
      console.log(paraRequest);
      that.client.classQuery(paraRequest, {"Token": localStorage.token}, (err, StandardReply) => {
        if (err == null) {
          console.log(StandardReply.getJsonrst());
          let res = JSON.parse(StandardReply);
          if (res.code === 0) {
            if(res.rs != null){
              that.panel.options = turnClassResToOption(res.rs)
            }else{
              return false
            }
          } else {
            that.$message.error(res.memo + ',错误代码：' + res.code);
          }
        } else {
          let res = err;
          that.$message.error(res.message + ',错误代码：' + res.code);
          console.log(res);
        }
      });
    },
    // 选择课程后，获取当前课程的建议上课人数和课时消耗
    getLessonTopMember(row) {
      let that = this;
      const jsonStr = {
        shopId: localStorage.shopId,
        classId: row.class_id
      };
      let paraRequest = new StandardRequest();
      paraRequest.setShopid(localStorage.shopId);
      paraRequest.setJsonstr(JSON.stringify(jsonStr));
      paraRequest.setSign(getSignStr(jsonStr));
      console.log(paraRequest);
      that.client.classSimpleQuery(paraRequest, {"Token": localStorage.token}, (err, StandardReply) => {
        if (err == null) {
          console.log(StandardReply.getJsonrst());
          let res = JSON.parse(StandardReply);
          if (res.code === 0) {
            row.top_limit = res.rs[0].top_limit;
            row.consume_hour = res.rs[0].consume_hour;
          } else {
            that.$message.error(res.memo + ',错误代码：' + res.code);
          }
        } else {
          let res = err;
          that.$message.error(res.message + ',错误代码：' + res.code);
          console.log(res);
        }
      });
    },
    confirmLessonTableEdit() {
      let that = this;
      // 按钮倒计时
      that.serachBtnStatus = true;
      let totalTime = 2;
      let clock = window.setInterval(() => {
        totalTime--;
        if (totalTime < 0) {
          totalTime = 2;
          that.serachBtnStatus = false;
        }
      }, 1000);

      if (!this.panel.name) {
        this.$message.error('模板名称不能为空');
        return false
      }
      if (this.panel.name.length < 3) {
        this.$message.error('模板名称不能小于3个字符');
        return false
      }
      if (this.panel.name.length > 20) {
        this.$message.error('模板名称不能大于20个字符');
        return false
      }
      //检查每天的课程是否都提交了
      if (!this.checkData()) {
        return false
      }
      const jsonStr = {
        planId: this.$route.query.id,
        planName: this.panel.name
      };

      let paraRequest = new StandardRequest();
      paraRequest.setShopid(localStorage.shopId);
      paraRequest.setJsonstr(JSON.stringify(jsonStr));
      paraRequest.setSign(getSignStr(jsonStr));
      console.log(paraRequest);
      that.client.sttPlanBasicEdit(paraRequest, {"Token": localStorage.token}, (err, StandardReply) => {
        if (err == null) {
          console.log(StandardReply.getJsonrst());
          let res = JSON.parse(StandardReply);
          if (res.code === 0) {
            let id = that.$route.query.id;
            // 提交课程内容
            that.LessonTemplateEdit(id);
          } else {
            that.$message.error(res.memo + ',错误代码：' + res.code);
          }
        } else {
          let res = err;
          that.$message.error(res.message + ',错误代码：' + res.code);
        }
      });
    },
    // 删除
    delRow(scope) {
      let delIndex = parseInt(scope.$index)
      let curIndex = parseInt(this.activeName) - 1;
      this.tabs[curIndex].tableData.splice(delIndex, 1)
    },
    // 提交新增课程模板
    confirmLessonTemplateAdd() {
      if (!this.panel.name) {
        this.$message.error('模板名称不能为空');
        return false
      }
      if (this.panel.name.length < 3) {
        this.$message.error('模板名称不能小于3个字符');
        return false
      }
      if (this.panel.name.length > 20) {
        this.$message.error('模板名称不能大于20个字符');
        return false
      }
      if (!this.checkData()) {
        return false
      }
      let that = this;

      const jsonStr = {
        shopId: localStorage.shopId,
        planName: this.panel.name
      };

      let paraRequest = new StandardRequest();
      paraRequest.setShopid(localStorage.shopId);
      paraRequest.setJsonstr(JSON.stringify(jsonStr));
      paraRequest.setSign(getSignStr(jsonStr));
      console.log(paraRequest);
      that.client.sttPlanBasicAdd(paraRequest, {"Token": localStorage.token}, (err, StandardReply) => {
        if (err == null) {
          console.log(StandardReply.getJsonrst());
          let res = JSON.parse(StandardReply);
          if (res.code === 0) {
            that.panel.tabId = res.newid;
            // 提交课程内容
            that.LessonTableTemplateEdit(res.newid);
          } else {
            that.$message.error(res.memo + ',错误代码：' + res.code);
          }
        } else {
          let res = err;
          that.$message.error(res.message + ',错误代码：' + res.code);
          console.log(res);
        }
      });
    },
    // 数据组装
    DataAssembly() {
      let thisRow = {};
      for (let i = 0; i < this.tabs.length; i++) {
        for (let j = 0; j < this.tabs[i].tableData.length; j++) {
          thisRow = this.tabs[i].tableData[j];
          thisRow.lesson_index = parseInt(j);
          if (planId) {
            thisRow.plan_id = parseInt(planId);
          } else {
            thisRow.plan_id = parseInt(this.$route.query.id);
          }
          thisRow.week_day = parseInt(i + 1);
          thisRow.begin_str = getHoursAndMin(thisRow.timeLong[0]);
          thisRow.end_str = getHoursAndMin(thisRow.timeLong[1]);
          this.$delete(thisRow, 'Base');
          this.$delete(thisRow, 'SpdId');
          this.DataAssemblyRs.push(thisRow)
        }
      }
    },
    // 修改课程模板
    LessonTemplateEdit(planId) {
      let that = this;
      let planRs = [];
      let thisRow = {};

      for (let i = 0; i < this.tabs.length; i++) {
        for (let j = 0; j < this.tabs[i].tableData.length; j++) {
          thisRow = this.tabs[i].tableData[j];
          console.log(i,'--',j);
          console.log(thisRow);
          thisRow.lesson_index = parseInt(j);
          if (planId) {
            thisRow.plan_id = parseInt(planId);
          } else {
            thisRow.plan_id = parseInt(this.$route.query.id);
          }
          thisRow.week_day = parseInt(i + 1);
          thisRow.begin_str = getHoursAndMin(thisRow.timeLong[0]);
          thisRow.end_str = getHoursAndMin(thisRow.timeLong[1]);
          this.$delete(thisRow, 'Base');
          this.$delete(thisRow, 'SpdId');
          planRs.push(thisRow)
        }
      }

      const jsonStr = {
        planId: planId,
        planRs: planRs,
      };

      let paraRequest = new StandardRequest();
      paraRequest.setShopid(localStorage.shopId);
      paraRequest.setJsonstr(JSON.stringify(jsonStr));
      paraRequest.setSign(getSignStr(jsonStr));
      console.log(paraRequest);
      that.client.sttPlanDetailBatchSave(paraRequest, {"Token": localStorage.token}, (err, StandardReply) => {
        if (err == null) {
          console.log(StandardReply.getJsonrst());
          let res = JSON.parse(StandardReply);
          if (res.code === 0) {
            that.$message({
              showClose: true,
              message: '课程模板已上传成功！',
              type: 'success'
            });
            this.$router.push({
              path: '/lessonTableTemplate'
            });
            // 提交后清掉内存里的课表
            this.clearTableRAM();
            // this.getTableQuery();
          } else {
            // this.$router.push({
            //   path: '/lessonTable'
            // });
            // 提交后清掉内存里的课表
            // this.clearTableRAM();
            that.$message.error(res.memo + ',错误代码：' + res.code);
          }
        } else {
          let res = err;
          that.$message.error(res.message + ',错误代码：' + res.code);
          console.log(res);
        }
      });
    },
    clearTableRAM() {
      this.tabs = [
        {
          tableData: [], days: '1'
        },
        {
          tableData: [], days: '2'
        },
        {
          tableData: [], days: '3'
        },
        {
          tableData: [], days: '4'
        },
        {
          tableData: [], days: '5'
        },
        {
          tableData: [], days: '6'
        },
        {
          tableData: [], days: '7'
        },
      ];

    },
    // 检查数据
    checkData() {
      let res = true;
      for (let i = 0; i < this.tabs.length; i++) {
        for (let j = 0; j < this.tabs[i].tableData.length; j++) {
          if (!this.tabs[i].tableData[j].class_id) {
            let days = numberToWeekdays(i + 1);
            let lesson_index = j + 1;
            this.$message.error(days + '第' + lesson_index + '节课有课程未选择，请选择后再提交');
            res = false;
            break;
          }
        }
      }
      return res
    },
    checkData2() {
      // 目前报错规则：StbId  week_day class_id 不能为空为 0 begin_str end_str 必须是5位数字符串
      let that = this;
      this.DataAssembly();
      let tableDate = this.DataAssemblyRs;
      tableDate.map(function (item) {
        if (!item.class_id) {
          let days = numberToWeekdays(item.week_day);
          let lessonIndex = parseInt(item.lesson_index + 1);
          that.$message.error(days + '第' + lessonIndex + '节课有课程未选择，请选择后再提交');
          return false
        } else {
          return true
        }
      })
    },
    // 新增一行
    addRow() {
      // 读取当前周几
      let index = parseInt(this.activeName) - 1;
      let rows = this.testRow;
      let res = this.deepClone(rows);
      this.tabs[index].tableData.push(res);
    },
    //深拷贝赋初始值
    deepValue() {
      let that = this;
      let value = [
        this.testRow
      ];
      this.tabs.map(function (item) {
        let res = that.deepClone(value);
        item.tableData = res;
      })
    },
    deepClone(obj) {
      let _obj = JSON.stringify(obj),
          objClone = JSON.parse(_obj);
      return objClone
    },
    handleClick() {
    },
    // 增删会员课程
    lessonStudenChange() {
      this.dialogVisible = true
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 页面数据查询
    getTableQuery() {
      let that = this;
      that.loading = true;
      this.panel.name = this.$route.query.name;
      // 清掉上次的记录
      for (let i = 0; i < that.tabs.length; i++) {
        that.tabs[i].tableData = []
      }
      const jsonStr = {
        planId: this.$route.query.id
      };
      let paraRequest = new StandardRequest();
      paraRequest.setShopid(localStorage.shopId);
      paraRequest.setJsonstr(JSON.stringify(jsonStr));
      paraRequest.setSign(getSignStr(jsonStr));
      console.log(paraRequest);
      that.client.sttPlanDetailQuery(paraRequest, {"Token": localStorage.token}, (err, StandardReply) => {
        if (err == null) {
          console.log(StandardReply.getJsonrst());
          let res = JSON.parse(StandardReply);
          if (res.code === 0) {
            let bt = '';
            let et = '';
            that.loading = false;
            if (res.rs) {
              // 遍历分配
              res.rs.map(function (item) {
                for (let i = 0; i < 7; i++) {
                  if (item.week_day == i + 1) {
                    bt = new Date(2016, 9, 10, item.begin_str.substr(0, 2), item.begin_str.substr(3, 2));
                    et = new Date(2016, 9, 10, item.end_str.substr(0, 2), item.end_str.substr(3, 2));
                    item.timeLong = [bt, et];
                    that.tabs[i].tableData.push(item);
                  }
                }
              })
            } else {
              that.allTableData = [];
              that.recordsTotal = 0;
            }
          } else {
            that.$message.error(res.memo + ',错误代码：' + res.code);
          }
        } else {
          let res = err;
          that.$message.error(res.message + ',错误代码：' + res.code);
          console.log(res);
        }
      });
    },
    seeWeekTemp() {
      // 只看保存过的
    },
    // 去重
    unique(arr) {
      const res = new Map();
      return arr.filter((arr) => !res.has(arr.end_str) && res.set(arr.end_str, 1))
    }
  },
  watch: {
    $route(to) {
      if (to.name == 'lessonTableTemplateEdit') {
        this.temId = this.$route.query.id;
        this.panelSelect();
        if (parseInt(this.temId) == 0) {
          this.pageTitle = '新增课程表模板';
          this.deepValue();
          this.panel.name = '';
        } else {
          this.pageTitle = '编辑课程表模板';
          this.getTableQuery();
        }
      }
    },
  },
  components: {
    preview
  }
}
</script>

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

em {
  font-style: normal;
}

.context {
  /* height: 770px; */

  overflow-y: scroll;

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

.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 span {
  width: 169px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  color: #fff;
  background: #3799FF;
  border-radius: 250px;
  font-size: 18px;
  overflow: hidden;
  display: block;
  margin: 0 auto;
  margin-bottom: 30px;
}

.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;
}

/deep/ .panel_control .el-input {
  width: 200px;
  float: left;
}

.panel_control em {
  float: left;
  font-size: 14px;
  color: #545454;
  line-height: 45px;
  margin-right: 10px;
}

.seeTemp {
  /*position: relative;*/
  float: right;
  bottom: 0px;
  z-index: 22;
  margin-left: 10px;
}

.table {
  position: relative;
  /*top: -50px;*/
  top: 0px;
}

.el-range-editor.el-input__inner {
  width: 220px;
  padding: 3px 6px;
}

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

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

.wrning {
  float: right;
  font-size: 12px;
}

.rowBottom button.pull-right {
  float: right;
}
</style>
