<template>
    <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true">
                <el-form-item label="我的工作计时列表" >
                   
                </el-form-item>
                <el-form-item style="float:right;">
                    <el-link type="primary" :underline="false" @click="dialogVisible=true">新增工作计时</el-link>
                </el-form-item>
            </el-form>
        </el-col>

        <!--列表-->
        <el-table :data="list" highlight-current-row v-loading="listLoading" :height="tableHeight" style="width: 100%;">
            <el-table-column prop="projectName" label="项目" ></el-table-column>
            <el-table-column prop="subProjectName" label="子项目" ></el-table-column>
            <el-table-column prop="startTime" label="开始时间" >
            </el-table-column>
            <el-table-column prop="endTime" label="结束时间" >
            </el-table-column>
            <el-table-column prop="timerShow" label="工作时长" >
            </el-table-column>
            
            <el-table-column prop="endTime" label="状态" >
                <template slot-scope="scope">
                    <span style="color:red;" v-if="scope.row.endTime == null">进行中</span>
                    <span style="color:green;" v-if="scope.row.endTime != null">计时完成</span>
                </template>
            </el-table-column>
            
            <el-table-column label="操作" width="320">
                <template slot-scope="scope">
                    <el-button  type="default" :disabled="scope.row.endTime != null" :loading="logining" size="small" @click="stopTimer(scope.row.id)">停止</el-button>
                    <el-button  type="default" :loading="logining" :disabled="scope.row.endTime == null" size="small" @click="report(scope.row)">{{scope.row.reportId==null?'转日报':'查看日报'}}</el-button>
                    <el-button  type="default" :loading="logining" size="small"
                     @click="deleteItem(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 创建自动计时的dialog -->
        <el-dialog title="创建自动计时" :visible.sync="dialogVisible" width="550px">
            <el-form ref="workForm" :model="workForm" label-width="100px">
                <el-form-item label="投入项目" :prop="projectId"
                        :rules="{ required: true, message: '请选择投入项目', trigger: ['change','blur'] }">
                        <el-select v-model="workForm.projectId" placeholder="请选择" style="width:200px;" 
                        @change="selectProject()"
                        >
                        <el-option v-for="item in projectList" 
                        :key="item.id" :label="item.projectName" :value="item.id"></el-option>
                        </el-select>
                        <!--子项目 -->
                        <el-select v-model="workForm.subProjectId" 
                        placeholder="请选择" style="width:200px;" clearable="true" 
                        >
                        <el-option v-for="item in subProjectList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="createTimer" >开始计时</el-button>
            </span>
        </el-dialog>

        <!-- 创建日报的dialog -->
        <el-dialog title="转日报" :visible.sync="reportDialog" width="550px">
            <el-form ref="reportForm" :model="reportForm" label-width="100px">
                <el-form-item label="投入项目" >
                     {{reportForm.projectName}}  <span v-if="reportForm.subProjectId != null"> / {{reportForm.subProjectName}}   </span> 
                </el-form-item>
                <el-form-item label="开始时间" >
                     {{reportForm.startTime}}
                </el-form-item>
                <el-form-item label="结束时间" >
                     {{reportForm.endTime}}
                </el-form-item>
                <el-form-item label="时长" >
                     {{reportForm.timerShow}}
                </el-form-item>
                <el-form-item label="工作事项" >
                     <el-input v-model="reportForm.content" type="textarea" :rows="4" placeholder="请填写工作事项" clearable
                         ></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="reportDialog = false">取消</el-button>
                <el-button type="primary" @click="submitReport" >提交日报</el-button>
            </span>
        </el-dialog>
    </section>
    

</template>

