<template>
    <div>
        <div class="AssignTasks-all">
            <div class="AssignTasks-title">新建任务</div>
            <div class="AssignTasks-form">
                <el-form :model="taskform" :rules="rulestaskform" ref="taskform" label-width="80px"
                    class="demo-ruleForm">
                    <div class="AssignTasks-form-first">
                        <el-form-item label="所属部门" prop="department">
                            <el-select :disabled="true" size="medium" filterable v-model="taskform.department"
                                placeholder="请选择">
                                <el-option v-for="item in departmentNameInfos" :key="item.id" :label="item.name"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="任务名称" prop="taskname">
                            <el-input size="medium" v-model="taskform.taskname" placeholder="请输入内容"></el-input>
                        </el-form-item>
                        <el-form-item label="优先级" prop="value">
                            <el-select size="medium" filterable v-model="taskform.value" placeholder="请选择">
                                <el-option v-for="item in options" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="所属团组" prop="Thegroup">
                            <el-select size="medium" filterable v-model="taskform.Thegroup" placeholder="请选择">
                                <el-option v-for="item in groupNameInfos" :key="item.id" :label="item.name"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="类型" prop="type">
                            <el-select size="medium" v-model="taskform.type" clearable placeholder="请选择">
                                <el-option v-for="item in typearr" :key="item.id" :label="item.name" :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <!-- <el-form-item label="预计" prop="name">
                            <el-input size="medium" v-model="value" placeholder="请输入内容"></el-input>
                        </el-form-item> -->
                    </div>
                    <el-form-item label="指派给" prop="staff">
                        <el-select size="medium" style="width: 100%;" v-model="taskform.staff" multiple filterable
                            allow-create default-first-option @change="selectchg" placeholder="请选择人员">
                            <el-option v-for="item in executeTaskUserInfos" :key="item.id" :label="item.name"
                                :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <div class="quill-box">
                        <label class="quill-title">任务描述</label>
                        <quill-editor class="editor" ref="myTextEditor" v-model="content" :options="editorOption"
                            @blur="onEditorBlur($event)" @focus="onEditorFocus($event)" @ready="onEditorReady($event)"
                            @change="onEditorChange($event)">
                            <button id="custom-button">defineAsyncComponent</button>
                        </quill-editor>
                    </div>
                    <div style="display: flex;">
                        <el-form-item label="日程规则" prop="schedulerules">
                            <el-date-picker @change="riqi" v-model="taskform.schedulerules" type="datetimerange"
                                range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
                            </el-date-picker>
                            <!-- <el-date-picker
                            @change="riqi"
                            v-model="taskform.schedulerules"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期">
                            </el-date-picker> -->
                        </el-form-item>
                        <!-- <el-form-item>
                            <el-switch
                            v-model="taskform.kpi"
                            active-text="纳入绩效考核"
                            inactive-text="不纳入绩效考核">
                            </el-switch>
                        </el-form-item> -->
                    </div>
                </el-form>
                <div class="AssignTasks-btn">
                    <el-button size="medium" @click="submitForm('taskform')" type="primary">确定</el-button>
                    <el-button size="medium" @click="goback">取消</el-button>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
