<template>
    <div class="template-wrap">
        <div class="order-learn-header">
            <span class="order-learn-title">
                创建编序式学习
            </span>
            <Button class="btn-save" type="text" :loading="isLoading" ghost icon="ios-albums-outline" @click="saveData">保存数据</Button>
            <Button class="btn-save" type="text" :loading="isLoading" ghost icon="md-arrow-back" to="/home/SelfLearn" style="margin-right: 10px;">返回上级</Button>
        </div>
        <div class="order-learn-main">
            <!-- 基础信息表单 -->
            <div class="base-info-wrap">
                <p class="base-info-label">基础信息</p>
                <div class="base-info-form">
                    <!--<vuescroll>  -->
                    <Form ref="orderLearnInfo" :model="orderLearnInfo" label-position="top" class="evaluation-attr-form" :rules="ruleValidate" label-colon>
                        <FormItem label="名称" prop="name">
                            <Input v-model="orderLearnInfo.name"></Input>
                        </FormItem>
                        <FormItem label="学段" prop="periodCode">
                            <Select v-model="orderLearnInfo.periodCode">
                                <Option v-for="(item,index) in $store.state.user.schoolProfile.school_base.period" :value="item.id" :key="index">{{ item.name }}</Option>
                            </Select>
                        </FormItem>
                        <FormItem label="科目" prop="subjectCode">
                            <Select v-model="orderLearnInfo.subjectCode" not-found-text="请先选择学段">
                                <Option v-for="(item,index) in $jsFn.getPeriod($store.state.user.schoolProfile.school_base,orderLearnInfo.periodCode).subjects" :value="item.id" :key="index">{{ item.name }}</Option>
                            </Select>
                        </FormItem>
                        <FormItem label="描述" prop="introduce">
                            <Input v-model="orderLearnInfo.introduce" type="textarea" :rows="8"></Input>
                        </FormItem>
                    </Form>
                    <!--</vuescroll>-->
                </div>
            </div>
            <div class="order-learn-main dark-iview-split">
                <Split v-model="split1">
                    <!-- 学习阶段列表 -->
                    <div slot="left" class="learn-step-wrap">
                        <div class="base-info-label">
                            <span>
                                学习阶段
                            </span>
                            <!--只能挑选学习单元-->
                            <!--<Tooltip style="float:right;" placement="left">
                                <Icon class="add-learn-step-icon" type="md-add" size="20" />
                                <div slot="content">
                                    <p class="add-step-type-label" @click="addStepStatus = true"><Icon type="ios-hand-outline" size="18" style="margin-right:5px;" />手动选择内容</p>
                                    <p class="add-step-type-label" @click="selectUnit"><Icon type="md-list" size="18" style="margin-right:5px;" />选择最小单元</p>
                                </div>
                            </Tooltip>-->
                            <Icon class="add-learn-step-icon" type="md-add" size="20" @click="selectUnit"/>
                        </div>
                        <Table draggable :columns="columns" :data="orderLearnInfo.steps" @on-drag-drop="dragOrder" @on-row-click="getCurrentItem" :row-class-name="setClassName" style="width:100%;">
                            <template slot-scope="{ row, index }" slot="name">
                                <Icon type="ios-pricetags" color="white" style="margin-right:8px;" />
                                <span class="learn-step-name">{{row.name}}</span>
                            </template>
                            <template slot-scope="{ row, index }" slot="action">
                                <Icon type="md-create" color="white" class="edit-step-name-icon" @click="editSName(index)" />
                            </template>
                        </Table>
                    </div>
                    <!-- 学习资源区域 -->
                    <div slot="right" class="learn-content-wrap">
                        
                        <div class="base-info-label">
                            学习资源
                            <!--只能挑选最小单元，不能自定义添加内容-->
                            <div class="radio-box-wrap" style="display:none;">
                                <div :class="currentView == 0 ? 'radio-box-item active-radio-box-item':'radio-box-item'" @click="setCurrentView(0)">
                                    <Tooltip content="查看学习资源" placement="bottom">
                                        <Icon type="md-list" size="15" />
                                    </Tooltip>
                                </div>
                                <div :class="currentView == 1 ? 'radio-box-item active-radio-box-item':'radio-box-item'" @click="setCurrentView(1)">
                                    <Tooltip content="挑选学习资源" placement="bottom">
                                        <Icon type="md-card" size="15" />
                                    </Tooltip>
                                </div>
                            </div>
                        </div>
                        <!-- 选择学习资源 禁用！！！ -->
                        <div v-if="orderLearnInfo.steps.length !== 0" style="display:none;" :class="currentView == 1 ? 'animated faster fadeInLeft choose-learn-content-wrap':'animated fadeOutRight choose-learn-content-wrap'">
                            <ChooseContent ref="chooseContent" style="margin-top:10px;height:calc(100% - 10px);" @on-select-question="getSelectedQuestion" @on-cancel-file="cancelFile" @on-select-file="getSelectFile"></ChooseContent>
                            <Poptip padding="0px 0px" offset="10" placement="top-end" width="300" trigger="hover" :class="shoppingCarClass">
                                <Badge type="success" :count="getContentLength.total" show-zero :offset="[-3,-3]" style="margin-top:10px;cursor:pointer;" @mouseenter.native="changeActive($event)" @mouseleave.native="removeActive($event)">
                                    <Icon custom="iconfont icon-sp-car" color="#1cc0f3" size="40" />
                                </Badge>
                                <div slot="content">
                                    <div class="shopping-car-detail">
                                        <p class="shopping-car-detail-title">资源概览</p>
                                        <div class="shopping-car-detail-item">
                                            <span class="question-type">内容数：</span>
                                            <Progress stroke-color="#6bdfc3" :percent="getContentLength.total == 0 ? 0 : getContentLength.resourceL*100/getContentLength.total" :stroke-width="15" style="width:165px;vertical-align:top;padding-top:2px;" hide-info />
                                            <span class="question-num">{{getContentLength.resourceL}}道</span>
                                        </div>
                                        <div class="shopping-car-detail-item">
                                            <span class="question-type">习题数：</span>
                                            <Progress stroke-color="#6bdfc3" :percent="getContentLength.total == 0 ? 0 : getContentLength.itemL*100/getContentLength.total" :stroke-width="15" style="width:165px;vertical-align:top;padding-top:2px;" hide-info />
                                            <span class="question-num">{{getContentLength.itemL}}道</span>
                                        </div>
                                        <p class="shopping-car-detail-bottom" @click="goToPreview">查看详情</p>
                                    </div>

                                </div>
                            </Poptip>
                        </div>
                        <EmptyData v-if="orderLearnInfo.steps.length == 0" style="margin-top:100px;"></EmptyData>
                        <!-- 查看已选择资源 -->
                        <div v-if="orderLearnInfo.steps.length !== 0" :class="currentView == 0 ? 'animated faster fadeInLeft preview-learn-content-wrap':'animated fadeOutRight preview-learn-content-wrap'">
                            <vuescroll>
                                <p class="content-type-label">内容：{{orderLearnInfo.steps[stepIndex].resource.length}}个</p>
                                <div class="content-file-wrap" style="min-height:240px;">
                                    <Loading v-show="listLoading"></Loading>
                                    <ContentFileList v-show="!listLoading" :resources="orderLearnInfo.steps[stepIndex].resource"></ContentFileList>
                                </div>
                                <p class="content-type-label">题目：{{orderLearnInfo.steps[stepIndex].item.length}}道</p>
                                <div class="content-question-wrap">
                                    <EmptyData v-if="orderLearnInfo.steps[stepIndex].item.length == 0" style="margin-top:30px;"></EmptyData>
                                    <Loading v-show="listLoading"></Loading>
                                    <QuestionList v-show="!listLoading" :questions="orderLearnInfo.steps[stepIndex].item"></QuestionList>
                                </div>
                            </vuescroll>
                        </div>
                    </div>
                </Split>
            </div>
        </div>

        <Modal v-model="addStepStatus"
               title="添加学习阶段"
               class="dark-iview-modal dark-iview-input"
               width="660"
               @on-ok="confirmAddStep">
            <span>名称：</span>
            <Input v-model="newStepName" placeholder="请输入名称..." style="width: calc(100% - 50px);" />
        </Modal>
        <Modal v-model="selectUnitStatus"
               title="选择学习单元"
               class="dark-iview-modal"
               width="960"
               @on-ok="confirmSelectUnit">
            <SelectLearnUnit @selectUnit="getSelectedUnit"></SelectLearnUnit>
        </Modal>
        <Modal v-model="editStepStatus"
               title="修改名称"
               class="dark-iview-modal dark-iview-input"
               @on-ok="confirmEditStep">
            <span>名称：</span>
            <Input v-model="editStepName" placeholder="请输入名称..." style="width: calc(100% - 50px);" />
        </Modal>
        <Modal v-model="goToManageStatus"
               title="管理编序式自主学习活动"
               ok-text="是"
               cancel-text="否"
               @on-ok="confirmToManage">
            <p>编序式自主学习活动保存成功，是否跳转到管理页面查看？</p>
        </Modal>

    </div>
