<template>
    <div>
        <!--    面包屑导航区    -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>流量回放</el-breadcrumb-item>
            <el-breadcrumb-item>querydiff</el-breadcrumb-item>
        </el-breadcrumb>

        <!--    卡片    -->
        <el-card>
            <!--    搜索    -->
            <el-form :inline="true" :mode="taskListPageParam">
                <el-form-item label="任务名称">
                    <el-input v-model="taskListPageParam.taskName" placeholder="请输入任务名称"></el-input>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="queryTaskByPage">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="showCreateTaskDialog">新增任务</el-button>
                </el-form-item>
            </el-form>

            <!--    列表    -->
            <el-table :data="TaskTable" style="width: 100%" border:header-cell-style="{'text-align':'center'}" :cell-style="{'text-align':'center'}">
                <el-table-column prop="task_name" label="任务名称" @click="toTaskDetail(row.id)" showOverflowTooltip/>
                <el-table-column prop="project_name" label="所属项目" showOverflowTooltip/>
                <el-table-column prop="source" label="基准环境" showOverflowTooltip/>
                <el-table-column prop="target" label="验证环境" showOverflowTooltip/>\
                <el-table-column prop="simple_num" label="单个样本数" showOverflowTooltip/>
                <el-table-column prop="api_count" label="实际样本总数" showOverflowTooltip/>
                <el-table-column prop="error_count" label="执行异常总数" showOverflowTooltip/>
                <el-table-column prop="log_time" label="样本选取时间" showOverflowTooltip/>
                <el-table-column prop="created_time" label="创建时间" showOverflowTooltip/>
                <el-table-column prop="created_name" label="创建人" showOverflowTooltip/>
                <!-- 
                <el-table-column prop="status" label="运行状态" :formatter="statusFormatter" showOverflowTooltip/>
                <el-table-column prop="es_select_status" label="筛选状态" :formatter="esStatusFormatter" showOverflowTooltip/>
                -->
                <el-table-column label="操作" align="center" min-width="300px" showOverflowTooltip>
                    <template v-slot="{row}">
                        <el-button type="primary" size="mini" v-if="row.status != 1" @click="showEditTaskDialog(row.id)">编辑</el-button>
                        <el-button type="primary" size="mini" v-if="row.status != 1" @click="removeTaskById(row.id)">删除</el-button>
                        <el-button type="primary" size="mini" @click="toTaskDetail(row.id)">详情</el-button>
                        <el-button type="primary" size="mini" v-if="row.status != 1 && row.es_select_status === 1" @click="batch_request(row.id)">运行任务</el-button>
                        <el-button type="info" size="mini" v-else-if="row.status === 1">运行中</el-button>
                        <el-button type="primary" size="mini" v-if="row.es_select_status === 0 && row.status != 1" @click="selectEsById(row.id)">执行筛选</el-button>
                        <el-button type="primary" size="mini" v-else-if="row.es_select_status === 1" @click="selectEsById(row.id)">重新筛选</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!--    分页    -->
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="taskListPageParam.page"
                :page-sizes="[10, 20, 50, 100, 200]"
                :page-size="taskListPageParam.size"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </el-card>

        <!--    创建任务的dialog    -->
        <el-dialog
            title="新建回放任务"
            :visible.sync="createTaskSubmitDialogVisible"
            width="800px"
            top="8vh"
            :before-close="createTaskSubmitDialogClose">
            <div class="el-dialog-div">
                <el-form
                    :model="createTaskSubmitForm"
                    :rules="createTaskSubmitFormRules"
                    ref="createTaskSubmitFormRef"
                    label-width="100px"
                    inline>
                    <h3>基本信息:</h3>
                    <br>
                    <el-form-item label="任务名称" prop="submitName">
                        <el-input v-model.trim="createTaskSubmitForm.submitName"/>
                    </el-form-item>
                    <el-form-item label="所属项目" prop="ownerProjectId">
                        <el-select v-model="createTaskSubmitForm.ownerProjectId" placeholder="请选择所属项目" clearable>
                            <el-option v-for="item in this.allProject" :label="item.api_project_name" :value="item.id"
                                       :key="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="基准环境" prop="sourceEnv">
                        <el-select v-model="createTaskSubmitForm.sourceEnv" placeholder="请选择环境" clearable>
                            <el-option v-for="(item) in this.allEnv" :label="item.api_environment_name" :value="item.id"
                                       :key="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="验证环境" prop="targetEnv">
                        <el-select v-model="createTaskSubmitForm.targetEnv" placeholder="请选择环境" clearable>
                            <el-option v-for="item in this.allEnv" :label="item.api_environment_name" :value="item.id"
                                       :key="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="指定url" prop="subUrl">
                        <el-input v-model.trim="createTaskSubmitForm.subUrl" placeholder="英文,号隔开"/>
                    </el-form-item>
                    <el-form-item label="单个样本数" prop="simple">
                        <el-input v-model.trim="createTaskSubmitForm.simple"/>
                    </el-form-item>
                    <el-form-item label="样本选取日期">
                        <el-date-picker v-model="createTaskSubmitForm.logTime" type="date" :editable="false"
                                        format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" placeholder="选择日期" clearable></el-date-picker>
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="createTaskSubmitDialogClose()">取 消</el-button>
                <el-button type="primary" @click="createTaskSubmit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    name: "TaskListPage",
    data() {
        return {
            // 创建任务的显示控制
            createTaskSubmitDialogVisible: false,
            // 创建任务的表单对象
            createTaskSubmitForm: {
                        submitName: "",
                        ownerProjectId: "",
                        sourceEnv: "",
                        targetEnv: "",
                        logTime: "",
                        subUrl:"",
                        simple:''
            },
            allProject: [],
            allEnv: [],
            // 创建提测单的表单规则
            createTaskSubmitFormRules: {
                submitName: [
                    {required: true, message: '请输入任务名称', trigger: 'blur'},
                ],
                ownerProjectId: [
                    {required: true, message: '请选择所属项目', trigger: 'blur'},
                ],
                sourceEnv: [
                    {required: true, message: '请选择基准环境', trigger: 'blur'},
                ],
                targetEnv: [
                    {required: true, message: '请选择验证环境', trigger: 'blur'},
                ],
                logTime: [
                    {required: true, message: '请选择样本日期', trigger: 'blur'},
                ],
                simple: [
                    {required: true, message: '请确定单个样本量', trigger: 'blur'},
                ]
            },
            queryDateList: [],

            // 分页查询报告参数
            taskListPageParam: {
                taskName: "",
                page: 1,
                size: 10
            },
            TaskTable: null,
            total: 0,
            // 发布状态显示枚举
            statusMap: {
                0: '未运行',
                1: '运行中',
                2: '结束'
            },
            esStatusMap: {
                0: '未筛选',
                1: '已筛选',
            }
        }
    },
    methods: {
        // 关闭、取消创建
        async createTaskSubmitDialogClose(){
            this.createTaskSubmitForm={
                        submitName: "",
                        ownerProjectId: "",
                        sourceEnv: "",
                        targetEnv: "",
                        logTime: "",
                        subUrl:"",
                        simple:""
                        }
            this.createTaskSubmitDialogVisible = false
        },
         // 查询全部项目
        async queryApiProject() {
            const res = await this.$api.get("/api/backend/api_project/list/")
            if (res.success != true) {
                if (res.error.message != ''){
                    return this.$message.error(res.message)
                }else{
                    return this.$message.error("查询项目失败，请重试!")
                }
            }
            this.allProject = res.data
        },
         // 查询环境
        async queryEnv() {
            const res = await this.$api.get("/api/backend/api_environment/list/")
            if (res.success != true) {
                if (res.error.message != ''){
                    return this.$message.error(res.message)
                }else{
                    return this.$message.error("查询环境失败，请重试!")
                }
            }
            this.allEnv = res.data
        },
        // 创建提测单
        async createTaskSubmit() {
            if (this.createTaskSubmitForm.submitName === '' || this.createTaskSubmitForm.ownerProjectId === '' || this.createTaskSubmitForm.sourceEnv === '' || this.createTaskSubmitForm.targetEnv === '' || this.createTaskSubmitForm.logTime === '' || this.createTaskSubmitForm.simple === ''){
                return this.$message.error("请检查必填项")
            }
            this.createTaskSubmitForm.createUserName = localStorage.getItem('username'); // 记录创建人
            const res = await this.$api.put("api/querydiff/task/create/", this.createTaskSubmitForm)
            if (res.success !== true ) return this.$message.error(res.error.message)

            this.$message.success("保存成功!")
            // 初始化创建提测单的表单信息
            this.createTaskSubmitDialogClose()

            await this.queryTaskByPage();
        },
        // 状态格式化
        statusFormatter(row, column, cellValue) {
            return this.statusMap[cellValue]
        },
        // 状态格式化
        esStatusFormatter(row, column, cellValue) {
            return this.esStatusMap[cellValue]
        },
        // 任务分页查询
        async queryTaskByPage() {
        
            const res = await this.$api.get("/api/querydiff/task/list", this.taskListPageParam)
            // var res = {"success": true, "error": {"code": "", "message": ""}, "data": {"task": [{"id": 1, "task_name": "11就是我", "source_env_id": 15, "target_env_id": 16, "log_time": "2022.07.11", "project_id": 12, "simple_num": 200, "urls": "[\"/api\"]", "opt_num": 0, "status": 1, "es_select_status": 0, "created_name": "陈韬炼", "created_time": "2022-07-13T00:30:47"}], "total": 1}}
            if (res.success != true || res.data === null) return this.$message.error(res.error.message)
            this.TaskTable = res.data.task
            this.total = res.data.total
        },
        // 监听页大小改变的事件
        handleSizeChange(newSize) {
            this.taskListPageParam.size = newSize;
            this.queryTaskByPage()
        },
        // 监听页码改变的事件
        handleCurrentChange(newPage) {
            this.taskListPageParam.page = newPage;
            this.queryTaskByPage()
        },
        // 根据id执行es筛选
        async selectEsById(id) {
            const confirmResult = await this.$confirm(
                '执行当前任务的es流量筛选, 是否继续?',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            ).catch((err) => err)

            if (confirmResult === 'cancel') {
                return this.$message.info('已取消筛选！')
            }
            // 调用接口
            if (confirmResult === 'confirm') {
                const res = await this.$api.post("/api/querydiff/task/screen/", {task_id:id})
                if (res.code !== 200 || res.data.code != 0) return this.$message.error(res.message)
                this.$message.success('任务筛选成功！请查看详情')
            }
        },
        // 根据id执行流量回放
        async batch_request(id) {
            const confirmResult = await this.$confirm(
                '执行当前任务的es流量回放, 是否继续?',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            ).catch((err) => err)

            if (confirmResult === 'cancel') {
                return this.$message.info('已取消回放！')
            }
            
            if (confirmResult === 'confirm') {
                const res = await this.$api.get(`api/querydiff/task/run/${id}`)
                if (res.success !== true) return this.$message.error(res.error.message)
                this.$message.success('任务运行成功！请查看详情')
                await this.queryTaskByPage()
            }
        },

        // 根据id删除项目
        async removeTaskById(id) {
            const confirmResult = await this.$confirm(
                '此操作将永久删除该记录, 是否继续?',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            ).catch((err) => err)

            if (confirmResult === 'cancel') {
                return this.$message.info('已取消删除！')
            }
            // 确认删除时, 调用接口
            if (confirmResult === 'confirm') {
                const res = await this.$api.deleteApi(`/api/querydiff/task/delete/${id}`)
                if (res.success !== true) {
                    await this.queryTaskByPage()
                    return this.$message.error(res.error.message)
                    
                }
                this.$message.success('任务删除成功！')
                await this.queryTaskByPage()
            }
        },
        async showCreateTaskDialog(){
            this.createTaskSubmitDialogVisible = true
            this.queryApiProject()
            this.queryEnv()
        },
        // 跳转详情页
        async toTaskDetail(taskid) {
            this.$router.push(
                {
                    path: '/querydiff/taskDetail',
                    query: {
                        taskId: taskid,
                    }
                }
            )
        }
    },
    
    created() {
        this.queryTaskByPage()
    }
}
</script>
<style lang="less" scoped>
.el-breadcrumb {
    height: 32px;
    line-height: 32px;
}