export default {
    beforeRouteLeave(to, from, next) {
        console.log(to);
        console.log(from);
        if(to.name=='TaskList'){
            to.meta.keepAlive = true;
        }
        next()
    },
    data () {
        return {
            id:0,
            token:'',
            pageId:'',
            userId:'',
            departmentNameInfos:[],
            executeTaskUserInfos:[],
            groupNameInfos:[],
            taskform:{
                department:'',
                Thegroup:'',
                value:2,
                taskname:'',
                schedulerules:[],
                staff:[],
                type:'',
                kpi:true,
            },
            typearr:[],
            rulestaskform:{
                department: [
                    { required: true, message: '请选择所属部门', trigger: ['change','blur'] }
                ],
                taskname: [
                    { required: true, message: '请填写任务名称', trigger: ['change','blur'] }
                ],
                value: [
                    { required: true, message: '请选择优先级', trigger: ['change','blur'] }
                ],
                type: [
                    { required: true, message: '请选择类型', trigger: ['change','blur'] }
                ],
                Thegroup: [
                    { required: true, message: '请选择所属团组', trigger: ['change','blur']}
                ],
                staff: [
                    { required: true, message: '请选择人员', trigger: ['change','blur'] }
                ],
                schedulerules: [
                    { required: true, message: '请选择日程规则', trigger: ['change','blur'] }
                ],
            },
            options: [
                {
                value: 1,
                label: '1级'
                }, 
                {
                value: 2,
                label: '2级'
                }, 
                {
                value: 3,
                label: '3级'
                }, 
                {
                value: 4,
                label: '4级'
                }
            ],
            //富文本
            content: '',
            contents:'',
            editorOption: {
                modules: {
                toolbar: [
                    ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线
                    ["blockquote", "code-block"], // 引用  代码块
                    [{ header: 1 }, { header: 2 }], // 1、2 级标题
                    [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表
                    [{ script: "sub" }, { script: "super" }], // 上标/下标
                    [{ indent: "-1" }, { indent: "+1" }], // 缩进
                    // [{'direction': 'rtl'}],                         // 文本方向
                    [{ size: ["small", false, "large", "huge"] }], // 字体大小
                    [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
                    [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
                    [{ font: [] }], // 字体种类
                    [{ align: [] }], // 对齐方式
                    ["clean"], // 清除文本格式
                    ["link", "image", "video"], // 链接、图片、视频
                    ["sourceEditor"]
                ], //工具菜单栏配置
                },
                placeholder: '请在这里添加产品描述', //提示
                readyOnly: false, //是否只读
                theme: 'snow', //主题 snow/bubble
                syntax: true, //语法检测
            }
        }
    },
    methods: {
        // 失去焦点
        onEditorBlur(editor) {
            // this.content=this.contents
            // this.$refs.myTextEditor.quill.enable(false);
            // setTimeout(()=>{
            //     this.$refs.myTextEditor.quill.enable(true);
            // },1000)
        },
        // 获得焦点
        onEditorFocus(editor) {},
        // 开始
        onEditorReady(editor) {},
        // 值发生变化
        onEditorChange(editor) {
            console.log(editor);
            this.contents = editor.text;
        },
        riqi(){
           console.log(this.datetime(this.taskform.schedulerules[0]));
        },
        selectchg(){
            
        },
        //获取详情
        PostTaskAllocationDetails(){
            console.log(this.id)
            if(this.id==undefined||this.id==NaN){
                return false
            }else{
                var url = "/api/PersonnelModule/PostTaskAllocationDetails"
                var that = this
                this.$axios({
                    method: 'post',
                    url: url,
                    headers: {
                        Authorization: 'Bearer ' + that.userId
                    },
                    data:{
                        portType:1,
                        userId: 5,
                        pageId: that.pageId,
                        id: that.id,
                    }
                }).then(function (res) {
                    console.log(res)
                    if(res.data.code==200){
                        that.taskform.department=res.data.data.depId;
                        that.taskform.taskname=res.data.data.taskName;
                        that.taskform.value=res.data.data.taskPriority;
                        that.taskform.type=res.data.data.taskType;
                        that.taskform.Thegroup=res.data.data.diId;
                        for(var i=0;i<res.data.data.userTaskInfos.length;i++){
                            that.taskform.staff.push(res.data.data.userTaskInfos[i].userId);
                        }
                        that.content=res.data.data.taskContent;
                        that.taskform.schedulerules=[res.data.data.predictBeginTime,res.data.data.predictEndTime];
                        that.taskform.kpi=res.data.data.isIntoPerformance==1?true:false;
                        
                    }else{
                        that.$message.error(res.data.msg);
                    }
                }).catch(function (error) {
                    that.$message.error("获取详情失败");
                });
            }
        },
        //基础数据原
        PostTaskAllocationInit(){
            var url = "/api/PersonnelModule/PostTaskAllocationInit"
            var that = this
            this.$axios({
                method: 'post',
                url: url,
                headers: {
                    Authorization: 'Bearer ' + that.userId
                },
                data:{
                    portType:1,
                    userId: that.userId
                }
            }).then(function (res) {
                if(res.data.code==200){
                    that.executeTaskUserInfos=[];
                    that.typearr=[];
                    that.groupNameInfos=[];
                    that.departmentNameInfos.push(res.data.data.departmentNameInfo);
                    that.executeTaskUserInfos=res.data.data.executeTaskUserInfos;
                    that.groupNameInfos=res.data.data.groupNameInfos;
                    that.typearr=res.data.data.taskTypeInfos;
                    that.taskform.Thegroup=that.groupNameInfos[0].id;
                    that.taskform.department=that.departmentNameInfos[0].id;
                    that.taskform.type=that.typearr[0].id;
                    that.PostTaskAllocationDetails()
                }else{
                    that.$message.error(res.data.msg);
                }
            }).catch(function (error) {
                that.$message.error("获取数据源失败！");
            });
        },
        //确定
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.PostTaskAllocationAddOrEdit()
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        //返回上一页
        goback(){
            this.$router.go(-1);
        },
        //处理日期
        datetime(val){
            var date=new Date(val);
            var y=date.getFullYear();
            var m=date.getMonth()+1>=10?date.getMonth()+1:'0'+(date.getMonth()+1).toString();
            var d=date.getDate()>=10?date.getDate():'0'+(date.getDate()).toString();
            var s=date.getHours()>=10?date.getHours():'0'+(date.getHours()).toString();
            var f=date.getMinutes()>=10?date.getMinutes():'0'+(date.getMinutes()).toString();
            var mm=date.getSeconds()>=10?date.getSeconds():'0'+(date.getSeconds()).toString();
            return y+'-'+m+'-'+d+" "+s+':'+f+':'+mm
        },
        //转换日期
        transferdate(val){
            var today = new Date(val);
            var DD = String(today.getDate()).padStart(2, '0'); // 获取日
            var MM = String(today.getMonth() + 1).padStart(2, '0'); //获取月份，1 月为 0
            var yyyy = today.getFullYear(); // 获取年
            var Hours=today.getHours()<10 ? '0'+today.getHours() : new Date().getHours();;
            var Minutes=today.getMinutes()<10 ? '0'+today.getMinutes() : new Date().getMinutes();
            var Seconds=today.getSeconds()<10 ? '0'+today.getSeconds() : new Date().getSeconds();
            return yyyy+'-'+MM+'-'+DD+' '+Hours+':'+Minutes+':'+Seconds
        },
        //新增api
        PostTaskAllocationAddOrEdit(){
            var id=this.id;
            if(id==undefined){
                id=0
            }else{
                id=this.id;
            }
            var url = "/api/PersonnelModule/PostTaskAllocationAddOrEdit"
            var that = this
            console.log(that.contents);
            this.$axios({
                method: 'post',
                url: url,
                headers: {
                    Authorization: 'Bearer ' + that.userId
                },
                data:{
                    portType:1,
                    userId: that.userId,
                    pageId: that.pageId,
                    id: id,
                    depId: that.taskform.department,
                    diId: that.taskform.Thegroup,
                    taskType: that.taskform.type,
                    taskPriority:that.taskform.value,
                    taskName:that.taskform.taskname,
                    taskContent: that.contents,
                    userIds: that.taskform.staff,
                    predictBeginTime: that.datetime(that.taskform.schedulerules[0]),
                    predictEndTime: that.datetime(that.taskform.schedulerules[1]),
                    isIntoPerformance: that.taskform.staff?1:0,
                }
            }).then(function (res) {
                console.log(res)
                if(res.data.code==200){
                    that.$message({
                        type: 'success',
                        message: res.data.msg,
                        duration:'3000'
                    });
                    that.goback();
                }else{
                    that.$message.error(res.data.msg);
                }
            }).catch(function (error) {
                that.$message.error("保存失败！请联系信息部！");
            });
        },
    },
    computed: {
        editor() {
            return this.$refs.myTextEditor.quillEditor;
        }
    },
    mounted(){
        
        this.id = this.$route.query.id;
        this.token=JSON.parse(localStorage.getItem('userinif')).token;
        this.pageId=Number(localStorage.getItem('indexs').split('-')[1]);//页面id
        this.userId=JSON.parse(localStorage.getItem('userinif')).userInfo.userId;
        this.PostTaskAllocationInit() 

        
    }
}
</script>
<style>
.AssignTasks-all{
    background-color: #fff;
    padding: 10px;
    box-shadow: 0 0 5px #0005;
    border-radius: 10px;
    height: 100%;
    min-height: 830px;
}
.AssignTasks-title{
    font-size: 17px;
    font-weight: 600;
}
.AssignTasks-form{
    margin-top: 20px;
}
.AssignTasks-form-first{
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
}
.AssignTasks-form-first .el-form-item{
    width: 350px;
}
.AssignTasks-form-first .el-select{
    width: 100%;
}
.AssignTasks-form.el-range-editor.el-input__inner{
    width: 45%;
}
.AssignTasks-btn{
    text-align:right;
    padding-top: 20px;
}

.quill-box{
    display: flex;
    align-items: baseline;
    margin-bottom: 22px;
}
.quill-box .ql-container{
    height: 86%;
}
.quill-title{
    font-size: 14px;
    color: #606266;
    width: 70px;
    text-align: right;
    padding: 0 12px 0 0;
}
.quill-box .editor {
    line-height: normal !important;
    height: 300px;
    width: 96%;
}
.quill-box .ql-snow .ql-tooltip[data-mode=link]::before {
content: "请输入链接地址:";
}
.quill-box .ql-snow .ql-tooltip.ql-editing a.ql-action::after {
    border-right: 0px;
    content: '保存';
    padding-right: 0px;
}

.quill-box .ql-snow .ql-tooltip[data-mode=video]::before {
    content: "请输入视频地址:";
}

.quill-box .ql-snow .ql-picker.ql-size .ql-picker-label::before,
.quill-box .ql-snow .ql-picker.ql-size .ql-picker-item::before {
content: '14px';
}
.quill-box .ql-snow .ql-picker.ql-size .ql-picker-label[data-value=small]::before,
.quill-box .ql-snow .ql-picker.ql-size .ql-picker-item[data-value=small]::before {
content: '10px';
}
.quill-box .ql-snow .ql-picker.ql-size .ql-picker-label[data-value=large]::before,
.quill-box .ql-snow .ql-picker.ql-size .ql-picker-item[data-value=large]::before {
content: '18px';
}
.quill-box .ql-snow .ql-picker.ql-size .ql-picker-label[data-value=huge]::before,
.quill-box .ql-snow .ql-picker.ql-size .ql-picker-item[data-value=huge]::before {
content: '32px';
}

.quill-box .ql-snow .ql-picker.ql-header .ql-picker-label::before,
.quill-box .ql-snow .ql-picker.ql-header .ql-picker-item::before {
content: '文本';
}
.quill-box .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="1"]::before,
.quill-box .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="1"]::before {
content: '标题1';
}
.quill-box .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="2"]::before,
.quill-box .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="2"]::before {
content: '标题2';
}
.quill-box .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="3"]::before,
.quill-box .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="3"]::before {
content: '标题3';
}
.quill-box .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="4"]::before,
.quill-box .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="4"]::before {
content: '标题4';
}
.quill-box .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="5"]::before,
.quill-box .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="5"]::before {
content: '标题5';
}
.quill-box .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="6"]::before,
.quill-box .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="6"]::before {
content: '标题6';
}

.quill-box .ql-snow .ql-picker.ql-font .ql-picker-label::before,
.quill-box .ql-snow .ql-picker.ql-font .ql-picker-item::before {
content: '标准字体';
}
.quill-box .ql-snow .ql-picker.ql-font .ql-picker-label[data-value=serif]::before,
.quill-box .ql-snow .ql-picker.ql-font .ql-picker-item[data-value=serif]::before {
content: '衬线字体';
}
.quill-box .ql-snow .ql-picker.ql-font .ql-picker-label[data-value=monospace]::before,
.quill-box .ql-snow .ql-picker.ql-font .ql-picker-item[data-value=monospace]::before {
content: '等宽字体';
}
</style>