</template>
<script>
    
    import QuestionList from '@/components/learnactivity/QuestionList.vue'
    import ChooseContent from '@/components/selflearn/NewChooseContent.vue'
    import SelectLearnUnit from '@/components/selflearn/SelectLearnUnit.vue'
    import ContentFileList from '@/components/selflearn/ContentFileList.vue'
    import Loading from '@/common/Loading.vue'
    export default {
        components: {
            
            QuestionList,
            ChooseContent,
            SelectLearnUnit,
            ContentFileList,
            Loading
        },
        data() {
            return {
                selectedUnit: [],
                selectUnitStatus: false,
                isLoading: false,
                listLoading: false,
                goToManageStatus: false,
                shoppingCarClass: 'question-shopping-car',
                newStepName: '',
                editStepName: '',
                addStepStatus: false,
                editStepStatus: false,
                currentView: 0,
                split1: 0.2,
                currentCreateType: 0,
                stepIndex: 0,
                classroomList: [],
                columns: [
                    {
                        title: '',
                        slot: 'name',
                        ellipsis: true
                    },
                    {
                        title: '',
                        slot: 'action',
                        width: 50,
                        align: 'right'
                    }
                ],
                orderLearnInfo: {
                    name: '',
                    periodCode: '',
                    subjectCode: '',
                    creator: '',
                    introduce: '',
                    steps: []
                    //target: [],
                    //type: '',
                    //isOrder: '',
                },
                ruleValidate: {
                    name: [
                        { required: true, message: '请完善活动名称', trigger: 'change' }
                    ],
                    periodCode: [
                        { required: true, message: '请选择学段', trigger: 'change' }
                    ],
                    subjectCode: [
                        { required: true, message: '请选择学科', trigger: 'change' }
                    ],
                    isOrder: [
                        { required: true, message: '请选择模式', trigger: 'change' }
                    ],
                    introduce: [
                        { required: true, message: '请完善说明信息', trigger: 'change' }
                    ]
                },
            }
        },
        created() {
            let routerData = this.$route.params.orderLearnInfo
            if (routerData != undefined) {
                this.orderLearnInfo = routerData
            }
        },
        computed: {
            getContentLength() {
                if (this.orderLearnInfo.steps.length == 0) {
                    return {
                        itemL: 0,
                        resourceL: 0,
                        total: 0
                    }
                } else {
                    let itemL = this.orderLearnInfo.steps[this.stepIndex].item == undefined ? 0 : this.orderLearnInfo.steps[this.stepIndex].item.length
                    let resourceL = this.orderLearnInfo.steps[this.stepIndex].resource == undefined ? 0 : this.orderLearnInfo.steps[this.stepIndex].resource.length
                    return {
                        itemL,
                        resourceL,
                        total: itemL + resourceL
                    }

                }
            }
        },
        methods: {
            /**
             * 通过id查询题目信息
             * */
            findQuestionById() {
                if (this.orderLearnInfo.steps.length > 0) {
                    this.listLoading = true
                    if (!this.orderLearnInfo.steps[this.stepIndex].requestedI) {
                        this.$api.learnActivity.FindQuestionById(this.orderLearnInfo.steps[this.stepIndex].item).then(
                            res => {
                                if (res.error == null) {
                                    this.orderLearnInfo.steps[this.stepIndex].item.length = 0
                                    this.$set(this.orderLearnInfo.steps[this.stepIndex], 'item', res.result.data)
                                    this.orderLearnInfo.steps[this.stepIndex].requestedI = true
                                } else {
                                    this.$Message.error("API ERROR!")
                                }
                                setTimeout(() => {
                                    this.listLoading = false
                                }, 500)
                            },
                            err => {
                                this.$Message.error("API ERROR!")
                                setTimeout(() => {
                                    this.listLoading = false
                                }, 1000)
                            }
                        )
                    } else {
                        setTimeout(() => {
                            this.listLoading = false
                        }, 300)
                    }
                }
            },
            /**
             * 通过id查询内容信息
             * */
            findResourceById() {
                if (this.orderLearnInfo.steps.length > 0) {
                    this.listLoading = true
                    if (!this.orderLearnInfo.steps[this.stepIndex].requestedR) {
                        this.$api.learnActivity.FindSyllabusResourceById(this.orderLearnInfo.steps[this.stepIndex].resource).then(
                            res => {
                                if (res.error == null) {
                                    this.orderLearnInfo.steps[this.stepIndex].resource.length = 0
                                    this.orderLearnInfo.steps[this.stepIndex].resource = res.result.data
                                    this.orderLearnInfo.steps[this.stepIndex].requestedR = true
                                } else {
                                    this.$Message.error("API ERROR!")
                                }
                                setTimeout(() => {
                                    this.listLoading = false
                                }, 500)
                            },
                            err => {
                                this.$Message.error("API ERROR!")
                                setTimeout(() => {
                                    this.listLoading = false
                                }, 500)
                            }
                        )
                    } else {
                        setTimeout(() => {
                            this.listLoading = false
                        }, 300)
                    }
                }
            },
            /**
             * 确认修改学习阶段名称
             * @param index
             */
            confirmEditStep() {
                this.orderLearnInfo.steps[this.stepIndex].name = this.editStepName
            },
            /**
             * 编辑学习阶段名称
             * @param index
             */
            editSName(index) {
                this.editStepName = this.orderLearnInfo.steps[index].name
                this.editStepStatus = true
            },
            confirmToManage() {
                this.$router.push({
                    name: 'selfLearn'
                })
            },
            goToPreview() {
                this.currentView = 0
            },
            selectUnit() {
                this.selectUnitStatus = true
            },
            /**
             * 处理SelectLearnUnit组件选择事件
             * @param data
             */
            getSelectedUnit(data) {
                this.selectedUnit = data
            },
            confirmSelectUnit() {
                this.orderLearnInfo.steps.push(...this.selectedUnit)
                this.selectedUnit.length = 0
            },
            changeActive(e) {
                this.shoppingCarClass = 'question-shopping-car animated pulse'
            },
            removeActive() {
                this.shoppingCarClass = 'question-shopping-car'
            },
            chooseUnit(data) {
                this.orderLearnInfo.steps.push(data)
            },
            confirmAddStep() {
                this.orderLearnInfo.steps.push(
                    {
                        name: this.newStepName,
                        requestedI: true,
                        requestedR: true,
                        resource: [],
                        item: []
                    }
                )
                this.newStepName = ''
            },
            checkData() {
                let flag = true
                this.$refs.orderLearnInfo.validate((valid) => {
                    if (!valid) {
                        flag = false
                    }
                })
                return flag
            },
            saveData() {
                let check = this.checkData()
                if (check) {
                    this.isLoading = true
                    this.orderLearnInfo.creator = this.$store.state.userInfo.TEAMModelId
                    this.orderLearnInfo.code = this.$store.state.userInfo.TEAMModelId
                    let str = JSON.stringify(this.orderLearnInfo)
                    let requestData = JSON.parse(str)
                    for (let i = 0; i < requestData.steps.length; i++) {
                        if (requestData.steps[i].requestedI) {
                            requestData.steps[i].item = requestData.steps[i].item.map(item => { return item.id })
                        } 
                        if (requestData.steps[i].requestedR) {
                            requestData.steps[i].resource = requestData.steps[i].resource.map(item => { return item.id })
                        }                        
                    }
                    
                    this.$api.learnActivity.SaveOrderLearn(requestData).then(
                        res => {
                            if (res.error == null) {
                                this.orderLearnInfo.id = res.result.data.id
                                this.goToManageStatus = true
                            } else {
                                this.$Message.error('API ERROR!')
                            }
                            this.isLoading = false
                        },
                        err => {
                            this.isLoading = false
                        }
                    )
                } else {
                    this.$Message.error('请先完善信息，再保存！')
                }
            },
            getSelectedQuestion(data) {
                this.orderLearnInfo.steps[this.stepIndex].item.push(data.question)
                this.shoppingCarClass = 'question-shopping-car animated heartBeat'
                setTimeout(() => {
                    this.shoppingCarClass = 'question-shopping-car'
                }, 1000)
            },
            cancelFile(data) {
                this.orderLearnInfo.steps[this.stepIndex].resource = data.files
            },
            getSelectFile(data) {
                this.orderLearnInfo.steps[this.stepIndex].resource.push(data.file)
                this.shoppingCarClass = 'question-shopping-car animated heartBeat'
                setTimeout(() => {
                    this.shoppingCarClass = 'question-shopping-car'
                }, 1000)
            },
            setCurrentView(index) {
                this.currentView = index
            },
            selectCreateType(index) {
                this.currentCreateType = index
            },
            addContent() {
                this.stepIndex = (++this.stepIndex) % 5
            },
            setClassName(row, index) {
                if (index == this.stepIndex) {
                    return 'ivu-table-row-highlight'
                }
            },
            getCurrentItem(row, index) {
                this.stepIndex = index
                this.currentView = 0
                this.$refs.chooseContent.refreshData()
            },
            dragOrder(index1, index2) {
                if (index1 > index2) {
                    let item = this.orderLearnInfo.steps[index1];
                    this.orderLearnInfo.steps.splice(index1, 1);
                    this.orderLearnInfo.steps.splice(index2, 0, item);
                } else if (index1 < index2) {
                    let item = this.orderLearnInfo.steps[index1];
                    this.orderLearnInfo.steps.splice(index2, 0, item);
                    this.orderLearnInfo.steps.splice(index1, 1);
                }
            }
        }
    }
