<template>
    <div>
        <van-nav-bar :title="title" left-text="返回" @click-left="back" fixed left-arrow />
        <div class="content">
            <van-form>
                <!-- 类型 -->
                <van-field v-model="taskform.taskType" label="类型" @click="taskType.show = true" readonly clickable>
                    <template #input><span>{{taskType.list[taskform.taskType]}}</span></template>
                </van-field>
                <van-popup v-model="taskType.show" position="bottom" v-if="canEdit">
                    <van-picker
                    show-toolbar
                    :columns="taskType.list"
                    @confirm="tasktypeChange"
                    @cancel="taskType.show = false;$forceUpdate();"/>
                </van-popup>
                <!-- 任务内容 -->
                <van-field v-model="taskform.name" label="任务内容" placeholder="请输入任务内容" :rules="[{ required: true, message: '请输入任务内容' }]" type="textarea" :disabled="!canEdit"></van-field>
                <!-- 开始时间 -->
                <van-field v-if="taskform.type != 1" v-model="taskform.startDate" label="开始时间" placeholder="请选择开始时间" @click="startDateShow = true" readonly clickable></van-field>
                <van-popup v-model="startDateShow" position="bottom" v-if="canEdit">
                    <van-datetime-picker
                    type="date"
                    title="选择开始时间"
                    @confirm="startDateChange"
                    @cancel="startDateShow = false;$forceUpdate();"
                    :min-date="new Date(2010,0,1)"
                    :max-date="taskform.endDate ? new Date(taskform.endDate) : new Date(2030,11,31)"/>
                </van-popup>
                <!-- 截止时间 -->
                <van-field v-model="taskform.endDate" label="截止时间" placeholder="请选择截止时间" @click="endDateShow = true" readonly clickable></van-field>
                <van-popup v-model="endDateShow" position="bottom" v-if="canEdit">
                    <van-datetime-picker
                    type="date"
                    title="选择截止时间"
                    @confirm="endDateChange"
                    @cancel="endDateShow = false;$forceUpdate();"
                    :min-date="taskform.startDate ? new Date(taskform.startDate) : new Date(2010,0,1)"
                    :max-date="new Date(2030,11,31)"/>
                </van-popup>
                <!-- 完成时间 -->
                <van-field v-if="taskform.type == 1" v-model="taskform.finishDate" label="完成时间" placeholder="请选择完成时间" @click="finishDateShow = true" readonly clickable></van-field>
                <van-popup v-model="finishDateShow" position="bottom" v-if="canEdit">
                    <van-datetime-picker
                    type="date"
                    title="选择完成时间"
                    @confirm="finishDateChange"
                    @cancel="finishDateShow = false;$forceUpdate();"
                    :min-date="new Date(2010,0,1)"
                    :max-date="new Date(2030,11,31)"/>
                </van-popup>
                <!-- 执行人 -->
                <div style="border: 0.5px solid #87c3ff;margin:0.2rem;position:relative" v-for="item,index in taskform.executorList" :key="index">
                    <van-field v-model="item.executorName" :label="'执行人' + (index + 1)" placeholder="请选择执行人" @click="executorChange(item,index)" readonly clickable>
                        <template #input>
                            <span v-if="!item.executorName"></span>
                            <span v-else-if="user.userNameNeedTranslate != 1">{{item.executorName}}</span>
                            <span v-else><ww-open-data type='userName' :openid='item.executorName'></ww-open-data></span>
                        </template>
                    </van-field>
                    
                    <van-field label="计划工时">
                        <template #input>
                            <van-stepper v-model="item.planHours" :disabled="!canEdit"/><span>{{'\u3000h'}}</span>
                        </template>
                    </van-field>
                    <van-icon v-if="index != 0" class="delete_executor" name="delete-o" @click.stop="deleteExecutor(index)" />
                </div>
                <van-popup v-model="executor.show" position="bottom" v-if="canEdit">
                    <van-search v-model="executor.searchText" placeholder="输入员工姓名搜索" @search="onSearch" v-if="user.userNameNeedTranslate != '1'"></van-search>
                    <div style="minHeight:300px;">
                        <van-radio-group v-model="executor.item">
                            <van-radio v-for="uitem in executor.searchList" :key="uitem.id" :name="uitem" style="padding:10px">
                                <span>{{uitem.name}}</span>
                                <span v-if="user.userNameNeedTranslate != 1">{{uitem.name}}</span>
                                <span v-else><ww-open-data type='userName' :openid='uitem.name'></ww-open-data></span>
                            </van-radio>
                        </van-radio-group>
                    <van-button style="width:100%;position: -webkit-sticky;position: sticky;bottom: 0;" @click="searchExecutor()">确定</van-button>
                    </div>
                </van-popup>
                <!-- 添加执行人 -->
                <div class="add_executor" @click="addExecutor" v-if="canEdit">添加执行人</div>
                <!-- 优先级 -->
                <van-field v-model="taskform.taskLevel" label="优先级" @click="taskLevel.show = true" readonly clickable>
                    <template #input><span>{{taskLevel.list[taskform.taskLevel]}}</span></template>
                </van-field>
                <van-popup v-model="taskLevel.show" position="bottom" v-if="canEdit">
                    <van-picker
                    show-toolbar
                    :columns="taskLevel.list"
                    @confirm="taskLevelChange"
                    @cancel="taskLevel.show = false;$forceUpdate();"/>
                </van-popup>

            </van-form>
            <div class="form_btn" style="position:fixed; bottom:0px;width:100%;">
                <div style="padding-bottom:10px;">
                    <van-button square block type="info" @click="submitTask" native-type="submit" style="width:100%;float:left;" :disabled="!canEdit">
                        <div v-if="canEdit">保存</div>
                        <div v-else>暂无权限编辑</div>
                    </van-button>
                </div>
            </div>
                    
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return {
            title: '编辑任务',
            user: JSON.parse(localStorage.userInfo),
            taskId: JSON.parse(sessionStorage.taskId),
            canEdit: true,
            taskform:{      // 表单
                taskType: 0,
                name: '',
                startDate: null,
                endDate: null,
                finishDate: null,
                taskLevel: 0,
                executorList: [{executorName: '',executorId: '',planHours: 8}],

            },
            taskType:{
                show: false,
                list: ['任务','里程碑','风险']
            },
            startDateShow: false,
            endDateShow: false,
            finishDateShow: false,
            taskLevel:{
                show: false,
                list: ['一般','重要','紧急']
            },
            executor:{
                show: false,
                item: {id:null,name:''},
                index: 0,
                list: [],
                searchList: [],
                searchText: ''
            }

        }
    },
    mounted() {
        if(!this.taskId.addNew){
            this.title = '编辑任务'
            this.getTask()
        }else{
            this.title = '新建任务'
            this.taskform = {
                projectId: JSON.parse(sessionStorage.projectId),
                groupId: this.taskId.groupId,
                stagesId: this.taskId.stagesId,
                taskType: 0,
                name: '',
                startDate: null,
                endDate: null,
                finishDate: null,
                taskLevel: 0,
                executorList: [{executorName: '',executorId: '',planHours: this.user.timeType.allday}]
            }
        }
        this.getUsersList()
        console.log('mounted',this.taskId,null);
    },
    methods: {
        back() {
            history.back();
        },
        formatDate(date) {
            let mon = date.getMonth() + 1
            return `${date.getFullYear()}-${mon<10?'0'+mon:mon}-${date.getDate()<10?'0'+date.getDate():date.getDate()}`;
        },


        tasktypeChange(value,key){      // 类型
            this.taskform.taskType = key
            this.taskType.show = false
        },
        startDateChange(date){          // 开始时间
            this.taskform.startDate = this.formatDate(date)
            this.startDateShow = false
        },
        endDateChange(date){            // 截止时间
            this.taskform.endDate = this.formatDate(date)
            this.endDateShow = false
        },
        finishDateChange(date){         // 完成时间
            this.taskform.finishDate = this.formatDate(date)
            this.finishDateShow = false
        },
        
        executorChange(item,index){           // 选择执行人
            this.executor.show = true
            this.executor.index = index
            this.executor.searchList.forEach(u=>{if (u.id == item.executorId) {
                this.executor.item = u
            }})
        },
        deleteExecutor(index){
            console.log('deleteExecutor');
            this.taskform.executorList.splice(index,1)
            this.$forceUpdate();
        },
        addExecutor(){
            console.log('addExecutor');
            this.taskform.executorList.push({
                executorName: '',
                executorId: '',
                planHours: this.user.timeType.allday
            })
            this.$forceUpdate();
        },
        onSearch(val) {
            console.log(val);
            this.executor.searchList = [];
            this.executor.list.forEach(u=>{if (u.name.startsWith(val)) {
                this.executor.searchList.push(u);
            }})
        },
        searchExecutor(){
            this.taskform.executorList[this.executor.index].executorId = this.executor.item.id
            this.taskform.executorList[this.executor.index].executorName = this.executor.item.name
            this.executor.show = false
            console.log('searchExecutor',this.executor.item,this.executor.item.name);
        },

        taskLevelChange(value,key){     // 优先级
            this.taskform.taskLevel = key
            this.taskLevel.show = false
        },

        submitTask(){
            console.log('submitTask');
            if(!this.taskform.name.replace(/^\s*|\s*$/g,"")){
                return
            }
            
            // 执行人查重
            let arr = this.taskform.executorList
            let json={};
            for(let i in arr){
                if(!json[arr[i].executorId]){
                    json[arr[i].executorId]=1;
                }else{
                    this.$toast.fail("执行人存在重复");
                    return
                }
            }

            // 去除未选择执行人的执行人列表
            this.taskform.executorList = this.taskform.executorList.filter(item => item.executorId)
            this.taskform.executorListStr = JSON.stringify(this.taskform.executorList)
            
            delete this.taskform.executorList
            delete this.taskform.subTaskList;
            delete this.taskform.refTaskList;
            delete this.taskform.progress;
            this.$axios.post("/task/save", this.taskform)
            .then(res => {
                if(res.code == "ok") {
                    this.$toast.success('保存成功');
                    this.back()
                } else {
                    this.$toast.fail('保存失败');
                }
            }).catch(err=> {this.$toast.clear();console.log(err)});

        },

        getTask(){
            this.$axios.post("/task/getTask", {
                id: this.taskId.id
            }).then(res => {
                if(res.code == "ok") {
                    this.taskform = res.data
                    this.taskform.createDate = null;
                    this.taskform.indate = null;
                    let projectManagement = false

                    // 判断编辑权限
                    for(let i in this.user.functionList){
                        if(this.user.functionList[i].name == '查看全部项目'){
                            projectManagement = true
                        }
                    }
                    if(this.user.id == res.data.createrId || this.user.id == res.data.projectInchargerId || this.user.id == res.data.groupInchargerId || projectManagement || this.title == '新建任务'){
                        this.canEdit = true
                    }else{
                        this.canEdit = false
                    }


                    // (
                    //     (
                    //         (addForm.executorListFront == null || addForm.executorListFront.length<10) 
                    //         && (
                    //             addForm.id == null|| user.id == addForm.createrId || currentProject.inchargerId == user.id || permissions.projectManagement
                    //         )
                    //     ) 
                    //     || groupResponsibleId == user.id
                    // )



                    // this.canEdit = false
                } else {
                    this.$toast.fail('获取失败');
                }
            }).catch(err=> {this.$toast.clear();console.log(err)});
        },
        getUsersList(){
            this.$axios.post("/user/getSimpleActiveUserList", {})
            .then(res => {
                if(res.code == "ok") {
                    this.executor.list = res.data
                    this.executor.searchList = res.data
                } else {
                    this.$toast.fail('获取失败');
                }
            }).catch(err=> {this.$toast.clear();console.log(err)});
        }
    },
}
</script>

<style lang="less" scoped>
.content{
    margin-top: 46px;
    overflow: auto;
    .add_executor{
        font-size:13px;
        color:#1989fa;
        padding-left:0.42667rem;
        padding-bottom:.2rem;
        width:100px
    }
    .delete_executor{
        position: absolute;
        top: 3px;
        right: 3px;
        font-size: 22px;
        color: #c03131;
    }
}
</style>