<template>
    <div class="my-note" @change="handleClick">
        <div class="mynote">
            <div class="mynote-tab">
                <div @click="notetabType(1)" :class="notetab == 1 ? 'noteactive' : ' ' "> <span>新增笔记</span> </div>
                <div @click="notetabType(2)" :class="notetab == 2 ? 'noteactive' : ' '"> <span>我的笔记</span> </div>
            </div>
            <!-- 新增笔记  -->
            <div class="newcote-content" v-if="notetab == 1">
                <div class="newcote-time" v-if="mynoteData.playTime != 0">
                    <img :src="`${webBaseUrl}/images/coteplay.png`" />
                    {{formatSeconds(mynoteData.playTime)}}
                    <img :src="`${webBaseUrl}/images/cotedetel.png`" @click="timeDel()" />
                </div>
                <div class="newcote-text">
                    <el-input type="textarea" :autofocus="true" :style="`min-height:${inputHeight}px`" placeholder="好记性不如烂笔头，记录些什么吧～"
                        v-model="content_new" maxlength="200" :autosize="{ minRows: inputRows, maxRows: 20}"
                        show-word-limit>
                    </el-input>
                </div>
            </div>
            <!-- 我的笔记  -->
            <div  v-if="notetab == 2">
                <div class="mycote-content" v-show="!isEdit" :style="`height:${listHeight}px`">
                    <div v-if="noteList.length > 0">
                    <div style="border-bottom:1px solid #4444;padding-bottom:25px;" v-for="note in noteList"
                        :key="note.id">
                        <span class="mycote-time">{{note.sysUpdateTime}}
                            <span class="sm">{{note.openType == 9?'公开':'私密'}}</span>
                            <span class="more">
                                <el-dropdown>
                                    <span class="el-dropdown-link">
                                        <svg-icon style="margin-right: 0;font-size:26px;" icon-class="spot"></svg-icon>
                                    </span>
                                    <el-dropdown-menu slot="dropdown" class="dropdown-box"
                                        style="background:#333333;border: none;">
                                        <el-dropdown-item command="a" style="color:#fff" @click.native="noteDel(note)">
                                            <img style="width:13px;height:18px;vertical-align: middle;"
                                                src="@/assets/images/icon/note-del.png" /> 删除</el-dropdown-item>
                                        <el-dropdown-item command="b" style="color:#fff" @click.native="noteEdit(note)">
                                            <img style="width:13px;height:14px;margin-right:4px;vertical-align: middle;"
                                                src="@/assets/images/icon/note-edit.png" />编辑</el-dropdown-item>
                                    </el-dropdown-menu>
                                </el-dropdown>
                            </span>
                        </span>
                        <div style="margin-top:10px" class="newcote-time" v-if="note.playTime"
                            @click="onPlayVideo(note.contentId,note.playTime)">
                            <img :src="`${webBaseUrl}/images/coteplay.png`" alt="">
                            {{formatSeconds(note.playTime)}}
                        </div>
                        <div class="newcote-text">
                            {{note.content}}
                        </div>
                    </div>
                    <h6 class="mycote-dibu">已经到底啦</h6>
                    </div>
                    <div class="my-nonote" v-else>
                        <img :src="`${webBaseUrl}/images/no-note.png`" alt="" />
                        <h6 style="color: #666666;font-size: 14px;">你还没有记录此课程的笔记哦～</h6>
                    </div>
                </div>
                <div v-show="isEdit">
                    <p style="margin-top:37px">
                        <span style="font-size: 14px;color: #333333;margin-left:10px;">{{mynoteData.sysCreateTime}}</span>
                        <span class="sm">{{mynoteData.openType == 9?'公开':'私密'}}</span>
                        <svg-icon style="float:right;font-size:26px;margin-top:16px" icon-class="spot"></svg-icon>
                    </p>
                    <div class="newcote-content" style="margin-top:10px;min-height:236px;height: 100%;">
                        <div class="newcote-time" v-if="mynoteData.playTime != 0">
                            <img :src="`${webBaseUrl}/images/coteplay.png`" />
                            {{formatSeconds(mynoteData.playTime)}}
                            <img :src="`${webBaseUrl}/images/cotedetel.png`" @click="timeDel()" />
                        </div>
                        <div class="newcote-text">
                            <el-input type="textarea" :autofocus="true" placeholder="好记性不如烂笔头，记录些什么吧～"
                                v-model="mynoteData.content" maxlength="200" :autosize="{ minRows: 18, maxRows: 20}"
                                show-word-limit>
                            </el-input>
                        </div>
                    </div>
                </div>
            </div>
            <div class="newcote-bottom" v-if="notetab == 1 || isEdit">
                <span v-if="btnPlayTime" style="cursor: pointer;" @click="videoLocation"> <img :src="`${webBaseUrl}/images/playtime.png`"
                        alt=""> 视频位置</span>
                <el-radio v-if="mynoteData.openType == 9" v-model="editRadio" :label="9">公开</el-radio>
                <el-radio v-model="editRadio" :label="1">私密</el-radio>
                <el-button size="small" v-if="notetab != 1" v-show="isEdit" @click="editCancel()">取消</el-button>
                <el-button type="primary" size="small" @click="saveNote()">保存</el-button>
            </div>
        </div>
        <div class="animation-box" :class="inAnimation?'animation':''" @animationend="inAnimation=false">
            <div class="box-text">
                <img :src="`${webBaseUrl}/images/success-note.png`" />{{inAnimationText}}
            </div>
        </div>
    </div>