</script>
<style scoped lang="less">
    @import "./CreateOrderLearn.less";
</style>
<style lang="less">
    .content-file-wrap #loadingBox {
        margin-top: 88px !important;
    }
    .base-info-label .ivu-tooltip-inner {
        background-color: rgba(70,76,91,1);
    }

    .base-info-form .ivu-input, .base-info-form .ivu-select-selection {
        background: none;
        color: white;
        border-color: #606060;
    }

    .base-info-form .ivu-form .ivu-form-item-label {
        color: #A5A5A5;
    }

    .learn-step-wrap {
        background: none;
    }

        .learn-step-wrap .ivu-table-cell {
            padding-left: 0px;
        }

        .learn-step-wrap .ivu-table-header thead tr th {
            display: none;
        }

        .learn-step-wrap .ivu-table {
            background: none;
        }

            .learn-step-wrap .ivu-table td {
                background: none;
                color: #a5a5a5;
                border-bottom: 1px solid #424242;
            }

        .learn-step-wrap .ivu-table-wrapper {
            border: none;
        }

        .learn-step-wrap .ivu-table::before {
            content: none;
        }

        .learn-step-wrap .ivu-table::after {
            content: none;
        }

        .learn-step-wrap .ivu-table-row-hover {
            background: #363636;
        }

            .learn-step-wrap .ivu-table-row-hover .item-tools {
                display: inline-block !important;
            }

    .ivu-table-overflowY {
        &::-webkit-scrollbar

    { /*滚动条整体样式*/
        width: 5px; /*高宽分别对应横竖滚动条的尺寸*/
        height: 1px;
    }

    &::-webkit-scrollbar-thumb { /*滚动条里面小方块*/
        -webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
        background: rgb(124,124,124);
    }

    &::-webkit-scrollbar-track { /*滚动条里面轨道*/
        -webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
        background: rgba(68,68,68,.5);
    }

    }

    .learn-step-wrap .ivu-table-row-hover td {
        background: none !important;
    }

    .learn-step-wrap .ivu-table-header {
        background-color: #222222;
    }

    .learn-step-wrap .ivu-table-row-highlight {
        background-image: linear-gradient(90deg, rgba(30, 30, 30, 0) 0%, rgba(110, 110, 110, 0.2) 50%, rgba(110, 110, 110, 0.4) 100%);
    }

    .learn-step-wrap .ivu-table-row-hover .edit-step-name-icon {
        display: inline-block;
    }
</style>