<script>
    import util from "../../common/js/util";

    export default {
        data() {
            return {
                firstLoadTime:null,
                projectList: [], //项目列表
                subProjectList:[],
                user: JSON.parse(sessionStorage.getItem("user")),
                dialogVisible: false,
                search: {
                    value: 0,
                    date: util.formatDate.format(new Date(new Date()), "yyyy-MM-dd"),
                },
                workForm:{},
                users: [],

                tableHeight: 0,
                listLoading: false,
                total: 0,
                page: 1,
                size: 20,
                list: [],
                logining: false,
                timer:null,
                reportForm:{},
                reportDialog: false
            };
        },
        methods: {
            submitReport() {
                this.http.post('/project-timer/tranferToReport',this.reportForm,
                    res => {
                        if (res.code == "ok") {
                            this.reportDialog = false;
                            this.getList();
                            this.$message({
                                message: '日报已提交，等待项目经理审核',
                                type: "success"
                            });
                        } 
                    },
                    error => {
                        this.listLoading = false;
                        this.$message({
                            message: error,
                            type: "error"
                        });
                        }
                    );
            },
            report(row) {
                if (row.reportId == null) {
                    this.reportForm = row;
                    this.reportDialog = true;
                } else {
                    this.$router.push('/daily');
                }
                
            },
            stopTimer(id) {
                this.$confirm("确定要停止计时吗?","提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                .then(() => {
                    this.listLoading = true;
                    this.http.post('/project-timer/endTimer',{id: id},
                    res => {
                        this.listLoading = false;
                        if (res.code == "ok") {
                            this.getList();
                        } else {
                            this.$message({
                                message: res.msg,
                                type: "error"
                            });
                        }
                    },
                    error => {
                        
                        this.$message({
                            message: error,
                            type: "error"
                        });
                        }
                    );
                })
                .catch(() => {});
            },
            deleteItem(id) {
                this.$confirm("确定要删除该记录吗?","提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                .then(() => {
                    this.listLoading = true;
                    this.http.post('/project-timer/deleteTimer',{id: id},
                    res => {
                        this.listLoading = false;
                        if (res.code == "ok") {
                            this.getList();
                        } else {
                            this.$message({
                                message: res.msg,
                                type: "error"
                            });
                        }
                    },
                    error => {
                        this.listLoading = false;
                        this.$message({
                            message: error,
                            type: "error"
                        });
                        }
                    );
                })
                .catch(() => {});
                
            },
            //创建计时器
            createTimer() {
                this.$refs.workForm.validate(valid => {
                    if (valid) {
                        if (this.workForm.projectId == null) {
                            this.$message({
                                message: '请选择投入项目',
                                type: "error"
                            });
                            return;
                        }
                        this.workForm.projectName = this.projectList.filter(p=>p.id == this.workForm.projectId)[0].projectName;
                        if (this.workForm.subProjectId != null) {
                            this.workForm.subProjectName = this.subProjectList.filter(s=>s.id == this.workForm.subProjectId)[0].name;
                        }
                        this.http.post('/project-timer/addTimer',this.workForm,
                            res => {
                                if (res.code == "ok") {
                                    this.dialogVisible = false;
                                    this.getList();
                                } 
                            },
                            error => {
                                this.listLoading = false;
                                this.$message({
                                    message: error,
                                    type: "error"
                                });
                                }
                            );
                    }
                });
            },
            //项目选中了， 加载子项目
            selectProject() {
                this.workForm.subProjectId = null;
                this.subProjectList = [];
                this.http.post('/sub-project/list',{ 
                        projectId: this.workForm.projectId
                    },
                    res => {
                        if (res.code == "ok") {
                            this.subProjectList = res.data;
                        } 
                    },
                    error => {
                        this.listLoading = false;
                        this.$message({
                            message: error,
                            type: "error"
                        });
                        }
                    );
            },
            //获取项目列表
            getProjectList() {
                this.listLoading = true;
                this.http.post( this.port.project.list, {},
                res => {
                    this.listLoading = false;
                    if (res.code == "ok") {
                        this.projectList = res.data;
                    } else {
                        this.$message({
                            message: res.msg,
                            type: "error"
                        });
                    }
                },
                error => {
                    this.listLoading = false;
                    this.$message({
                        message: error,
                        type: "error"
                    });
                });
            },
            //获取定时任务列表
            getList() {
                this.listLoading = true;
                this.http.post('/project-timer/getMyTimer', {},
                res => {
                    this.listLoading = false;
                    if (res.code == "ok") {
                        this.list = res.data;
                    } else {
                        this.$message({
                        message: res.msg,
                        type: "error"
                        });
                    }
                },
                error => {
                    this.listLoading = false;
                    this.$message({
                        message: error,
                        type: "error"
                    });
                });
            },
            calculateTimer() {
                if (this.list != null) {
                    var now = new Date();
                    var myList = JSON.parse(JSON.stringify(this.list));
                    console.log(myList);
                    for (var i=0;i<myList.length; i++) {
                        if (myList[i].endTime == null) {
                            if (myList[i].timerShow == null) {
                                myList[i].timerShow = this.formatTimer(myList[i].timer);
                                this.firstLoadTime = now;
                            } else {
                                myList[i].timerShow = this.formatTimer(myList[i].timer + ((now.getTime() - this.firstLoadTime.getTime())/1000));
                            }
                        } else {
                            myList[i].timerShow = this.formatTimer(myList[i].timer);
                        }
                        
                    }
                    this.list = myList;
                    // this.$forceUpdate();
                }
            },
            formatTimer(t) {
                var hours = parseInt(t/3600);
                var minutes = parseInt(t%3600/60);
                var seconds = parseInt(t%60);
                var show = '';
                console.log('hours=='+hours);
                show += hours<10?('0'+hours):hours;
                show += ':';
                show += minutes<10?('0'+minutes):minutes;
                show += ':';
                show += seconds<10?('0'+seconds):seconds;
                
                return show;
            }

        },
        created() {
            let height = window.innerHeight;
            this.tableHeight = height - 125;
            const that = this;
            window.onresize = function temp() {
                that.tableHeight = window.innerHeight - 125;
            };
        },
        
        mounted() {
            this.getList();
            this.getProjectList();
            this.timer = setInterval(() => {
                this.calculateTimer();
            }, 1000);
        },
        beforeDestroy() {
            clearInterval(this.timer);
        }
    };
</script>

<style lang="scss" scoped>
</style>