<template>
  <div class="context">
    <div class="panel">
      <h5>课程表模板</h5>
    </div>
    <div class="change">
      <el-button type="primary" @click="addLessonTemplate" size="mini">新增课程表模板</el-button>
      <el-button type="" @click="copyTemplate" size="mini">复制</el-button>
      <el-button type="danger" @click="deleteTemplate" size="mini">删除</el-button>
    </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">
        >
        <el-table-column label="选择" width="55">
          <template slot-scope="scope">
            <el-radio v-model="tableRadio" :label="scope.row"><i></i></el-radio>
          </template>
        </el-table-column>
        <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="plan_name" label="课程表模板名称">
          <template slot-scope="scope">
                        <span class="link" @click="editLessonTemplate(scope.row)">
                            {{ scope.row.plan_name }}
                        </span>
          </template>
        </el-table-column>
        <el-table-column prop="updated_at" label="最后编辑时间" :formatter="filterFmtDate" sortable>
        </el-table-column>
        <el-table-column prop="is_across" label="是否跨店" sortable>
          <template slot-scope="scope">
            <el-switch v-model="scope.row.is_across" :active-value="0" :inactive-value="1"
                       active-color="#409EFF" inactive-color="#D9D9D9" @change=editIsAcross($event,scope.row)>
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="110" align="center" sortable>
          <template slot-scope="scope">
            <span v-if="scope.row.status == 9">已删除</span>
            <span v-if="scope.row.status == 2">已发布</span>
            <span v-if="scope.row.status == 1">未发布</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="操作" width=220px>
          <template slot-scope="scope">
            <el-button type="text" @click="editLessonTemplate(scope.row)">编辑</el-button>
            <el-button type="text" @click="viewWeekTemplate(scope.row)">预览本周</el-button>
            <el-button type="success" size="mini" @click="openLessonTable(scope.row)">发布</el-button>
          </template>
        </el-table-column>

      </el-table>
      <br>
      <el-pagination background :total="pageination.total" :page-size="pageination.pageItem"
                     @current-change="pageChange"></el-pagination>
    </div>

    <el-dialog title="课程表模板复制" :visible.sync="dialogCopyVisible" width="640px">
      <el-form ref="form" :model="copyForm" label-width="160px">
        <el-form-item label="新模板名称">
          <el-input v-model="copyForm.name" placeholder="请输入新模板名称"></el-input>

        </el-form-item>
      </el-form>
      <div class="dialogFooter">
        <el-button type="primary" size="small" @click="copyTemplateConfirm">确定</el-button>
        <el-button @click="dialogCopyVisible = false" size="small">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="发布课程表" :visible.sync="dialogVisible" width="640px">
      <div class="dialogTitle">
        <span>{{ form.name }}</span>
      </div>
      <div>
        <span class="demonstration">选择发布日期(按周选取)</span>
        <br>
        <br>
        <el-date-picker v-model="form.week" type="week" :picker-options="{'firstDayOfWeek': 1}"
                        format="yyyy 第 WW 周" placeholder="选择周">
        </el-date-picker>
      </div>
      <div class="dialogFooter">
        <el-button type="primary" size="small" @click="public">确定</el-button>
        <el-button @click="dialogVisible = false" size="small">取消</el-button>
      </div>
    </el-dialog>
    <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: '',
      dialogVisible: false,
      dialogCopyVisible: false,
      previewVisible: false,//todo
      dialogdata: [],
      dialogValue: [],
      start: 0,
      draw: 1,
      // panel 配置项目
      multipleSelection: [],
      pageination: {
        pageItem: 10,
        pageoptions: pageOptions(),
        total: 100,
        pageIndex: 1,
      },
      form: {
        Id: '',
        name: '',
        week: '',
        wechat: 1,
        appoint: 1,
      },
      copyForm: {
        Id: '',
        name: '',
      },
      tableData: [],
      tableRadio: [],
    }
  },
  mounted() {
    this.getTableQuery();
  },
  methods: {
    clickChange(item) {
      this.tableRadio = item
    },
    viewWeekTemplate(row) {
      let that = this;

      const jsonStr = {
        plan_id: row.plan_id
      };

      let paraRequest = new StandardRequest();
      paraRequest.setShopid(localStorage.shopId);
      paraRequest.setJsonstr(JSON.stringify(jsonStr));
      paraRequest.setSign(getSignStr(jsonStr));
      console.log(paraRequest);
      that.client.sttPlanPreview(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){
              that.smallTitle = ' ';
              that.BigTitle = row.plan_name;
              that.previewDate = res.rs;
              if(that.previewDate.sttplanpreviewclasslist){
                // 前台排序
                that.previewShow = true;
                that.previewDate.sttplanpreviewclasslist.sort((a, b) => a.class_index - b.class_index);//升序
              }else{
                that.$message.error('当前课程表为空');
              }
            }
          } else {
            that.$message.error(res.memo + ',错误代码：' + res.code);
          }
        } else {
          let res = err;
          that.$message.error(res.message + ',错误代码：' + res.code);
          console.log(res);
        }
      });
    },
    // 跨店修改
    editIsAcross(e,row) {
      let that = this;
      console.log(e);
      const jsonStr = {
        shopId: localStorage.shopId,
        planId: row.plan_id,
        state: e
      };
      let paraRequest = new StandardRequest();
      paraRequest.setShopid(localStorage.shopId);
      paraRequest.setJsonstr(JSON.stringify(jsonStr));
      paraRequest.setSign(getSignStr(jsonStr));
      console.log(paraRequest);
      that.client.sttPlanBasicShopEdit(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'
            });
            // 重载列表
            // that.getTableQuery();
          } else {
            that.$message.error(res.memo + ',错误代码：' + res.code);
          }
        } else {
          let res = err;
          that.$message.error(res.message + ',错误代码：' + res.code);
          console.log(res);
        }
      });
    },
    // 删除
    deleteTemplate() {
      let that = this;
      if (this.tableRadio.length == 0) {
        this.$message.error("请先选中一条记录");
        return false
      }
      let row = that.tableRadio;

      this.$confirm('此操作将永久删除该课程表模板, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const jsonStr = {
          planId: row.plan_id,
          status: 9,//9删除
        };
        let paraRequest = new StandardRequest();
        paraRequest.setShopid(localStorage.shopId);
        paraRequest.setJsonstr(JSON.stringify(jsonStr));
        paraRequest.setSign(getSignStr(jsonStr));
        console.log(paraRequest);
        that.client.sttPlanBasicStatusEdit(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'
              });
              // 重载列表
              that.getTableQuery();
            } else {
              that.$message.error(res.memo + ',错误代码：' + res.code);
            }
          } else {
            let res = err;
            that.$message.error(res.message + ',错误代码：' + res.code);
            console.log(res);
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    copyTemplate() {
      let that = this;
      if (this.tableRadio.length == 0) {
        this.$message.error("请先选中一条记录");
        return false
      }
      let row = that.tableRadio;
      this.copyForm.name = '';
      this.copyForm.Id = row.plan_id;
      this.dialogCopyVisible = true;
    },
    copyTemplateConfirm() {
      let that = this;
      if (!that.copyForm.name) {
        this.$message.error('错了哦，新模版名不能为空');
        return false
      }
      if (that.copyForm.name.length > 20) {
        this.$message.error('错了哦，新模版名字的字数超过20个字');
        return false
      }
      const jsonStr = {
        shopId: localStorage.shopId,
        planId: that.copyForm.Id,
        planName: that.copyForm.name,
      };
      let paraRequest = new StandardRequest();
      paraRequest.setShopid(localStorage.shopId);
      paraRequest.setJsonstr(JSON.stringify(jsonStr));
      paraRequest.setSign(getSignStr(jsonStr));
      console.log(paraRequest);
      that.client.sttPlanCopy(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'
            });
            // 关闭弹窗
            that.dialogCopyVisible = false;
            // 重载列表
            that.getTableQuery();
          } else {
            that.$message.error(res.memo + ',错误代码：' + res.code);
          }
        } else {
          let res = err;
          that.$message.error(res.message + ',错误代码：' + res.code);
          console.log(res);
        }
      });
    },
    // 发布课程表
    openLessonTable(row) {
      this.dialogVisible = true;
      this.form.name = row.plan_name;
      this.form.Id = row.plan_id;
      this.form.week = '';
    },
    // 发布
    public() {
      let that = this;
      if (!this.form.week) {
        this.$message({
          showClose: true,
          message: '错了哦，发布周期不能空',
          type: 'error'
        });
        return false
      }
      const jsonStr = {
        shopId: localStorage.shopId,
        planId: this.form.Id,
        incomingDate: nonTfmtDatetoLength(this.form.week, 10)//对应日期 字符串 年-月-日 格式
      };

      let paraRequest = new StandardRequest();
      paraRequest.setShopid(localStorage.shopId);
      paraRequest.setJsonstr(JSON.stringify(jsonStr));
      paraRequest.setSign(getSignStr(jsonStr));
      console.log(paraRequest);
      that.client.sttPlanBasicPublish(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: this.form.name + '已发布！',
              type: 'success'
            });
            // 重载列表
            that.getTableQuery();
            this.dialogVisible = false;
          } else {
            that.$message.error(res.memo + ',错误代码：' + res.code);
          }
        } else {
          let res = err;
          that.$message.error(res.message + ',错误代码：' + res.code);
          console.log(res);
        }
      });
    },
    // 取消发布
    unpubilc(row) {
      let that = this;
      let param = {
        token: localStorage.token,
        detectorid: row.Id,
        status: 4,//0禁用1启用9删除
      };
      let postdata = qs.stringify(param);
      testSelect(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);
        }
      });
    },
    // 新增课程表模板
    addLessonTemplate() {
      this.$router.push({
        path: '/lessonTableTemplateEdit', query: {
          id: 0
        }
      });
    },
    // 编辑课程表模板
    editLessonTemplate(row) {
      this.$router.push({
        path: '/lessonTableTemplateEdit', query: {
          id: row.plan_id,
          name: row.plan_name
        }
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 页面数据查询
    getTableQuery() {
      let that = this;
      that.loading = true;

      const jsonStr = {
        shopId: localStorage.shopId,
        status: -99,//1:未发布 2:已发布 传-99本字段查询全部记录
        start: that.start,
        tableMax: that.pageination.pageItem
      };

      let paraRequest = new StandardRequest();
      paraRequest.setShopid(localStorage.shopId);
      paraRequest.setJsonstr(JSON.stringify(jsonStr));
      paraRequest.setSign(getSignStr(jsonStr));
      console.log(paraRequest);
      that.client.sttPlanBasicQuery(paraRequest, {"Token": localStorage.token}, (err, StandardReply) => {
        if (err == null) {
          console.log(StandardReply.getJsonrst());
          let res = JSON.parse(StandardReply);
          if (res.code === 0) {
            that.loading = false;
            if (res.rs) {
              that.allTableData = res.rs;
              that.recordsTotal = res.pagecount * that.pageination.pageItem;
            } else {
              that.allTableData = [];
              that.recordsTotal = 0;
            }

            // 设置分页数据
            that.setPagination();
          } else {
            that.$message.error(res.memo + ',错误代码：' + res.code);
          }
        } else {
          let res = err;
          that.$message.error(res.message + ',错误代码：' + res.code);
          console.log(res);
        }
      });
    },
    // 设置分页数据
    setPagination() {
      // 分页属性
      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();
    },
    // 过滤时间
    filterFmtDate(value, row, column) {
      let that = this;
      return nonTfmtDate(column, 11);
    },
  },
  watch: {
    $route(to) {
      if (to.name == 'lessonTableTemplate') {
        this.getTableQuery()
      }
    },
  },
  components: {
    preview
  }
}
</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;
}

.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: 14px;
  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;
}

.link {
  color: #03B1FF;
  text-decoration: underline;
  cursor: pointer;
}

em {
  font-style: normal;
}
</style>