</template>
<script>
import apiNote from '@/api/phase2/note.js';
import { mapGetters } from 'vuex';
import { formatDate, formatSeconds } from '@/utils/datetime.js';
import { testType, correctJudgment, numberToLetter } from '@/utils/tools.js';
export default {
    props: {
        data: {
          type: Object,
          default: () => { }
        },
        height:{
          type: Number,
          default: 200
        },
        score: {
            type:Number,
            default:0
        }
    },
    name: 'MyNote',
    data() {
        return {
            inAnimationText:'笔记保存成功，U币+2',
            isEdit:false,
            inputHeight:70,
            listHeight:170,
            inputRows:2,
            courseId:'',
            inAnimation: false,
            btnPlayTime:false,//是否显示添加视频时间
            radio: '1',
            notetab: 1,
            autoSave: null,
            mynoteData: {
                type: 1, //我发布的是1 我导入的是2
                content: '',
                playTime: 0,
                courseId: '',// 课程id
                contentId: '',//课程内容id
                courseName: '',// 课程名称
                openType: 9,// 1表不公开 9表完全公开
            },
            content_new: '',
            editRadio: 9 , // 单选按钮（笔记公开状态）状态值 ： 1- 私密 9-公开
            noteList: [],
            type: 1, // 1自动保存 2点击保存
        };
    },
    computed: {
        ...mapGetters(['intTimeNote', 'userInfo']),
    },
    mounted() {
        // console.log(this.$route,'route');
        // console.log(this.data,'data111');
        this.courseId = this.$route.query.id;
        this.getMyNote();

    },
    watch: {
        //内容的高度
        height(val){

          //$this.controlHeight=h-
            this.listHeight=val-95;
            this.inputHeight=(val-220);

            this.inputRows=parseInt(this.inputHeight/30);
            if(this.inputRows>20){
              this.inputRows=20;
            }

            //console.log(this.inputHeight,this.inputRows,this.listHeight,'my note height');

            if(this.inputHeight>500){
              this.inputHeight=500;
            }
        },
        selected:{
          handler(val,old){
            this.$emit('change',this.selected)
          },
          deep:true
        },
        data(val){
           if(val.id) {
            console.log(val,'val');
            this.mynoteData.courseId = this.courseId;
            this.mynoteData.courseName = this.data.name;
            // this.mynoteData.contentId = this.data.id;
           }
        },
        // intTimeNote(val) {
        //     this.mynoteData.playTime = val;
        // }
    },
    methods: {
        handleClick(){
          this.$emit('change',this.selected)
        },
        onPlayVideo(conId,time) {
            //这里应该加上内容的id
            this.$emit('onPlayVideo',conId,time);
        },

        // 取消编辑
        editCancel(){
          this.isEdit = false; // 关闭编辑框
          this.getMyNote(); // 重新渲染对应课程的笔记列表
        },
        formatSeconds(value) {
            let result = parseInt(value)
            let h = Math.floor(result / 3600);
            let m = Math.floor((result / 60 % 60));
            let s = Math.floor((result % 60));

            let res = '';
            if (h > 0) {
                res += `${h}:${m}:${s}`;
            } else {
                res += `${m}:${s}`;
            }
            return res;
        },
        showVideoTimeBtn(showOrHidden){
          this.btnPlayTime=showOrHidden;
        },
        //设置音视频的时间,引用页面调用
        setVideoTime(contentId,time){
            this.mynoteData.contentId=contentId;//内容id
            this.mynoteData.playTime=time;//秒
        },
        timeDel() {
            this.mynoteData.playTime = 0;
        },
        autoSaveNote() {
            this.autoSave = setInterval(() => {
                localStorage.setItem("NOTE_TEXT", this.mynoteData.content);
            }, 10000);
        },
        noteEdit(note) {
            console.log(note,'note');
            this.isEdit = true;
            this.mynoteData = note;
            this.editRadio = this.mynoteData.openType; // 设置默认的单选按钮选中状态
            // this.notetabType(1);
        },
        noteDel(note) {
            this.$confirm('您确定要删除这条笔记吗？', '删除提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                apiNote.del(note.id).then(res => {
                    if (res.status == 200) {
                      //删除事件
                      let event = {
                        key: "DeleteNote",//
                        title: "删除笔记",//
                        parameters:"author",//
                        content: "删除了笔记",//
                        source:'page',
                        objId: note.id,//关联的id
                        objType: "6",//关联的类型
                        objInfo: "",
                        aid: this.userInfo.aid, //当前登录人的id
                        aname: this.userInfo.name,//当前人的姓名
                        status: 1 //状态，直接写1
                      }
                      this.$store.dispatch("userTrigger", event);
                      this.getMyNote();
                    } else {
                        this.$message({ type: 'error', message: res.message, offset: 50 });
                    }
                })
            }).catch((err) => {
                    this.$message({ type: 'info', message: '已取消删除', offset: 50 });
                });

        },
        getMyNote() {
            apiNote.myCourse(this.courseId).then(res => {
                if (res.status == 200) {
                    this.noteList = res.result;
                }
            })
        },
        videoLocation() {
            this.$emit('videoLocation');
        },
        notetabType(num) {
            this.notetab = num;
            if(num == 1) {
              this.content_new = '';  // 清空内容
              this.btnPlayTime=true; // 显示添加视频时间
            }
        },
        saveNote() {
            let that = this;
            if (this.content_new == '') {
                this.$message({ type: 'info', message: '您还没有书写笔记！', offset: 50 });
                return;
            }
            this.mynoteData.courseId = this.courseId;
            this.mynoteData.courseName = this.data.name;
            this.mynoteData.openType = this.editRadio;
            if(this.isEdit) {
                if (this.mynoteData.content == '') {
                    this.$message({ type: 'info', message: '您还没有书写笔记！', offset: 50 });
                    return;
                }
                apiNote.update(this.mynoteData).then(res=>{
                   if(res.status == 200) {
                    this.inAnimationText = '笔记编辑成功';
                    this.inAnimation = true;
                    this.isEdit = false;
                    this.editRadio = 9; // 重置默认笔记公开状态
                    setTimeout(() => {
                        that.getMyNote();
                        that.mynoteData = {
                            type: 1, //我发布的是1 我导入的是2
                            content: '',
                            playTime: '',
                            // courseId: '',// 课程id
                            // contentId: '',//课程内容id
                            // courseName: '',// 课程名称
                            openType: 9,// 1表不公开 9表完全公开
                        };
                    }, 2000)
                   }
                })
            } else {
                this.mynoteData.content = this.content_new; //赋值笔记内容
                let curOpenType=this.mynoteData.openType;
                apiNote.save(this.mynoteData).then(res => {
                if (res.status == 200) {
                    if (!this.mynoteData.id) {
                        this.inAnimationText = '笔记保存成功，U币+5';
                        this.inAnimation = true;
                        this.editRadio = 9; //重置默认笔记公开状态
                        this.mynoteData.openType = 9;
                        if(this.mynoteData.openType != 9){
                           return
                        }
                    setTimeout(() => {
                        localStorage.setItem("NOTE_TEXT", '');
                        // clearInterval(this.autoSave);
                        that.getMyNote();
                        that.notetabType(2);
                        that.mynoteData = {
                            type: 1, //我发布的是1 我导入的是2
                            content: '',
                            playTime: '',
                            // courseId: '',// 课程id
                            // contentId: '',//课程内容id
                            // courseName: '',// 课程名称
                            openType: 9,// 1表不公开 9表完全公开
                        };

                    }, 2000)
                        // 是编辑新增
                        let event = {
                            key: "PublishNote",//后台的事件key
                            title: '发布了笔记',//事件的标题
                            parameters: "openType:"+curOpenType,//用户自定义参数 name:value,name:value
                            content: "编辑了笔记",//this.mynoteData.content,//事件的内容
                            objId: res.result.id,//关联的id
                            objType: "6",//关联的类型
                            objInfo: this.data.name +''+ this.score,
                            aid: this.userInfo.aid, //当前登录人的id
                            aname: this.userInfo.name,//当前人的姓名
                            status: 1 //状态，直接写1
                        }
                        this.$store.dispatch("userTrigger", event);
                    }

                }
            })
            }
        }
    },
    beforeDestroy() {
        //    clearInterval(this.autoSave);
        this.autoSave = null;
    },
}
</script>

