<template>
    <div>
        <el-row>
            <el-col :span="24">
                <el-select v-model="select_issue_type" placeholder="请选择Task类型" @change="handleChangeType"
                    style="width: 40%;" size="mini">
                    <el-option key="1" label="未关闭的任务" value="1"></el-option>
                    <el-option key="2" label="已关闭的任务" value="2"></el-option>
                </el-select>
                <el-button style="float: right; padding: 3px 0" type="text" icon="el-icon-circle-plus-outline"
                    @click="createTask()">添加</el-button>
                <div class="table-container">
                    <el-table :data="tasks_list" border fit highlight-current-row
                        style="width: 100%; margin-left: 2px; margin-top: 20px;" height="80vh">
                        <el-table-column prop="task_intro" label="TASK介绍" align="left">
                        </el-table-column>
                        <el-table-column label="TASK资料" align="left" width="150">
                            <template slot-scope="scope">
                                <el-button class="el-icon-view" @click="showMaterial(scope.row)" size="mini"
                                    type="text">查看</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column prop="task_processor_name" label="处理者" align="left" width="150">
                        </el-table-column>
                        <el-table-column prop="task_state_desp" label="任务状态" align="left" width="150">
                        </el-table-column>
                        <!--el-table-column prop="create_time" label="任务创建时间" align="left">
                      </el-table-column-->
                        <!--el-table-column prop="consuming_time" label="耗时" align="left">
                          <template slot-scope="scope">
                              <el-tag>{{ scope.row.consuming_time }}</el-tag>
                          </template>
                      </el-table-column-->
                        <el-table-column label="任务处理时间" align="left" width="400px">
                            <template slot-scope="scope">
                                计划：{{ scope.row.plan_start_time }}~{{ scope.row.plan_close_time }}<br />
                                实际：{{ scope.row.plan_start_time }}~{{ scope.row.real_close_time }}
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" align="left">
                            <template slot-scope="scope">
                                <el-button v-if="scope.row.task_state < 4" type="text" size="mini" class="el-icon-edit"
                                    @click="updateTaskType(scope.row)">处理</el-button>
                                <el-button @click="update(scope.row)" size="mini" class="el-icon-edit-outline"
                                    type="text">编辑</el-button>
                                <el-button class="el-icon-delete" size="mini" type="text"
                                    @click="handleClick(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </el-col>
        </el-row>

        <!-- 修改Task信息对话框 -->
        <el-dialog title="修改Task" :visible.sync="dialogVisibleupTask" :close-on-click-modal="false" width="36%"
            append-to-body>
            <el-form :model="upTask" label-width="120px">
                <el-form-item label="Task任务描述">
                    <el-input v-model="upTask.task_intro" type="textarea" :rows="4"></el-input>
                </el-form-item>
                <el-form-item label="Task处理者">
                    <el-select v-model="upTask.task_processor" placeholder="请选择" style="width: 100%;">
                        <el-option v-for="item in task_member_list" :key="item.id" :label="item.staff_name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="计划处理时间">
                    <el-date-picker v-model="upTask.planned_time" type="datetimerange" range-separator="至"
                        start-placeholder="开始日期" end-placeholder="结束日期" format="yyyy-MM-dd HH:mm:ss"
                        value-format="yyyy-MM-dd HH:mm:ss">
                    </el-date-picker>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisibleupTask = false">取 消</el-button>
                <el-button type="primary" @click="conformupTask">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 处理Task对话框 -->
        <el-dialog title="处理Task" :visible.sync="dialogVisibleTaskType" :close-on-click-modal="false" width="30%"
            append-to-body>
            <el-form label-width="100px">
                <el-form-item label="Task状态">
                    <el-select v-model="task_type" placeholder="请选择" style="width: 100%;">
                        <el-option v-for="item in task_state_list" :key="item.id" :label="item.desp" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="*提示*" style="color: red;">
                    <span>如有Task资料输出，请在Task资料清单中添加</span>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisibleTaskType = false">取 消</el-button>
                <el-button type="primary" @click="conformTaskType">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 添加Task信息对话框 -->
        <el-dialog title="添加Task" :visible.sync="dialogVisibleCreateTask" :close-on-click-modal="false" width="45%"
            append-to-body>
            <el-form :model="newTask" label-width="120px">
                <el-form-item label="Task介绍">
                    <el-input v-model="newTask.task_intro" type="textarea" :rows="4"></el-input>
                </el-form-item>
                <el-form-item label="Task处理者">
                    <el-select v-model="newTask.task_processor" placeholder="请选择" style="width: 100%;">
                        <el-option v-for="item in task_member_list" :key="item.id" :label="item.staff_name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="计划处理时间">
                    <el-date-picker style="width: 100%" v-model="newTask.planned_time" type="datetimerange" range-separator="至"
                        start-placeholder="开始日期" end-placeholder="结束日期" format="yyyy-MM-dd HH:mm:ss"
                        value-format="yyyy-MM-dd HH:mm:ss" :default-time="['00:00:00', '23:59:59']">
                    </el-date-picker>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisibleCreateTask = false">取 消</el-button>
                <el-button type="primary" @click="conformCreateTask">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 资料信息对话框 -->
        <el-dialog title="Task资料清单" :visible.sync="dialogVisibleShowMaterial" :close-on-click-modal="false" width="95%"
            style="position: fixed;top:-10%" append-to-body v-if="update_view == false">
            <div class="custom-dialog">
                <Materials :materials_class="materials_class" :materials_owner="task_id" :edid_authority="true"
                    v-if="update_view == false" />
            </div>
        </el-dialog>

    </div>
