<template>
  <div class="manage-root live-create">
    <Header />
    <div class="manage-root-contain">
        <nav-menu class="manage-root-contain-left" :activeMenuIndex="activeMenuIndex"></nav-menu>
        <div class="manage-root-contain-right">
            <breadcrumb :breadcrumbList="breadcrumbList" class="breadcrumb-box"></breadcrumb>
            <div class="create-top">
                <div class="common-title-box">
                    <h3>{{id?'编辑直播课程':'创建直播课程'}}</h3>
                    <div class="btn-box" v-if="id||!id&&stepIndex!==1">
                        <el-button size="small" @click="handleStep('-')" :disabled="stepIndex===0">上一步</el-button>
                        <el-button type="primary" size="small" @click="handleStep('+')" :disabled="stepIndex===1">下一步</el-button>
                    </div>
                </div>
                <el-steps :active="stepIndex" align-center>
                    <el-step title="课程信息" description="填写课程基本信息">
                        <svg-icon icon-class="dot" slot="icon" class="svg-dot"></svg-icon>
                    </el-step>
                    <el-step :title="id?'完成编辑':'完成创建'" :description="id?'课程编辑完成':'课程创建完成'">
                        <svg-icon icon-class="dot" slot="icon" class="svg-dot"></svg-icon>
                    </el-step>
                </el-steps>
            </div>
            <div class="create-bottom">
                <el-form :model="organizeForm" :rules="rulesOrganize" ref="organizeForm" label-width="100px" class="registerForm" v-if="stepIndex===0">
                    <el-form-item label="课程封面" prop="cover_image_url">
                        <upload :datafileList="organizeForm.cover_image_list" :changeFillId="handleAvatarSuccess" :fileName="'cover'" :showList="true" uploadType="image" :filleNumber="1" v-if="!organizeForm.cover_image_url" styleType="upload" />
                        <div class="cover-box" v-else @mouseover="Imagemouseover('coverFlag',true)" @mouseout="Imagemouseover('coverFlag',false)">
                            <el-image :src="organizeForm.cover_image_url" fit="cover" style="width:282px;height:174px;"></el-image>
                            <p v-show="coverFlag" @click="handleDeleteFile('cover',0)"><i class="el-icon-delete"></i></p>
                        </div>
                        <p class="tips">建议上传宽高为282*174的图</p>
                    </el-form-item>
                    <el-form-item label="课程名称" prop="title">
                        <el-input v-model="organizeForm.title" placeholder="请输入课程名称" @blur="handleTrim('organizeForm','title')"></el-input>
                    </el-form-item>
                    <el-form-item label="机构" prop="orgName">
                        <el-select v-model="organizeForm.orgName" filterable allow-create default-first-option placeholder="请选择">
                            <el-option
                                v-for="item in orgList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.name">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="教师" prop="teacher">
                        <el-select v-model="organizeForm.teacher" multiple filterable allow-create default-first-option placeholder="请选择">
                            <el-option
                                v-for="(item,i) in teacherList"
                                :key="item+i"
                                :label="item"
                                :value="item">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="开始时间" prop="startData">
                        <el-date-picker
                            v-model="organizeForm.startData"
                            type="datetime"
                            placeholder="选择日期"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            format="yyyy-MM-dd HH:mm">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="直播链接" prop="liveLink" class="live-link">
                        <el-input v-model="organizeForm.liveLink" placeholder="请输入直播链接" @blur="handleTrim('organizeForm','liveLink')">
                            <template slot="prepend">Http://</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="原价" prop="price" class="price-box">
                        <el-input-number v-model="organizeForm.price" @change="handleChange" :min="0" size="small" :precision="2" class="personal-ceil"></el-input-number>
                        <span class="prepend">￥</span>
                        <span class="append">元</span>
                        <p class="tips">&#160; </p>
                    </el-form-item>
                    <el-form-item label="优惠价格" prop="currentPrice" class="price-box">
                        <el-input-number v-model="organizeForm.currentPrice" @change="handleChange" :min="0" size="small" :precision="2" class="personal-ceil"></el-input-number>
                        <span class="prepend">￥</span>
                        <span class="append">元</span>
                        <p class="tips">优惠价格必须低于原价</p>
                    </el-form-item>
                </el-form>
                <div v-if="stepIndex===1">
                    <el-result icon="success" :subTitle="id?'直播课程编辑成功':'直播课程创建成功'">
                        <template slot="extra">
                            <el-button size="small" @click="handleback">返回列表</el-button>
                            <el-button type="primary" size="small" @click="handleCreate">继续创建</el-button>
                        </template>
                    </el-result>
                </div>
            </div>
        </div>
    </div>
  </div>
