<template>
    <div>
        <el-form :disabled="isDetail">
            <el-card shadow="hover" class="m-b-20">
                <div class="flex-between">
                    <el-page-header @back="goBack" :content="isDetail ? '查看' : (id ? '更新' : '创建') + '教学实验'"></el-page-header>
                    <div>
                        <el-button type="primary" size="small" @click="upload" v-show="!isDetail">{{id ? '更新' : '创建'}}</el-button>
                    </div>
                </div>
            </el-card>

            <el-card shadow="hover" class="mgr20 m-b-20">
                <div>
                    <p class="m-b-20">考核名称</p>
                    <el-input
                        placeholder="请输入考核名称"
                        v-model="experimentalName"
                        clearable
                        maxlength="15"
                        class="inline-input"
                        @change="judgeExpName"
                    ></el-input>
                </div>
            </el-card>

            <el-card shadow="hover" class="mgr20 m-b-20">
                <div>
                    <p class="m-b-20">班级名称</p>
                    <el-input
                        placeholder="请输入班级名称"
                        v-model="experimentalClassName"
                        clearable
                        maxlength="15"
                        class="inline-input"
                    ></el-input>
                </div>
            </el-card>

            <el-card shadow="hover" class="m-b-20">
                <div>
                    <p class="m-b-20">发布方式</p>
                    <el-radio :disabled="id ? true : false" v-model="type" label="1" class="fons">手动发布</el-radio>
                    <el-radio :disabled="id ? true : false" v-model="type" label="2" class="fons">定时发布</el-radio>
                </div>
            </el-card>
            <!-- 根据发布方式判断时间的显示 -->
            <el-card shadow="hover" class="m-b-20">
                <div>
                    <p class="m-b-20">实验时间</p>
                    <!-- 手动发布显示 -->
                    <div class="date-inputs" v-if="type==1">
                        实验时长：
                        <el-input size="small" v-model="duration.day" placeholder></el-input> 天
                        <el-input size="small" v-model="duration.hour" placeholder></el-input> 小时
                        <el-input size="small" v-model="duration.minute" placeholder></el-input> 分
                    </div>

                    <!-- 定时发布显示 -->
                    <div v-if="type==2" class="addAssess">
                        <span class="mgr10">开始时间:</span>
                        <el-date-picker
                            size="small"
                            v-model="date"
                            type="datetimerange"
                            range-separator="-"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            :picker-options="pickerOptions"
                        ></el-date-picker>
                    </div>
                </div>
            </el-card>

            <el-card shadow="hover" class="mgr20 m-b-20">
                <div>
                    <p class="m-b-20">系统</p>
                    <div class="inline-input">
                        <el-select v-model="systemId" placeholder="请选择" @change="initData">
                            <el-option
                                v-for="item in systemList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.id"
                            ></el-option>
                        </el-select>
                    </div>
                </div>
            </el-card>

            <!-- 实训项目模块 -->
            <el-card shadow="hover" class="m-b-20">
                <div class="flex-between m-b-20">
                    <span>实训项目</span>
                    <div style="display: inline-flex;">
                        <div>
                            <el-input size="small" placeholder="请输入项目名称" prefix-icon="el-icon-search" v-model="keyword" clearable></el-input>
                        </div>
                        <el-button style="margin-left: 5px" type="primary" size="small" round @click="toProject">自定义实验项目</el-button>
                    </div>
                </div>
                <!-- 实训项目表格 -->
                <el-table :data="projectData" class="table" stripe header-align="center">
                    <!-- 单选实训项目ID -->
                    <el-table-column width="60" label="选择" align="center">
                        <template slot-scope="scope">
                            <el-radio v-model="projectId" :label="scope.row.projectId">&nbsp;</el-radio>
                        </template>
                    </el-table-column>
                    <el-table-column prop="projectName" label="项目名称" align="center"></el-table-column>
                    <el-table-column prop="auth" label="项目权限" align="center">
                        <template slot-scope="scope">
                            {{projectPermissionsList[scope.row.projectPermissions]}}
                        </template>
                    </el-table-column>
                    <el-table-column prop="creater" label="创建人" align="center">
                        <template slot-scope="scope">
                            {{roleStatus(scope.row.founder)}}
                        </template>
                    </el-table-column>
                    <el-table-column prop="creationTime" label="创建时间" align="center"></el-table-column>
                    <el-table-column label="操作" align="center">
                        <template slot-scope="scope">
                            <el-button type="text" @click="showProject(scope.row)">查看</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="pagination">
                    <el-pagination
                        background
                        :page-size="pageSize"
                        @current-change="handleCurrentChange"
                        layout="total,prev, pager, next"
                        :total="total"
                    ></el-pagination>
                </div>
            </el-card>

            <!-- 邀请码 -->
            <el-card shadow="hover">
                <div style="margin-bottom: 10px">
                    <p class="m-b-20">设置邀请码</p>
                    <el-radio v-model="isCode" label="0">是</el-radio>
                    <el-radio v-model="isCode" label="1">否</el-radio>
                </div>
                <div v-show="isCode == 0">
                    <el-input style="display: inline-block;width: auto;margin-right: 10px" v-model.number="invitationCode" maxlength="6" placeholder="请设置6个数字"></el-input>
                    <el-button type="text" @click="createInv">随机</el-button>
                </div>
            </el-card>
        </el-form>
    </div>