</template>

<script>

import project from '@/api/project'
import story from '@/api/story'
import operation from '@/api/operation'
import material from '@/api/material'
import Materials from '@/views/components/Materials.vue'

export default {
    name: 'Task',
    components: {
        Materials,
    },
    props: ['story_id'],

    data() {
        return {
            upload_url: process.env.BASE_WMS_API + '/upload/uploadFile',
            tasks_list: [],
            materials_class: 4, //task资料
            file_list: [],
            select_issue_type: '1',
            update_view: false,
            issue_type_list: [],
            IssueId: 0,
            task_type: 0,
            task_id: 0,
            duration: null,
            task_member_list: [],
            task_state_list: [],
            upTask: {
                task_id: 0,
                task_intro: '',
                task_processor: '',
                planned_time: []
            },
            newTask: {
                //story_id: 0,
                task_intro: '',
                task_name: '',
                create_time: '',
                task_processor: '',
                plan_close_time: ''
            },
            dialogVisibleCreateTask: false,
            dialogVisibleShowMaterial: false,
            dialogVisibleTaskType: false,
            dialogVisibleupTask: false,
            dialogVisibleShowLog: false
        };
    },
    mounted() {
        this.get_story_task_list()
        console.log('------------------------------------');
        console.log(this.story_id);
        // console.log(this.project_id);
        this.get_Story_Task_member_list()
        this.get_task_state_list()


    },
    created() {

    },
    methods: {

        handleClick(row) {
            this.$confirm('您确定要删除此Task吗？').then(() => {
                operation.DeleteTask({ task_id: row.task_id }).then(res => {
                    this.$message.success('删除成功')
                    this.dialogVisibleEdit = false
                    this.get_story_task_list()
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },

        update(row) {
            console.log(row)
            this.dialogVisibleupTask = true
            this.upTask.task_id = row.task_id
            this.upTask.task_intro = row.task_intro
            this.upTask.task_processor = row.task_processor + ''
            this.upTask.planned_time.length = 0;

            if (row.plan_close_time != null && row.plan_start_time != null) {
                this.upTask.planned_time.push(row.plan_start_time);
                this.upTask.planned_time.push(row.plan_close_time);
            }
            console.log(this.upTask.planned_time)
        },
        conformupTask() {
            if (this.upTask.planned_time && this.upTask.planned_time.length === 2) {
                // 获取开始时间和结束时间
                this.upTask.plan_start_time = this.upTask.planned_time[0];
                this.upTask.plan_close_time = this.upTask.planned_time[1];
            }
            story.UpdateTaskInfo(this.upTask).then(res => {
                console.log(res)
                this.$message({
                    message: '修改成功',
                    type: 'success'
                })
                this.dialogVisibleupTask = false
                this.get_story_task_list()
            })
        },
        update_sub_component() {
            this.update_view = true;
            let that = this;
            setTimeout(() => {
                that.update_view = false;
            }, 100); // 1000 毫秒后执行
        },

        get_task_state_list() {
            story.GetTaskStateList().then(response => {
                this.task_state_list = response.data.data
            })
        },

        updateTaskType(row) {
            console.log(row)
            this.dialogVisibleTaskType = true
            this.task_type = ''
            this.task_id = row.task_id
        },
        conformTaskType() {
            const param = {
                task_id: this.task_id,
                task_type: this.task_type
            }
            operation.upTaskType(param).then(res => {
                this.$message({
                    message: '修改成功',
                    type: 'success'
                })
                this.dialogVisibleTaskType = false
                this.get_story_task_list()

            })
        },

        get_story_task_list() {
            var param = { story_id: this.story_id };
            story.GetStoryTaskList(param).then(response => {
                this.tasks_list = response.data.data
                this.tasks_list.forEach(item => {
                    if (item.consuming_time > 0) {
                        //execute_time 秒转换为时分秒
                        const hours = Math.floor(item.consuming_time / 3600);
                        const minutes = Math.floor((item.consuming_time % 3600) / 60);
                        const secs = item.consuming_time % 60;
                        if (hours > 0) {
                            item.consuming_time = hours + '时' + minutes + '分' + secs + '秒';
                        } else {
                            item.consuming_time = minutes + '分' + secs + '秒';
                        }
                    } else {
                        item.consuming_time = '-';
                    }
                    // const plannedTimeInSeconds = Math.floor(item.planned_time / 1000);
                    // if (plannedTimeInSeconds > 0) {
                    //     // execute_time 秒转换为时分秒
                    //     const hours = Math.floor(plannedTimeInSeconds / 3600);
                    //     const minutes = Math.floor((plannedTimeInSeconds % 3600) / 60);
                    //     const secs = plannedTimeInSeconds % 60;
                    //     if (hours > 0) {
                    //         item.planned_time = hours + '时' + minutes + '分' + secs + '秒';
                    //     } else {
                    //         item.planned_time = minutes + '分' + secs + '秒';
                    //     }
                    // } else {
                    //     item.planned_time = '-';
                    // }
                })
            })

        },

        //获取Story参与员工信息
        get_Story_Task_member_list() {
            const param = {
                story_id: this.story_id
            }
            console.log(param)
            story.GetStoryMemberList(param).then(response => {
                this.task_member_list = response.data.data
                console.log(this.task_member_list);
            })
        },



        showLog(IssueId) {
            this.IssueId = IssueId;
            this.dialogVisibleShowLog = true;
        },


        showMaterial(row) {
            this.task_id = row.task_id
            this.dialogVisibleShowMaterial = true;
            this.update_sub_component();
        },

        createTask() {
            this.get_Story_Task_member_list()
            this.dialogVisibleCreateTask = true
            this.file_list = []
            this.fileList = []
        },
        conformCreateTask() {
            console.log(this.file_list);
            // console.log(this.newTask);
            if (this.newTask.planned_time && this.newTask.planned_time.length === 2) {
                // 获取开始时间和结束时间
                //const startTime = this.newTask.planned_time[0];
                //const endTime = this.newTask.planned_time[1];
                // 计算结束时间与开始时间的差值，得到时长（毫秒）

                this.newTask.plan_start_time = this.newTask.planned_time[0];
                this.newTask.plan_close_time = this.newTask.planned_time[1];
                //this.duration = endTime.getTime() - startTime.getTime();
            } else {
                console.log('请选择有效的日期范围');
            }
            this.newTask.story_id = this.story_id
            //this.newTask.planned_time = this.duration
            story.AddStoryTaskInfo(this.newTask).then(res => {
                if (res.data.code === 20000) {
                    this.$message({
                        message: '创建成功',
                        type: 'success'
                    })
                    this.get_story_task_list()
                    this.dialogVisibleCreateTask = false
                } else {
                    this.$message({
                        message: '创建失败：' + res.data.message,
                        type: 'error'
                    })
                }
            })
        },
        handleSuccess(file, fileList) {
            this.file_list.push(file);
        },

        handleRemove(file, fileList) {
            let find = 0;
            for (let i = 0; i < this.file_list.length; i++) {
                if (this.file_list[i]['url'] == file['url']) {
                    find = i;
                }
            }
            this.file_list.splice(find, 1)
        },

        handlePreview(file) {
            console.log(file)
        },

        handleChangeType(value) {
            this.get_project_issue_list()
        },

        beforeUpload(file) {

            const isJPGorPNGorPDF = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'application/pdf';
            const isLt5M = file.size / 1024 / 1024 < 100

            if (!isJPGorPNGorPDF) {
                this.$message.error('只能上传jpg/png/pdf文件!')
            }
            if (!isLt5M) {
                this.$message.error('上传文件大小不能超过 100MB!')
            }
            return isJPGorPNGorPDF && isLt5M
        },

        previewImage(url) {
            this.$dialog({
                title: '图片预览',
                content: `<img src="${url}" alt="Preview" style="max-width: 100%; max-height: 100%;">`,
                closable: true,
                appendToBody: true
            });
        },

        previewPDF(url) {
            this.$dialog({
                title: 'PDF 预览',
                content: `<iframe src="${url}" frameborder="0" style="width: 100%; height: 600px;"></iframe>`,
                closable: true,
                appendToBody: true
            });
        }
    }
}
</script>
<style scoped>
.table-container {
    height: 80vh;
    /* 设置容器高度，与表格高度一致 */
    overflow-y: auto;
    /* 当内容超出高度时显示垂直滚动条 */
}
</style>