</template>

<script>
//这里可以导入其它文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》from ‘《组件路径》';
import Header from "../../../components/Header.vue";
import NavMenu from "../../../components/NavMenu.vue"
import Breadcrumb from '../../../components/Breadcrumb.vue';
import { getLogin } from "@/api/ajax";
import Upload from "../../../components/Upload.vue"

export default {
  //import引入的组件需要注入到对象中才能使用
  components: { Header, NavMenu, Breadcrumb, Upload },
  props: {},
  data() {
    //这里存放数据
    const validatePrice = (rule, value, callback) => {
        if (value === '') {
            callback(new Error('请输入价格'));
        } else {
            let price = this.organizeForm.price
            let currentPrice = this.organizeForm.currentPrice
            if (price!==undefined&&currentPrice!==undefined) {
                if(price===0&&rule.fullField==='price'){
                    callback(new Error('原价需大于0'));
                }else if(currentPrice>=price){
                    callback(new Error('优惠价格必须低于原价'));
                }else{
                    callback();
                }
            } else {
                callback(new Error('请输入'));
            }
            
        }
    };
    return {
        activeMenuIndex: "live_course",
        breadcrumbList:[
            {
                icon:'file-list-line',
                url:'',
                text:''
            },
            {
                icon:'',
                url:'',
                notLink: true,
                text:'内容管理'
            },
            {
                icon:'',
                url:'',
                notLink: true,
                text:'课程管理'
            },
            {
                icon:'',
                url:'',
                text:'直播课'
            }
        ],
        id:this.$route.query.id?this.$route.query.id:'',
        stepIndex:0, // 步骤索引
        newPwdFlag: false, // 查看新密码
        comfirmPwdFlag: false, // 查看确认密码
        organizeForm:{
            cover_image_url: '',
            cover_image_list: [],
            cover_image_id: null,
            title: '',
            orgName: '',
            teacher: [],
            startData:'',
            liveLink:'',
            price:'',
            currentPrice:''
        },
        rulesOrganize:{
            title:[
                { required: true, message: '请输入课程名称', trigger: 'blur' }
            ],
            orgName: [
                { required: true, message: '请输入机构', trigger: 'blur' }
            ],
            teacher: [
                { required: true, message: '请选择教师', trigger: 'change' }
            ],
            startData:[
                { required: true, message: '请选择开始时间', trigger: 'blur' }
            ],
            liveLink:[
                { required: true, message: '请输入直播链接', trigger: 'blur' },
            ],
            price:[
                { required: true, validator: validatePrice, trigger: 'blur' },
            ],
            currentPrice:[
                { required: true, validator: validatePrice, trigger: 'blur' },
            ],
        },
        teacherList:['李老师','赵老师'],
        orgList:[],
        coverFlag: false,
    }
  },
  //计算属性 类似于data概念
  computed: {
    
  },
  //监控data中数据变化
  watch: {
    
  },
  //方法集合
  methods: {
    // 上一步下一步
    handleStep(type){
        if(type=='-'){
            if(this.stepIndex>0) this.stepIndex--
        }else{
            if(this.stepIndex<1) {
                this.$refs['organizeForm'].validate((valid) => {
                    if (valid) {
                        this.handleAddCourse()
                    } else {
                        return false;
                    }
                });
            }
        }
    },
    // 级联选择器
    handleCity(value){
        console.log(value)
    },
    changeIcon(flag){
        this[flag] = !this[flag]
    },
    // 返回列表
    handleback(){
        localStorage.setItem("pageNumber",1)
        this.$router.push({
            path: "/live_course",
            query: {
                
            },
        });
    },
    //继续创建
    handleCreate(){
        this.$router.replace('/createLive')
        location.reload()
    },
    handleChange(value) {
        // console.log(value)
    },
    handleAvatarSuccess(fileList,name) {
        if(name==='cover'){
            this.organizeForm.cover_image_list = fileList
            this.organizeForm.cover_image_id = fileList[0]&&fileList[0].response&&fileList[0].response.file_info_list&&fileList[0].response.file_info_list[0]?fileList[0].response.file_info_list[0].file_id:''
            this.organizeForm.cover_image_url = fileList[0]&&fileList[0].response&&fileList[0].response.file_info_list&&fileList[0].response.file_info_list[0]?fileList[0].response.file_info_list[0].file_url:''
        }else if(name==='courseVideo'){
            this.createCourseForm.videoResource = fileList
            this.createCourseForm.file_id = fileList[0]&&fileList[0].response&&fileList[0].response.file_info_list&&fileList[0].response.file_info_list[0]?fileList[0].response.file_info_list[0].file_id:''
            this.createCourseForm.file_url = fileList[0]&&fileList[0].response&&fileList[0].response.file_info_list&&fileList[0].response.file_info_list[0]?fileList[0].response.file_info_list[0].file_url:''
        }else if(name==='courseAudio'){
            this.createCourseForm.audioResource = fileList
            this.createCourseForm.file_id = fileList[0]&&fileList[0].response&&fileList[0].response.file_info_list&&fileList[0].response.file_info_list[0]?fileList[0].response.file_info_list[0].file_id:''
            this.createCourseForm.file_url = fileList[0]&&fileList[0].response&&fileList[0].response.file_info_list&&fileList[0].response.file_info_list[0]?fileList[0].response.file_info_list[0].file_url:''
        }else if(name==='courseResource'){
            fileList.forEach(item=>{
                if(item.response&&item.response.file_info_list&&item.response.file_info_list[0]){
                    let index = item.response.file_info_list[0].file_name.lastIndexOf('.');
                    item.name = item.response.file_info_list[0].file_name
                    let type = item.response.file_info_list[0].file_name.substring(index + 1).toLowerCase()
                    item.type = this.handleJudgeType(type)
                    item.file_id = item.response.file_info_list[0].file_id
                }
            })
            this.createCourseForm.resource = fileList
        }
    },
    Imagemouseover(item,flag) {
      this[item] = flag
    },
    handleDeleteFile(item,i) {
      this.$confirm("确定删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        if(item==='cover'){
            this.organizeForm.cover_image_list.splice(i, 1);
            this.organizeForm.cover_image_url = ''
            this.organizeForm.cover_image_id = null
        }
      });
    },
    handleAddCourse(){
        let MethodName = "/CourseServer/Manager/ZBCourseManager/AddZBCourse";
        let form = this.organizeForm
        let data = {
            cover_image_id: form.cover_image_id,
            name: form.title,
            org_id: form.orgName,
            teacher_name_list:form.teacher,
            begin_time: form.startData,
            price: form.price,
            price_discount: form.currentPrice,
            url: form.liveLink
        }
        if(this.id){
            MethodName = "/CourseServer/Manager/ZBCourseManager/UpdateZBCourse"
            data.id = this.id
        }
        getLogin(MethodName, data)
        .then((res) => {
            if(res.status===1){
               this.recordedId = res.id
               this.stepIndex++
            }
        })
        .catch(() => {
            this.loading = false
        });
    },
    // 去掉前后空格
    handleTrim(form,fild){
        this[form][fild] = this[form][fild].trim()
    },
    // 查询机构列表
    getOrgList(){
        let MethodName = "/OrgServer/Client/OrgManager/GetOrgIndexList";
        let data = {
            status: 1
        }
        getLogin(MethodName, data)
        .then((res) => {
            if(res.status===1){
               this.orgList = res.org_index_list
            }
        })
        .catch(() => {
        });
    },
    // 获取课程信息
    getCourseInfo(){
        let MethodName = "/CourseServer/Manager/ZBCourseManager/GetZBCourseInfo";
        let data = {
            id: this.id
        }
        getLogin(MethodName, data)
        .then((res) => {
            if(res.status===1){
                let form = this.organizeForm
                form.cover_image_id = res.zb_course.cover_image_id
                form.cover_image_url = res.zb_course.cover_image_url
                form.cover_image_list.push[{
                    id: res.zb_course.cover_image_id
                }]
                form.title = res.zb_course.name
                form.orgName = res.zb_course.org_id
                form.teacher = res.zb_course.teacher_name_list
                form.price = res.zb_course.price
                form.currentPrice = res.zb_course.price_discount
                form.liveLink = res.zb_course.url
                form.startData = res.zb_course.begin_time
            }
        })
        .catch(() => {
            this.loading = false
        });
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    let obj = {
        icon:'',
        url:'',
        text:'创建课程'
    }
    if(this.id){
        obj.text = '编辑课程'
        this.getCourseInfo()
    }
    this.breadcrumbList.push(obj)
    this.getOrgList()
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {

  },
  //生命周期-创建之前
  beforeCreated() { },
  //生命周期-挂载之前
  beforeMount() { },
  //生命周期-更新之前
  beforUpdate() { },
  //生命周期-更新之后
  updated() { },
  //生命周期-销毁之前
  beforeDestory() { },
  //生命周期-销毁完成
  destoryed() { },
  //如果页面有keep-alive缓存功能，这个函数会触发
  activated() { }
}
</script>
<style lang="scss" scoped>
/* @import url(); 引入css类 */
.create-top{
    background: #FFFFFF;
    border-radius: 4px;
    padding: 24px;
    .common-title-box{
        margin-bottom: 4px;
    }
}
.create-bottom{
    padding: 40px 40px;
    margin-top: 16px;
    background: #FFFFFF;
    border-radius: 4px;
    height: calc(100vh - 292px);
    overflow: auto;
    .tips{
        margin: 0;
        color: #86909C;
        font-size: 12px;
        line-height: 20px;
    }
}
.cover-box{
    position: relative;
    width: 282px;
    height: 174px;
    p{
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 174px;
        line-height: 174px;
        font-size: 20px;
        text-align: center;
        cursor: pointer;
        background: rgba(0, 0, 0, 0.3);
        color: #F2F3F5;
        margin: 0;
    }
}
</style>

<style lang="scss">
.live-create{
    .personal-ceil{
        width: 200px;
        .el-input__inner{
            width: 200px;
            padding: 0 60px;
        }
    }
    .el-range-input{
        background: #F2F3F5;
    }
    .el-tag{
        background: #fff;
    }
    .live-link{
        .el-input-group--prepend .el-input__inner{
            margin-left: 0;
            border-left: 1px solid #E5E6EB;
        }
    }
    .price-box{
        width: 300px;
        display: inline-block;
        .el-form-item__content{
            position: relative;
            .prepend,.append{
                position: absolute;
                left: 44px;
                font-size: 14px;
                line-height: 22px;
                color: #1D2129;
                line-height: 34px;
            }
            .append{
                left: 142px;
            }
        }
    }
}
.el-date-picker__editor-wrap{
    .el-input, .el-textarea{
        width: auto;
    }
}
</style>