</template>
<script>
import Setting from '@/setting'
import util from '@/libs/util'
import { mapState, mapActions } from 'vuex'
export default {
    data() {
        return {
            id: '',
            roleStatus: util.getRoleName,
            systemId: Setting.systemId,
            systemList: Setting.systemList,
            isDetail: true,
            duration: {
                day: '',
                hour: '',
                minute: ''
            },
            keyword: '',
            searchTimer: null,
            date: '',
            experimentDuration: '0d0h0m',
            experimentalNumber: 0,
            projectId: '',
            projectName: '',
            status: '',
            surplusTime: '',
            experimentalName: '',//考核名称
            experimentalClassName: '', //班级名称
            type: '1',
            isCode: '0', //是否设置邀请码
            startTime: '0000-00-00 00:00:00', //开始时间
            stopTime: '0000-00-00 00:00:00', //结束时间
            invitationCode: '',
            currPage: 1,
            projectDataAll: [],
            projectData: [],
            invRepeat: false,
            pickerOptions: {
                disabledDate: time => {
                    return time.getTime() < new Date().getTime() - 86400000
                }
            },

            projectPermissionsList: ['练习','考核','竞赛'],
            projectQueryData: {
                userId: this.userId,
                systemId: this.systemId
            },
            page: 1,
            pageSize: 5,
            total: 0,
            multipleSelection: [],
            isToProject: false,
            expNameRepeat: false
        };
    },
    computed: {
        ...mapState('user', [
            'userId'
        ]),
        ...mapState('project', [
            'assFields'
        ]),
    },
    mounted() {
        console.log(22,this.assFields)
        this.date = [util.formatDate("yyyy-MM-dd hh:mm:ss",new Date(new Date().getTime() + 300000)),util.formatDate("yyyy-MM-dd hh:mm:ss",new Date(new Date().getTime() + 300000))]
        this.id = this.$route.query.id
        this.isDetail = Boolean(this.$route.query.show)
        this.id && this.getData()
        this.getProjectData()
        this.recoveryData()
    },
    beforeDestroy(){
        if(!this.isToProject) this.setAss({})
    },
    watch: {
        date: function(val){
            if(val[0] != '0000-00-00 00:00:00'){
                this.startTime = util.formatDate("yyyy-MM-dd hh:mm:ss",new Date(val[0]))
                this.stopTime = util.formatDate("yyyy-MM-dd hh:mm:ss",new Date(val[1]))
            }
        },
        duration: {
            handler(n,o){
                this.experimentDuration = `${n.day ? n.day : 0}d${n.hour ? n.hour : 0}h${n.minute ? n.minute : 0}m`
            },
            deep: true
        },
        keyword: function(val) {
            clearTimeout(this.searchTimer)
            this.searchTimer = setTimeout(() => {
                this.initData()
            },500)
        }
    },
    methods: {
        ...mapActions('project', [
            'setAss'
        ]),
        getProjectData(){ 
            let data = {
                pageNo: this.page,
                pageSize: 10000,
                userId: this.userId,
                systemId: this.systemId,
                projectName: this.keyword,
                projectPermissions: 1,
            }
            this.$get(this.api.queryAllManagements,data).then(res => {
                let list = res.pageInfo.list
                let result = []
                list.map(n => {
                    n.enable || result.push(n)
                })
                this.projectDataAll = result
                this.total = result.length
                this.handlePage()
            }).catch(res => {});
        },
        handlePage(){
            let list = this.projectDataAll
            let result = list.slice((this.page - 1) * this.pageSize,this.page * this.pageSize)
            this.projectData = result
        },
        initData(){
            this.page = 1
            this.getProjectData()
        },
        recoveryData(){
            if(JSON.stringify(this.assFields) != '{}'){
                let info = this.assFields
                this.experimentDuration = info.experimentDuration
                this.experimentalClassName = info.experimentalClassName
                this.experimentalName = info.experimentalName
                this.invitationCode = info.invitationCode
                this.isCode = String(info.isCode)
                this.projectId = info.projectId
                this.startTime = info.startTime
                this.stopTime = info.stopTime
                this.surplusTime = info.surplusTime
                this.type = String(info.type)
                this.expNameRepeat = info.expNameRepeat

                this.formatDuration()
            }
        },
        upload() {
            if(!this.experimentalName) return this.$message.warning('请填写考核名称')
            if(this.expNameRepeat) return this.$message.warning('考核名称重复，请重新输入')
            if(!this.experimentalClassName) return this.$message.warning('请填写班级名称')
            if(this.type == 1){
                this.status = 1
            }else{
                if(new Date().getTime() > new Date(this.startTime).getTime()) return this.$message.warning('开始时间不能早于当前时间')
                this.status = 1
                let timestamp = new Date(new Date(this.stopTime).getTime() - new Date(this.startTime).getTime())
                let minute = 1000 * 60
                let hour = minute * 60
                let day = hour * 24
                this.experimentDuration = `${Math.floor(timestamp / day)}d${Math.floor(timestamp % day / hour)}h${Math.floor(timestamp % day % hour / minute)}m`
            }
            if(this.type == 1 && this.experimentDuration == '0d0h0m') return this.$message.warning('请填写实验时长')
            if(this.type == 2 && this.startTime == '0000-00-00 00:00:00') return this.$message.warning('请填写实验时间')
            if(!this.projectId) return this.$message.warning('请选择实训项目')
            this.projectName = this.projectData.find(n => n.projectId == this.projectId).projectName
            if(this.isCode == 0){
                if(!this.invitationCode) return this.$message.warning('请设置邀请码')
                if(!this.invitationCode || String(this.invitationCode).length < 6 || isNaN(this.invitationCode)) return this.$message.warning('请输入6位纯数字邀请码')
                // if(this.invRepeat) return this.$message.warning('邀请码重复，请重新输入')
            }
            
            let data = {
                id: this.id,
                experimentDuration: this.experimentDuration,
                creationTime: this.id ? this.creationTime : util.formatDate("yyyy-MM-dd hh:mm:ss"),
                experimentalClassName: this.experimentalClassName,
                experimentalName: this.experimentalName,
                experimentalNumber: this.experimentalNumber,
                invitationCode: this.invitationCode,
                isCode: this.isCode,
                projectId: this.projectId,
                projectName: this.projectName,
                status: Number(this.status),
                surplusTime: this.surplusTime,
                type: Number(this.type),
                userId: this.userId,
                systemId: this.systemId
            }
            if(this.type == 2){
                data.startTime = this.startTime
                data.stopTime = this.stopTime
            }else{
                data.startTime = '0000-00-00 00:00:00'
                data.stopTime = '0000-00-00 00:00:00'
            }
            if(this.id){
                this.$post(this.api.expUpdate, data).then(res => {
                    util.successMsg('修改成功');
                    this.$router.back()
                })
                .catch(err => {
                });
            }else{
                this.$post(this.api.expSave, data).then(res => {
                    util.successMsg('创建成功');
                    this.$router.back()
                })
                .catch(err => {
                });
            }
        },
        getData() {
            this.$get(this.api.expInfo + this.id)
                .then(res => {
                    if(res.errmessage == 'success'){
                        let info = res.ExperimentalTeaching
                        this.creationTime = info.creationTime
                        this.experimentDuration = info.experimentDuration
                        this.experimentalClassName = info.experimentalClassName
                        this.experimentalName = info.experimentalName
                        this.experimentalNumber = info.experimentalNumber
                        this.invitationCode = info.invitationCode
                        this.isCode = String(info.isCode)
                        this.projectId = info.projectId
                        this.projectName = info.projectName
                        this.startTime = info.startTime
                        this.status = info.status
                        this.stopTime = info.stopTime
                        this.surplusTime = info.surplusTime
                        this.type = String(info.type)

                        this.formatDuration()
                    }else{
                        util.errorMsg('查询失败');
                    }
                })
                .catch(err => {

                });
        },
        formatDuration(){
            let duration = this.experimentDuration.replace(/\D+/g,',').split(',')
            this.duration = {
                day: duration[0],
                hour: duration[1],
                minute: duration[2]
            }
            this.date = [this.startTime,this.stopTime]
        },
        handleCacheData(){
            let data = {
                id: this.id,
                experimentDuration: this.experimentDuration,
                experimentalClassName: this.experimentalClassName,
                experimentalName: this.experimentalName,
                invitationCode: this.invitationCode,
                isCode: this.isCode,
                projectId: this.projectId,
                startTime: this.startTime,
                stopTime: this.stopTime,
                surplusTime: this.surplusTime,
                type: this.type,
                expNameRepeat: this.expNameRepeat
            }
            this.setAss(data)
            this.isToProject = true
        },
        toProject(){
            this.handleCacheData()
            this.$router.push('/project')
        },
        showProject(row){
            this.handleCacheData()
            this.$router.push(`/addproject?id=${row.projectId}&show=1`)
        },
        goBack() {
            if(this.isDetail){
                this.$router.back()
            }else{
                this.$confirm('确定返回？未更新的信息将不会保存。', '提示', {
                    type: 'warning'
                })
                .then(() => {
                    this.$router.back()
                })
                .catch(() => {});
            }
        },
        varifyInv() {
            this.$get(this.api.getInvitationCode, { invitationCode: this.invitationCode })
            .then(res => {
                if(res.InvitationCode) {
                    this.$message.warning('邀请码重复，请重新输入')
                    this.invRepeat = true
                }else{
                    this.invRepeat = false
                }
            })
            .catch(err => {});
        },
        createInv() {
            let result = ''
            for(let i=0; i<6; i++){
                result += Math.floor(Math.random()*10)
            }
            this.invitationCode = result
            // this.varifyInv()
        },
        handleCurrentChange(val){
            this.page = val
            this.handlePage()
        },
        judgeExpName(){
            this.$get(this.api.expCheck, { experimentalName: util.encodeStr(this.experimentalName) })
            .then(res => {
                if(res.errmessage != 'success') {
                    this.$message.warning('考核名称重复，请重新输入')
                    this.expNameRepeat = true
                }else{
                    this.expNameRepeat = false
                }
            })
            .catch(err => {});
        },
    },
};
</script>

<style lang="scss" scoped>
    .inline-input{
        width: 300px;
    }
    .date-inputs{
        .el-input{
            width: 100px;
        }
    }
</style>