<template>
    <div class="manage-course-container">
        <div class="mgt-course-header dark-iview-input">
            <Input v-model="keyWord" search :placeholder="$t('cusMgt.searchHolder')" style="width: 300px" @on-change="searchCourse" />
            <div class="action-btn-wrap">
                <!--<span @click="editCus(-1)" :class="selections.length == 0 ? 'action-btn-disabled action-btn':'action-btn'">
                    <Icon type="md-create" size="18" />
                    <span>编辑课程</span>
                </span>-->
                <span v-if="$access.can('admin.*|course-upd')" @click="showConfirmDel(-1)" :class="selections.length == 0 ? 'action-btn-disabled action-btn':'action-btn'">
                    <Icon type="md-trash" size="18" />
                    <span>{{$t('cusMgt.delBatch')}}</span>
                </span>
                <span v-if="$access.can('admin.*|course-upd')" @click="showAddCourse(0)" class="action-btn">
                    <Icon type="md-add" size="18" />
                    <span>{{$t('cusMgt.addCus')}}</span>
                </span>
            </div>
        </div>
        <div class="mgt-course-body dark-iview-table">
            <Table ref="selection" :columns="tableColumns" :data="courseListShow" :height="tableHeight" :loading="tableLoading" @on-selection-change="getSelectInfo">
                <Loading slot="loading" :top="0"></Loading>
                <template slot-scope="{ row,index }" slot="index">
                    {{index + 1}}
                </template>
                <template slot-scope="{ row,index }" slot="period">
                    <!--<span>{{$jsFn.getPeriod(schoolBase,row.period.id).name}}</span>-->
                    <span>{{row.period.name}}</span>
                </template>
                <template slot-scope="{ row,index }" slot="count">
                    <span>{{row.teachers ? row.teachers.length : 0}}</span>
                </template>
                <template slot-scope="{ row,index }" slot="teachers" class="opaque-tooltip">
                    <Tooltip  class="opaque-tooltip" max-width="200" :content="row.teachers ? getTeacherName(row.teachers) : $t('cusMgt.noTeacher')">
                        <span class="teachers-wrap">{{row.teachers ? getTeacherName(row.teachers) : $t('cusMgt.noTeacher')}}</span>
                    </Tooltip>
                </template>
                <template slot-scope="{ row,index }" slot="subject">
                    <span>{{row.subject.name}}</span>
                </template>
                <template slot-scope="{ row,index }" slot="action">
                    <div class="item-tools" v-if="$access.can('admin.*|course-upd')">
                        <Icon type="md-create" style="margin-right:10px;cursor:pointer;" size="18" color="white" @click="editCus(index)" />
                        <Icon type="md-trash" style="margin-left:10px;cursor:pointer;" size="18" color="white" @click="showConfirmDel(index)" />
                    </div>
                </template>
            </Table>
        </div>
        <Modal v-model="addCourseStatus"
               :title="actionType == 0 ? $t('cusMgt.addCus'):$t('cusMgt.editCus')"
               class-name="dark-iview-form dark-iview-modal"
               @on-ok="addCourse">
            <Form ref="courseBaseInfo" :model="courseBaseInfo" :rules="courseBaseValidate" label-position="right" label-colon :label-width="100">
                <FormItem :label="$t('cusMgt.cusName')" prop="name">
                    <Input v-model="courseBaseInfo.name" :placeholder="$t('cusMgt.nameHolder')"></Input>
                </FormItem>
                <FormItem :label="$t('cusMgt.cusCode')" prop="id">
                    <Input v-model="courseBaseInfo.id" :placeholder="$t('cusMgt.codeHolder')"></Input>
                </FormItem>
                <FormItem :label="$t('cusMgt.cusPd')" prop="period.id">
                    <Select v-model="courseBaseInfo.period.id" :placeholder="$t('cusMgt.pdHolder')">
                        <Option v-for="(item,index) in schoolBase.period" :value="item.id" :key="index" 
                                @click.native="courseBaseInfo.period = { id: item.id, name: item.name }">
                            {{ item.name }}
                        </Option>
                    </Select>
                </FormItem>
                <FormItem :label="$t('cusMgt.cusSubject')" prop="subject.id">
                    <Select v-model="courseBaseInfo.subject.id" :placeholder="$t('cusMgt.sjHolder')">
                        <Option v-for="(item,index) in $jsFn.getPeriod(schoolBase, courseBaseInfo.period.id).subjects" 
                                :value="item.id" :key="index" @click.native="courseBaseInfo.subject = {name: item.name, id:item.id}">
                            {{ item.name }}
                        </Option>
                    </Select>
                </FormItem>
                <FormItem :label="$t('cusMgt.cusTeachers')" prop="teachers">
                    <Select label-in-value multiple v-model="teacherId" :placeholder="$t('cusMgt.teacherHolder')" :max-tag-count="3" filterable @on-change="getTeahcers">
                        <Option v-for="(item,index) in $store.state.teachers.teacherList" :value="item.id" :key="index">{{ item.name }}</Option>
                    </Select>
                </FormItem>
            </Form>
        </Modal>
        
    </div>