.el-dialog {
    .el-form-item {
        margin-right: 0;
    }
}

.el-table /deep/ .cell {
    white-space: nowrap;
}

.el-card {
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15) !important;

    .el-table {
        margin-top: 15px;
        margin-bottom: 15px;
    }

    .el-pagination {
        text-align: center;
        margin-top: 15px;
    }
}

.el-dialog {
    .el-card {
        margin-bottom: 10px;
        box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15) !important;

        .summary {
            display: flex;
            flex-direction: column;
            width: 80%;
            color: #8A8C94 !important;

            .summaryTitle {
                line-height: 32px;
                font-size: 16px;
                padding: 0 0 0 18px;
                box-sizing: border-box;
                vertical-align: middle;
            }

            .summaryDetail {
                display: flex;
                justify-content: space-around;
                width: 100%;
                height: 64px;

                .summary-icon {
                    vertical-align: middle;
                    width: 100px;
                    position: relative;
                }

                .summary-icon div {
                    position: absolute;
                    left: 50%;
                    top: 50%;
                    transform: translateX(-50%) translateY(-50%);

                    .iconfont {
                        line-height: 64px;
                        height: 64px;
                        width: 64px;
                        font-size: 32px;
                        text-align: center;
                    }
                }

                .labelName {
                    line-height: 32px;
                    font-size: 14px;
                    padding: 0;
                    box-sizing: border-box;
                    vertical-align: middle;
                    display: block;
                }
            }

            .summaryDetail div:not(:first-child) {
                padding-left: 20px;
                border-left: 1px solid #F5F5F5;
            }

            .summaryDetail div:nth-child(2) {
                margin-left: 80px;
                flex: 2;
            }

            .summaryDetail div:nth-child(3) {
                flex: 1;
            }

            .summaryDetail div:nth-child(4) {
                flex: 1;
            }

            .summaryDetail div:nth-child(5) {
                flex: 1;
            }
        }
    }
}


</style>