<template>
    <div>
        <van-nav-bar title="填写日报" left-text="返回" @click-left="back" fixed left-arrow/>

        <van-form class="login_form" @submit="register">
            <van-field readonly clickable name="datetimePicker" :value="form.createDate" label="时间选择" placeholder="点击选择时间" 
            @click="showPicker = true" :rules="rules.createDate" />
            <van-popup v-model="showPicker" position="bottom">
                <van-datetime-picker v-model="currentDate" type="date" :min-date="minDate" :max-date="maxDate" @confirm="changeTime" @cancel="showPicker = false"/>
            </van-popup>

            <!-- <van-cell title="待分配时长" :value="report.time + 'h'" size="large"></van-cell> -->

            <div class="form_domains" v-for="(item,index) in form.domains" :key="item.id">
                <van-button v-if="index == 0" @click="addNewPro" class="form_addNew" icon="plus" type="info" size="mini">新增项目</van-button>
                <van-icon v-else class="form_del" name="delete" @click="delPro(index)" />

                <van-cell-group :title="'项目' + (index+1)">
                    <van-field readonly clickable name="projectId" :value="item.projectName" label="投入项目" placeholder="请选择投入项目" @click="clickPicker(index)"
                    :rules="[{ required: true, message: '请选择投入项目' }]"/>
                    <van-popup v-model="showPickerProject" position="bottom">
                        <van-picker show-toolbar :columns="project" value-key="projectName" @confirm="choseProject" @cancel="showPickerProject = false" />
                    </van-popup>

                    <!-- <van-field readonly clickable class="form_input" :value="item.workingTime" name="workingTime" label="工作时长" placeholder="请输入工作时长（单位：小时）"
                    :rules="[{ required: true, message: '请输入工作时长（单位：小时）' }]" @touchstart.native.stop="showNumberKey = true"/>
                    <van-number-keyboard v-model="item.workingTime" :show="showNumberKey" close-button-text="完成" extra-key="." :maxlength="4" @blur="showNumberKey = false" /> -->
                    <!-- 全天上下午模式 -->
                    <van-field v-if="reportTimeType.type < 2" readonly clickable  :value="item.label" label="工作时长" placeholder="请选择工作时长(小时)" @click="clickTimePicker(index)"
                    :rules="[{ required: true, message: '请选择工作时长' }]"/>
                    <van-popup v-model="showPickerTime" position="bottom">
                        <van-picker show-toolbar :columns="timeType"  value-key="label" @confirm="choseTimePick" @cancel="showPickerTime = false" />
                    </van-popup>
                    
                    <!-- 选择数字时间长度模式 -->
                    <van-popup v-model="showPickerHours" position="bottom">
                        <van-picker show-toolbar :columns="timeRange" 
                        :default-index="15"
                        @confirm="choseTimePick" @cancel="showPickerHours = false" />
                    </van-popup>

                    <!-- 时间段选择模式 -->
                    <van-field readonly v-if="reportTimeType.type == 2" clickable name="datetimePicker" :value="item.startTime" label="开始时间" placeholder="点击选择时间" 
                        @click="showStartTime = true" />
                    <van-popup v-model="showStartTime" position="bottom">
                        <van-datetime-picker
                        v-model="startTime"
                        type="time"
                        @confirm="confirmTime(item,0);"
                        @cancel="showStartTime = false"
                        :min-hour="8"
                        :max-hour="23"
                        :filter="filter"
                        />
                    </van-popup>
                    <van-field v-if="reportTimeType.type == 2" readonly clickable name="datetimePicker" :value="item.endTime" label="结束时间" placeholder="点击选择时间" 
                        @click="showEndTime = true" />
                    <van-popup v-model="showEndTime" position="bottom" >
                        <van-datetime-picker
                        v-model="endTime"
                        type="time"
                        :min-hour="8"
                        :max-hour="23"
                        :filter="filter"
                        @confirm="confirmTime(item,1)"
                        @cancel="showEndTime = false"
                        />
                    </van-popup>
                    <van-field class="form_input" 
                    v-model="item.content" name="content" type="textarea" label="工作事项" placeholder="请输入工作事项" 
                    rows="3" autosize  />
                </van-cell-group>
            </div>
            <div class="form_btn" style="margin: 16px;">
                <van-button v-if="canEdit" round block type="info" native-type="submit"> 提交 </van-button>
                <van-button v-else round block type="info" disabled native-type="submit"> 提交 </van-button>
            </div>
        </van-form>
        <div style="padding:15px;">
            <van-button  v-if="canCancel" round block type="default" @click="cancel"> 撤销 </van-button>
        </div>
        
        <div class="form_tip" v-if="!canEdit"> 当前日报无法修改 </div> 
    </div>