</template>
<script>
    export default {
        data() {
            // 验证只能是字母和数字
            const validateCode = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error(this.$t('cusMgt.codeErr1')))
                }
                let zg = /^[0-9a-zA-Z]+$/
                if (zg.test(value)) {
                    callback()
                } else {
                    callback(new Error(this.$t('cusMgt.codeErr2')))
                }
            }
            return {
                schoolBase: {
                    period:[]
                },
                tableHeight:780,
                teacherId:[],
                actionType:0, //0新增 1编辑
                delCusList: [],
                tableLoading: false,
                courseBaseInfo: {
                    code: '',
                    id: '',
                    name: '',
                    period: {
                        id: '',
                        name: ''
                    },
                    subject: {
                        id: '',
                        name: ''
                    },
                    teachers: []
                },
                courseBaseValidate: {
                    id: [
                        {required: true, validator: validateCode, trigger: 'change' }
                    ],
                    name: [
                        { required: true, message: this.$t('cusMgt.codeHolder'), trigger: 'change' }
                    ],
                    'period.id': [
                        { required: true, message: this.$t('cusMgt.pdHolder'), trigger: 'change' }
                    ],
                    'subject.id': [
                        { required: true, message: this.$t('cusMgt.sjHolder'), trigger: 'change' }
                    ]
                },
                addCourseStatus: false,
                keyWord: '',
                selections: [],
                courseList: [],
                courseListShow: [],
                tableColumns: [
                    {
                        type: 'selection',
                        width: 80,
                        align: 'center'
                    },
                    {
                        title: this.$t('cusMgt.tableCol1'),
                        slot: 'index',
                        width: 100,
                        align:'center'
                    },
                    {
                        title: this.$t('cusMgt.tableCol2'),
                        key: 'name',
                        align:'center'
                    },
                    {
                        title: this.$t('cusMgt.tableCol3'),
                        key: 'id',
                        align:'center'
                    },
                    {
                        title: this.$t('cusMgt.tableCol4'),
                        slot: 'period',
                        width: 150,
                        align:'center'
                    },
                    {
                        title: this.$t('cusMgt.tableCol5'),
                        slot: 'subject',
                        width: 150,
                        align:'center'
                    },
                    {
                        title: this.$t('cusMgt.tableCol6'),
                        slot: 'count',
                        width: 120,
                        align:'center'
                    },
                    {
                        title: this.$t('cusMgt.tableCol7'),
                        slot: 'teachers',
                        align:'center'
                    },
                    {
                        title: ' ',
                        slot: 'action',
                        width: 150,
                        align:'center'
                    }
                ]
            }
        },
        methods: {
            getTeahcers(val) {
                this.courseBaseInfo.teachers.length = []
                for (let item of val) {
                    this.courseBaseInfo.teachers.push({
                        id: item.value,
                        name:item.label
                    })
                }
            },
            //id换名字
            //获取名字集合
            getTeacherName(ids) {
                let names = ids.map(item => {
                    return item.name
                })
                return names.join(', ')
            },
            //关键字搜索课程
            searchCourse() {
                this.courseListShow = this.courseList.filter((item, index) => {
                    return item.name.indexOf(this.keyWord) != -1
                })
            },
            getSelectInfo(selection) {
                this.selections = selection
            },
            //获取课程列表
            getCourseInfo() {
                this.tableLoading = true
                let requestData = {
                    'school_code': this.$store.state.userInfo.schoolCode
                }
                this.$api.courseMgmt.findCourse(requestData).then(
                    (res) => {
                        if (res) {
                            this.courseList = res.courses
                            this.courseListShow = [...this.courseList]
                        }
                    },
                    (err) => {

                    }
                ).finally(() => {
                    setTimeout(() => {
                        this.tableLoading = false
                    },500)
                })
            },
            
            //显示新增/编辑课程对话框
            showAddCourse(type) {
                this.addCourseStatus = true
                this.actionType = type
                this.courseBaseInfo = {
                    code: '',
                    id: '',
                    name: '',
                    period: {
                        id: '',
                        name: ''
                    },
                    subject: {
                        id: '',
                        name: ''
                    },
                    teachers: [],
                    option:'insert'
                }
                this.teacherId.length = 0
            },
            //显示确认删除对话框
            showConfirmDel(index) {
                this.delCusList.length = 0
                if (index == -1) {//批量删除
                    if (this.selections.length == 0) {
                        this.$Message.warning(this.$t('cusMgt.sltCusTips'))
                    } else {
                        this.delCusList.push(...this.selections)
                    }
                } else {
                    this.delCusList.push(this.courseListShow[index])
                }
                let cusNames = this.delCusList.map(item => {
                    return item.name
                })
                this.$Modal.confirm({
                    title: this.$t('cusMgt.delCus'),
                    content: `${this.$t('cusMgt.delContent')}${cusNames.join(', ')}?`,
                    onOk: () => {
                        this.tableLoading = true
                        this.confirmDelCus()
                    }
                })
            },
            //确认删除课程
            confirmDelCus() {
                if (this.delCusList.length) {
                    let ids = this.delCusList.map((item) => {
                        return item.id
                    })
                    let code = this.$store.state.userInfo.schoolCode
                    this.$api.courseMgmt.deleteCourseAll({
                        ids, code
                    }).then(
                        res => {
                            if (res.error == null) {
                                this.$Message.success(this.$t('cusMgt.delOk'))
                                let ids = this.delCusList.map((item) => {
                                    return item.id
                                })
                                for (let index in this.courseList) {
                                    if (ids.indexOf(this.courseList[index].id) !== -1) {
                                        this.courseList.splice(index, 1)
                                    }
                                }
                                this.keyWord = ''
                                this.searchCourse()
                            } else {
                                this.$Message.error(this.$t('cusMgt.delErr'))
                            }
                        },
                        err => {
                            this.$Message.error(this.$t('cusMgt.delErr'))
                        }
                    ).finally(() => {
                        this.tableLoading = false
                    })
                }
                
            },
            //编辑课程
            editCus(index) {
                this.actionType = 1
                if (index == -1) {//‘批量编辑’
                    if (this.selections.length == 0) {
                        this.$Message.warning(this.$t('cusMgt.sltCusTips'))
                    } else {
                        this.courseBaseInfo = this.selections[0]
                        this.addCourseStatus = true
                    }
                } else {
                    this.courseBaseInfo = this.courseListShow[index]
                    this.teacherId = this.courseBaseInfo.teachers.map(item => {
                        return item.id
                    })
                    this.addCourseStatus = true
                }
            },
            /**新增/修改课程 */
            addCourse() {
                this.$refs['courseBaseInfo'].validate((valid) => {
                    if (valid) {
                        let option = this.courseBaseInfo.option
                        if (!option) {
                            option = 'update'
                        }
                        this.courseBaseInfo.code = this.$store.state.userInfo.schoolCode
                        this.$api.courseMgmt.saveOrUpdateCourse({
                            course: this.courseBaseInfo,
                            option: option
                        }).then(
                            (res) => {
                                if (res.error == null) {
                                    if (this.actionType == 0) {
                                        this.courseList.push(this.courseBaseInfo)
                                        this.$Message.success(this.$t('cusMgt.addOk'))
                                    } else {
                                        this.courseListShow[index].teachers = this._.cloneDeep(this.courseBaseInfo.teachers)
                                        this.$Message.success(this.$t('cusMgt.editOk'))
                                    }
                                    this.keyWord = ''
                                    this.searchCourse()
                                    this.teacherId = []
                                } else {
                                    this.$Message.error('API ERROR!')
                                }
                            },
                            (err) => {
                                this.$Message.error('API ERROR!')
                            }
                        )
                    } else {
                        this.$Message.error(this.$t('cusMgt.formTips'))
                        setTimeout(() => {
                            this.addCourseStatus = true
                        },100)
                    }
                })
            },
        },
        created() {
            this.getCourseInfo()
            this.$nextTick(() => {
                let dom = document.getElementsByClassName('mgt-course-body')
                if (dom.length > 0) {
                    this.tableHeight = dom[0].offsetHeight - 20
                }
            })
            //直接读取登录成功拿到得学校基础信息
            this.$store.dispatch('user/getSchoolProfile').then(
                res => {
                    this.schoolBase = res.school_base
                    this.classList = JSON.parse(JSON.stringify(this.$store.state.user.schoolProfile.school_classes))
                },
                err => {
                    this.$Message.warning(this.$t('cusMgt.noSchool'))
                }
            )
            this.$store.dispatch('teachers/getTeacherList').then(res => {
            })
        }
    }
</script>
<style scoped lang="less">
    @import "./ManageCourse.less";
</style>
<style>
    .mgt-course-body .ivu-table-row-hover .item-tools {
        display: inline-block !important;
    }
    .mgt-course-body .ivu-tooltip {
        width:100%;
    }
</style>