<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="5">
                        <em>课程表名称:</em>
                        <el-input v-model="panel.name" placeholder="请输入课程表名称" :disabled="panel.inputState"></el-input>
                    </el-col>
                    <el-col :span="5" v-if="!panel.inputState">
                        <em>课程表时间:</em>
                        <el-date-picker
                                v-model="panel.week"
                                type="week"
                                :picker-options="{'firstDayOfWeek': 1}"
                                format="yyyy 第 WW 周"
                                placeholder="选择周">
                        </el-date-picker>
                    </el-col>
                </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>
        <el-button class="seeTemp">预览模板</el-button>
        <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="选择时间范围"
                                :readonly="scope.row.Locking == 1"
                        >
                        </el-time-picker>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="ClassId"
                        label="课程"
                        align="center"
                >
<!--                    locking是1的不可编辑课程和时间-->
                    <template slot-scope="scope">
                        <el-select v-model="scope.row.ClassId" @change="getRowTop(scope.row)" :disabled="scope.row.Locking == 1">
                            <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="OrderToplimit"
                        label="预约名额"
                        align="center"
                >
                    <template slot-scope="scope">
                        <el-input-number v-model="scope.row.OrderToplimit" :min="1" :max="9999"
                                         label=""></el-input-number>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="ConsumeHour"
                        label="消耗课时"
                        align="center"
                >
                    <template slot-scope="scope">
                        <el-input-number v-model="scope.row.ConsumeHour" :min="0" :max="9999"
                                         label=""></el-input-number>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="WxVisible"
                        label="微信可见"
                >
                    <template slot-scope="scope">
                        <el-switch
                                v-model="scope.row.WxVisible"
                                :active-value="1"
                                :inactive-value="0"
                                active-color="#409EFF"
                                inactive-color="#D9D9D9"
                                @change=changeWechat($event,scope.row)
                        >
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="WxOrder"
                        label="微信可预约"
                >
                    <template slot-scope="scope">
                        <el-switch
                                v-model="scope.row.WxOrder"
                                :active-value="1"
                                :inactive-value="0"
                                active-color="#409EFF"
                                inactive-color="#D9D9D9"
                                @change=changeWechatOrder($event,scope.row.ClassSelf)
                        >
                        </el-switch>
                    </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('/lessonManage')">返回课程表</el-button>
                <!--                ID为0是新建,不为0是修改-->
                <el-button type="primary" class="pull-right" @click="confirmLessonTable"
                           v-if="this.$route.query.id == 0">提交
                </el-button>
                <el-button type="primary" class="pull-right" @click="confirmEditLessonTable"
                           v-if="this.$route.query.id != 0">提交
                </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="dialogVisible">
            <div class="dialogTitle">
                <span>基础功能</span>
            </div>
            <div>
                <el-transfer filterable v-model="dialogValue" :data="dialogdata"></el-transfer>
            </div>
            <div class="dialogFooter">
                <el-button type="primary" size="small">确定</el-button>
                <el-button @click="dialogVisible = false" size="small">取消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import Global from '../Global.js'
    import {
        SttPlanBasicAdd,
        SttPlanDetailListQuery,
        SttPlanDetailBatchSave,
        STTBasicAdd,
        SttPlanBasicEdit,
        STTDetailListQuery,
        STTDetailBatchSave,
        STTBasicEdit,
        testTable,
        testTableLong,
        testSelect,
        ClassListQuery,
        STTDetailAllowDelCheck,
        ClassDetailOne
    } from "../api/getApiRes";

    let qs = require('qs');
    export default {
        data() {
            return {
                pageTitle: '新增课程表',
                dialogVisible: false,
                dialogdata: [],
                dialogValue: [],
                temId: '',
                activeName: '1',
                tableData: [],
                // panel 配置项目
                panel: {
                    inputState: true,
                    name: '',
                    usercode: '',
                    username: '',
                    compname: '',
                    keyword: '',
                    USERCODE: '',
                    week: '',
                    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: 100,
                    pageoptions: pageOptions(),
                    total: 100,
                    pageIndex: 1,
                },
                testRow: {
                    timeLong: [new Date(2016, 9, 10, 8, 1), new Date(2016, 9, 10, 9, 2)],
                    BeginStr: '08:30',
                    EndStr: '09:30',
                    ClassId: '',
                    OrderToplimit: 1,
                    ConsumeHour: 1,
                    WxOrder: 1,
                    WxVisible: 0,
                },
                tabs: [
                    {
                        tableData: [], days: '1'
                    },
                    {
                        tableData: [
                            // {name:'1'},
                        ], days: '2'
                    },
                    {
                        tableData: [], days: '3'
                    },
                    {
                        tableData: [], days: '4'
                    },
                    {
                        tableData: [], days: '5'
                    },
                    {
                        tableData: [], days: '6'
                    },
                    {
                        tableData: [], days: '7'
                    },
                ]
            }
        },
        mounted() {
            // 加载课程选项
            this.panelSelect();
            if (parseInt(this.$route.query.id) == 0) {
                //  深拷贝赋初始值
                this.pageTitle = '新增课程表'
                this.deepValue();
                this.panel.name = '';
                this.panel.week = '';
            } else {
                // 读取赋值
                this.pageTitle = '编辑课程表'
                this.getTableQuery();
            }
        },
        methods: {
            // 加载选项
            panelSelect() {
                let that = this;
                let param = {
                    token: localStorage.token,
                    vipType: '',
                    start: 1,
                    expDay: 0,
                    tableMax: 9999,
                };
                let postdata = qs.stringify(param);
                ClassListQuery(postdata).then(res => {
                    let json = res;
                    if (json.Code == 0) {
                        // that.dialogdata = json.Rs;
                        that.panel.options = turnClassResToOption(json.Rs)
                        console.log(that.panel.options);
                    } else {
                        that.$message.error(json.Memo);
                    }
                })
            },
            // 选择课程后，获取当前课程的建议上课人数和课时消耗
            getRowTop(row) {
                let that = this;
                console.log(row);
                let param = {
                    token: localStorage.token,
                    classId: row.ClassId,
                };
                let postdata = qs.stringify(param);
                ClassDetailOne(postdata).then(res => {
                    let json = res;
                    if (json.Code == 0) {
                        row.OrderToplimit = json.Rs.TopLimit;
                        row.ConsumeHour = json.Rs.ConsumeHour;
                        // row.WxOrder = json.Rs.WxOrder; //不支持联动
                        row.WxVisible = json.Rs.WxVisible;
                    } else {
                        that.$message.error(json.Memo);
                    }
                })
            },
            confirmEditLessonTable() {
                let id = this.$route.query.id
                // 提交课程内容,不再修改课程名称和时间的信息
                this.EditLessonTable(id);
            },
            // 删除
            delRow(scope) {
                if(!scope.row.StdId){
                    let delIndex = parseInt(scope.$index)
                    let curIndex = parseInt(this.activeName) - 1;
                    this.tabs[curIndex].tableData.splice(delIndex, 1)
                }else{
                    this.checkCannotDel(scope)
                }
            },
            // 检测课表中课程可否删除
            checkCannotDel(scope) {
                let that = this;
                let param = {
                    token: localStorage.token,
                    stdId : scope.row.StdId ,
                };
                let postdata = qs.stringify(param);
                STTDetailAllowDelCheck(postdata).then(res => {
                    let json = res;
                    if (json.Code == 0) {
                        let delIndex = parseInt(scope.$index)
                        let curIndex = parseInt(this.activeName) - 1;
                        this.tabs[curIndex].tableData.splice(delIndex, 1)
                    } else {
                        that.$message.error(json.Memo);
                    }
                })
            },
            // 提交课程
            confirmLessonTable() {
                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
                }
                let that = this;
                let param = {
                    token: localStorage.token,
                    name: this.panel.name,
                    incomingDate: nonTfmtDatetoLength(this.panel.week, 10),//对应日期 字符串 年-月-日 格式,
                };
                let postdata = qs.stringify(param);
                STTBasicAdd(postdata).then(res => {
                    let json = res;
                    if (json.Code == 0) {
                        that.panel.tabId = json.Id;
                        // 提交课程内容
                        that.EditLessonTable(json.Id);
                    } else {
                        that.$message.error(json.Memo);
                    }
                })
            },
            // 保存课程
            EditLessonTable(planId) {
                let that = this;
                // 校验提交的数据
                if (!this.checkData) {
                    return false
                }
                // 提交数据
                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];
                        thisRow.LessonIndex = parseInt(j + 1);
                        if (planId) {
                            thisRow.StbId = parseInt(planId);
                        } else {
                            thisRow.StbId = parseInt(this.$route.query.id);
                        }
                        thisRow.WeekDay = parseInt(i + 1);
                        thisRow.BeginStr = getHoursAndMin(thisRow.timeLong[0]);
                        thisRow.EndStr = getHoursAndMin(thisRow.timeLong[1]);
                        thisRow.StdId = thisRow.StdId ? thisRow.StdId : 0;
                        this.$delete(thisRow, 'Base');
                        this.$delete(thisRow, 'SpdId');
                        planRs.push(thisRow);
                    }
                }

                let res = JSON.stringify(planRs);
                // 如果传入0就用url里的，如果非0就用传入的
                // let uploadPlanId = planId == 0 ? this.$route.query.id : planId;
                let param = {
                    token: localStorage.token,
                    stbId: planId,
                    stbRs: res,
                };
                let postdata = qs.stringify(param);
                STTDetailBatchSave(postdata).then(res => {
                    let json = res;
                    if (json.Code == 0) {
                        that.$message({
                            showClose: true,
                            message: '课程已上传成功！',
                            type: 'success'
                        });
                        this.$router.push({
                            path: '/lessonManage'
                        });
                        // this.getTableQuery();
                    } else {
                        that.$message.error(json.Memo);
                    }
                })
            },
            // 检查数据
            checkData() {
                // todo
                let tableDate = this.tabs;
                tableDate.map(function (item) {
                    console.log(item);
                })

            },
            // 新增一行
            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 valus = [
                    this.testRow
                ];
                this.tabs.map(function (item) {
                    let res = that.deepClone(valus);
                    item.tableData = res;
                })
            },
            deepClone(obj) {
                let _obj = JSON.stringify(obj),
                    objClone = JSON.parse(_obj);
                return objClone
            },
            handleClick() {
            },
            changeWechat(e, row) {
                // if(parseInt(e) == 0){
                //     this.$message.success('当前课程微信已不可见');
                // }else{
                //     this.$message.success('当前课程微信不可见');
                // }
            },
            changeWechatOrder(e, row) {
                // if(parseInt(e) == 0){
                //     this.$message.success('当前课程微信已不可预约');
                // }else{
                //     this.$message.success('当前课程微信可预约');
                // }
            },
            // 增删会员课程
            lessonStudenChange() {
                this.dialogVisible = true
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            // 页面数据查询
            getTableQuery() {
                let that = this;
                that.loading = true;
                let param = {
                    token: localStorage.token,
                    stbId: this.$route.query.id,//
                };
                // 只能读取，不能修改
                this.panel.inputState = true;
                this.panel.name = this.$route.query.name;


                let postdata = qs.stringify(param);
                STTDetailListQuery(postdata).then(res => {
                    let json = res;
                    let Rs = json.Rs
                    let bt = '';
                    let et = '';
                    if (json.Code == 0) {
                        that.loading = false;
                        // 清掉上次的记录
                        for (let i = 0; i < that.tabs.length; i++) {
                            that.tabs[i].tableData = []
                        }
                        if (Rs) {
                            // 遍历分配
                            Rs.map(function (item) {
                                for (let i = 0; i < 7; i++) {
                                    if (item.WeekDay == i + 1) {
                                        bt = new Date(2016, 9, 10, item.BeginStr.substr(0, 2), item.BeginStr.substr(3, 2));
                                        et = new Date(2016, 9, 10, item.EndStr.substr(0, 2), item.EndStr.substr(3, 2));
                                        item.timeLong = [bt, et];
                                        that.tabs[i].tableData.push(item);

                                    }
                                }
                            })
                        } else {
                            that.allTableData = [];
                            that.recordsTotal = 0;
                        }
                    } else {
                        that.$message.error(json.Memo);
                    }
                })
            },
        },
        watch: {
            $route(to) {
                if (to.name == 'EditLessonManage') {
                    this.temId = this.$route.query.id;
                }
            },
            temId(e) {
                if (parseInt(e) == 0) {
                    this.pageTitle = '新增课程表'
                    this.deepValue();
                    this.panel.name = '';
                    this.panel.week = '';
                    this.panel.inputState = false
                } else {
                    this.pageTitle = '编辑课程表'
                    this.getTableQuery();
                    this.panel.inputState = true
                }
            },
        },
    }
</script>

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

    em {
        font-style: normal;
    }

    .context {
        overflow: hidden;
        height: 770px;

        overflow-y: scroll;
        display: block;
        margin: 0 auto;
        background-color: #fff !important;
        min-height: 100%;
        padding: 30px;
        padding-bottom: 10px;
    }

    .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: 60px;
        z-index: 222;
    }

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

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