</template>

<script>
    export default {
        data() {
            return {
                canCancel:false,
                canEdit:false,
                showEndTime: false,
                showStartTime: false,
                startTime:'09:00',
                endTime: '18:00',
                nowTime:new Date(),
                showPickerHours: false,
                timeRange:[0.5,1.0,1.5,2.0,2.5,3.0,3.5,4.0,4.5,5.0,5.5,6.0,6.5,7.0,7.5,8.0,8.5,9.0,9.5,10.0,10.5,11.0,11.5,12.5,13.0,13.5,14.0,14.5,15.0],
                selectTime:null,
                reportTimeType:{},
                user: JSON.parse(localStorage.userInfo),
                minDate: new Date(2010, 0, 1),
                maxDate: new Date(new Date().getFullYear(),new Date().getMonth(),new Date().getDate()),
                currentDate: new Date(),
                showPickerTime: false,
                showPicker: false,
                showPickerProject: false,
                clickIndex: 0,
                clickTimeIndex: 0,
                showNumberKey: false,
                canClick: 2,
                timeType:[],
                form: {
                    createDate: this.format(new Date(new Date()),"yyyy-MM-dd"),
                    domains: [{
                        id: null,
                        projectId: "",
                        projectName: "",
                        workingTime: "",
                        content: "",
                        state: 2,
                    }],
                },
                rules: {
                    createDate: [{ required: true, message: '请选择填报日期' }],
                },
                project: [],
                report: "",

                loading: false,
                finished: false
            };
        },

        created() {
        },

        methods: {
            cancel() {
                const toast = this.$toast.loading({
                    forbidClick: true,
                    duration: 0
                });
                var ids = '';
                var data = this.form.domains;
                data.forEach(element => {
                    if (element.id != null && element.id != '') {
                        ids +=(element.id+',');
                    }
                });
                this.$axios.post("/report/cancel", {userId: this.user.id, reportIds:ids})
                .then(res => {
                    if(res.code == "ok") {
                        toast.clear();
                        this.$toast.success('撤销成功');
                        this.getReport();
                    } else {
                        toast.clear();
                        this.$toast.fail('获取失败');
                    }
                }).catch(err=> {toast.clear();});
            },

            confirmTime(item, field) {
                if (field == 0) {
                    item.startTime = this.startTime;
                    this.showStartTime = false;
                } else {
                    item.endTime = this.endTime;
                    this.showEndTime = false;
                }
            },
            filter(type, options) {
                if (type === 'minute') {
                    return options.filter(option => option % 30 === 0);
                }

                return options;
            },
            choseTimePick(value, index) {
                //选中时间
                if (this.reportTimeType.type == 0) {
                    this.form.domains[this.clickTimeIndex].timeType = value.value;
                    this.form.domains[this.clickTimeIndex].workingTime = value.hours;
                    this.form.domains[this.clickTimeIndex].label = value.label;
                    this.showPickerTime = false;
                } else if (this.reportTimeType.type == 1) {
                    console.log('this.reportTimeType.type=='+value);
                    this.form.domains[this.clickTimeIndex].workingTime = value;
                    this.form.domains[this.clickTimeIndex].label = value.toFixed(1)+'小时';
                    this.showPickerHours = false;
                }
      
            },
            clickTimePicker(i) {
                this.clickTimeIndex = i;
                
                if (this.reportTimeType.type == 0) {
                    this.showPickerTime = true;
                } else if (this.reportTimeType.type == 1) {
                    this.showPickerHours = true;
                }
            },
            getTimeType() {
                this.$axios.post('/time-type/getCompanyTimeSetting', { companyId: this.user.companyId})
                .then(res => {
                    if(res.code == "ok") {
                        var t = res.data;
                        this.reportTimeType = t;
                        //转化时间格式
                        if (t.allday != null) {
                            this.timeType.push({value:0, label:'全天 - '+t.allday+'小时', hours:t.allday});
                        }
                        if (t.am != null) {
                            this.timeType.push({value:1, label:'上午 - '+t.am+'小时', hours: t.am});
                        }
                        if (t.pm != null) {
                            this.timeType.push({value:2, label:'下午 - '+t.pm+'小时', hours: t.pm});
                        }
                    } else {
                        toast.clear();
                        this.$toast.fail(res.msg);
                    }
                }).catch(err=> {toast.clear();});
            },

            // 返回
            back() {
                history.back();
            },

            // 时间转换
            format(date, pattern) {
                pattern = pattern || "yyyy-MM-dd";
                var _this = this;
                return pattern.replace(/([yMdhsm])(\1*)/g, function ($0) {
                    switch ($0.charAt(0)) {
                        case 'y': return _this.padding(date.getFullYear(), $0.length);
                        case 'M': return _this.padding(date.getMonth() + 1, $0.length);
                        case 'd': return _this.padding(date.getDate(), $0.length);
                        case 'w': return date.getDay() + 1;
                        case 'h': return _this.padding(date.getHours(), $0.length);
                        case 'm': return _this.padding(date.getMinutes(), $0.length);
                        case 's': return _this.padding(date.getSeconds(), $0.length);
                    }
                });
            },

            padding(s, len) {
                var len = len - (s + '').length;
                for (var i = 0; i < len; i++) { s = '0' + s; }
                return s;
            },

            // 获取项目
            getProject() {
                const toast = this.$toast.loading({
                    forbidClick: true,
                    duration: 0
                });
                this.$axios.post("/project/getProjectList", {})
                .then(res => {
                    if(res.code == "ok") {
                        toast.clear();
                        this.project = res.data;
                    } else {
                        toast.clear();
                        this.$toast.fail('获取失败');
                    }
                }).catch(err=> {toast.clear();});
            },

            // 获取日报
            getReport() {
                const toast = this.$toast.loading({
                    forbidClick: true,
                    duration: 0
                });
                this.$axios.post("/report/getReport", {date: this.form.createDate})
                .then(res => {
                    if(res.code == "ok") {
                        toast.clear();
                        this.report = res.data;
                        var t = res.data.timeType;
                        var timeType=[];
                        //转化时间格式
                        if (t.allday != null) {
                            timeType.push({value:0, label:'全天 - '+t.allday+'小时', hours:t.allday});
                        }
                        if (t.am != null) {
                            timeType.push({value:1, label:'上午 - '+t.am+'小时', hours: t.am});
                        }
                        if (t.pm != null) {
                            timeType.push({value:2, label:'下午 - '+t.pm+'小时', hours: t.pm});
                        }
                        var list = res.data.report;
                        if(list.length != 0) {
                            this.canEdit = false;
                            this.canCancel = false;
                            let array = [];
                            for(var i in list) {
                                var projectName = "";
                                for(var j in this.project) {
                                    if(this.project[j].id == list[i].projectId) {
                                        projectName = this.project[j].projectName;
                                    }
                                }
                                array.push({
                                    id: list[i].id,
                                    projectId: list[i].projectId,
                                    projectName: projectName,
                                    workingTime: String(list[i].workingTime),
                                    content: list[i].content,
                                    state: list[i].state,
                                    timeType: list[i].timeType,
                                    label: timeType[list[i].timeType].label
                                })
                                if (list[i].state >= 2) {
                                    this.canEdit = true;
                                } else if (list[i].state == 0) {
                                    this.canCancel = true;
                                }
                            }
                            this.form.domains = array;
                        } else {
                            //没有填报的可以点击提交
                            this.form.domains = [{
                                id: null,
                                projectId: "",
                                projectName: "",
                                workingTime: "",
                                content: "",
                                state: 2,
                            }]
                            this.canEdit = true;
                        }
                    } else {
                        toast.clear();
                        this.$toast.fail('获取失败');
                    }
                }).catch(err=> {toast.clear();});
            },

            // 改变时间
            changeTime(time) {
                this.form.createDate = this.format(new Date(time),"yyyy-MM-dd");
                this.currentDate = time;
                this.showPicker = false;
                this.getReport();
            },

            // 选择项目
            clickPicker(i) {
                this.clickIndex = i;
                this.showPickerProject = true;
            },

            choseProject(value, index) {
                this.form.domains[this.clickIndex].projectId = value.id;
                this.form.domains[this.clickIndex].projectName = value.projectName;
                this.showPickerProject = false;
            },

            // 添加项目 
            addNewPro() {
                this.form.domains.push({
                    id: null,
                    projectId: "",
                    projectName: "",
                    workingTime: "",
                    content: "",
                    state: 2,
                })
            },

            // 移除项目
            delPro(i) {
                this.$dialog.confirm({
                    title: '',
                    message: '是否移除当前项目'
                }).then(() => {
                    this.form.domains.splice(i,1);
                }).catch(() => {
                });
            },

            // 提交日报
            register() {
                const toast = this.$toast.loading({
                    forbidClick: true,
                    duration: 0
                });
                let formData = new FormData();
                if (this.reportTimeType.type == 0) {
                    var alldayNum = 0;
                    var amNum = 0;
                    var pmNum = 0;
                    for(var i in this.form.domains) {
                        if (this.form.domains[i].timeType == 0) {
                            alldayNum ++;
                        } else if (this.form.domains[i].timeType == 1) {
                            amNum++;
                        } else if (this.form.domains[i].timeType == 2) {
                            pmNum++;
                        }
                    }
                    if (alldayNum > 1) {
                        this.$toast.fail("工作时间-全天，只能选择一次");
                        return;
                    }
                    if (amNum > 1) {
                        this.$toast.fail("工作时间-上午，只能选择一次");
                        
                        return;
                    }
                    if (pmNum > 1) {
                        this.$toast.fail("工作时间-下午，只能选择一次");
                        return;
                    }
                    if (alldayNum == 1 && (amNum > 0 || pmNum > 0)) {
                        this.$toast.fail("工作时间-全天，不能和上下午同时存在");
                        return;
                    }
                }
                
                //填字段
                for(var i in this.form.domains) {
                    if (this.form.domains[i].id != null) {
                        formData.append("id", this.form.domains[i].id);
                    } else {
                        formData.append("id", -1);
                    }
                    formData.append("projectId", parseFloat(this.form.domains[i].projectId));
                    formData.append("reportTimeType", this.reportTimeType.type);
                    if (this.reportTimeType.type == 0) {
                        formData.append("timeType", this.form.domains[i].timeType);
                        formData.append("workingTime", parseFloat(this.form.domains[i].workingTime));
                    } else if (this.reportTimeType.type == 1) {
                        formData.append("workingTime", parseFloat(this.form.domains[i].workingTime));
                    } else if (this.reportTimeType.type == 2) {
                        formData.append("startTime", this.form.domains[i].startTime);
                        formData.append("endTime",this.form.domains[i].endTime);
                    }
                    
                    
                    formData.append("content", this.form.domains[i].content);
                    formData.append("createDate", this.form.createDate);
                }
                this.$axios.post("/report/editReport", formData)
                .then(res => {
                    if(res.code == "ok") {
                        toast.clear();
                        this.$toast.success('填报成功');
                        this.$router.push("/index");
                    } else {
                        toast.clear();
                        this.$toast.fail('填报失败');
                    }
                }).catch(err=> {toast.clear();});
            },
        },
        
        mounted() {
            //获取传递过来的日期
            var passDate = this.$route.query.date;
            if (passDate != null) {
                this.form.createDate = this.$route.query.date;
            }
            
            this.getProject();
            this.getReport();
            this.getTimeType();

        }
    };
</script>

<style lang="less" scope>
    .login_form {
        margin-top: 46px;
    }

    .form_domains {
        position: relative;
        .form_addNew {
            position: absolute;
            right: 15px;
            top: 10px;
        }

        .form_del {
            color: #ff0000;
            font-size: 22px;
            position: absolute;
            right: 15px;
            top: 10px;
        }
    }

    .form_tip {
        text-align: center;
        margin-top: 20px;
        color: #afafaf;
        font-size: 14px;
    }

    .card__footer {
        padding-top: 10px;
    }
    .card__tags {
        .van-tag {
            margin-right: 5px;
        }
    }
</style>
<style lang="less">
    .van-nav-bar .van-icon , .van-nav-bar__text {
        color: #20a0ff;
    }
</style>