<style scoped lang="scss">
::v-deep .el-dropdown-menu__item:hover {
    background: #333333;
}

.mynote {
    // width: 100%;
    margin: 35px 30px;
    position: relative;

    .animation {
        display: block !important;
        animation-name: ubAddBlock;
        animation-duration: 2s;
        animation-fill-mode: forwards;
    }

    .animation-box {
        display: none;
        position: absolute;
        bottom: 0;
        right: 200px;
        .box-text {
            padding: 12px 16px;
            width: 252px;
            height: 40px;
            background: #FFFFFF;
            box-shadow: 0px 8px 20px 0px rgba(0, 35, 114, 0.1);
            border-radius: 2px;
            font-size: 14px;
            color: rgba(0, 0, 0, 0.65);

            img {
                width: 16px;
                height: 16px;
                vertical-align: middle;
                margin-right: 22px;
            }
        }
    }

    .newcote-time {
        width: 80px;
        height: 30px;
        border-radius: 4px;
        border: 1px solid #3379FB;
        font-size: 14px;
        color: #387DF7;
        ;
        text-align: center;
        line-height: 28px;
        margin-bottom: 12px;

        img {
            vertical-align: middle;
            margin: 0 5px;

        }
    }

    .newcote-bottom {
        span {
            font-size: 14px;
            color: #333333;
            margin-right: 30px;

            img {
                width: 20px;
                height: 24px;
                vertical-align: middle;
            }
        }
    }

    .newcote-text {
        //    margin-top: 24px;
        font-size: 14px;
        color: #333333;
        height: 100%;
        white-space: pre-line;

        ::v-deep .el-textarea__inner {
            background: #f5f5f5;
            border: none;
            padding: 0;
        }
    }
    .sm {
      width: 50px;
      height: 22px;
      border-radius: 10px;
      border: 1px solid #3379FB;
      color: #3379FB;
      font-size: 12px;
      line-height: 50px;
      margin-left: 20px;
      padding: 3px 10px;
    }
    .newcote-content {
        margin: 30px 0px;
        box-sizing: border-box;
        padding: 35px 30px;
        height: 100%;
        background-color: #F5F5F5;
    }

    .mycote-content {
        margin: 30px 0px;
        box-sizing: border-box;
        padding: 8px 30px;
        min-height: 200px;
        overflow-y: auto;
        background-color: #fff;

        .my-nonote {
            text-align: center;
            margin-top: 100px;

            img {
                width: 198px;
                height: 163px;
            }
        }

        .mycote-time {
            color: #666;
            font-size: 14px;
            padding-bottom: 20px;



            .more {
                margin-top: 12px;
                float: right;
            }
        }

        .mycote-dibu {
            margin: 50px 50px;
            text-align: center;
            color: #999999;
            font-size: 14px;
        }
    }

    .mynote-tab {
        width: 180px;
        margin-top: 17px;

        display: flex;

        div {
            font-size: 16px;
            color: #666666;
            flex: 1;
        }

        .noteactive span {
            font-weight: 600;
            color: #333333;
            padding-bottom: 7px;
            border-bottom: 4px solid #387DF7;
        }
    }

}
</style>
