<template>
    <div>
        <div v-if="!$route.path.includes('autoRunSubProjectList')">
            <search-layout :needBox="true">
                <template slot="searchItem1">
                    <span class="label">项目ID</span>
                    <el-input
                        v-model="searchParams.projectId"
                        size="small"
                        clearable
                        placeholder="请输入"
                        maxlength="60"
                        @keyup.enter.native="doSearch"
                    >
                    </el-input>
                </template>
                <template slot="searchItem2">
                    <span class="label">项目名称</span>
                    <el-input
                        v-model="searchParams.projectName"
                        size="small"
                        clearable
                        placeholder="请输入"
                        maxlength="60"
                        @keyup.enter.native="doSearch"
                    >
                    </el-input>
                </template>
                <template slot="searchItem3">
                    <span class="label">创建时间</span>
                    <!-- <el-date-picker
                        v-model="createDate"
                        type="daterange"
                        format="yyyy-MM-dd"
                        value-format="yyyy-MM-dd"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                    >
                    </el-date-picker> -->
                    <el-date-picker
                        v-model="searchParams.createStartDate"
                        type="date"
                        format="yyyy-MM-dd"
                        value-format="yyyy-MM-dd"
                        placeholder="开始日期"
                        class="dateRangeInput"
                    >
                    </el-date-picker>
                    <span class="dateSeparator">至</span>
                    <el-date-picker
                        v-model="searchParams.createEndDate"
                        type="date"
                        format="yyyy-MM-dd"
                        value-format="yyyy-MM-dd"
                        placeholder="结束日期"
                        class="dateRangeInput"
                    >
                    </el-date-picker>
                </template>

                <template slot="searchBtn1">
                    <el-button type="primary" @click="doSearch">查询</el-button>
                </template>
                <template slot="searchBtn2">
                    <el-button type="primary" @click="doReset">重置</el-button>
                </template>
            </search-layout>

            <div class="btnsPanel">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-delete"
                    @click="delRows"
                    >批量删除</el-button
                >
                <el-button
                    type="primary"
                    icon="el-icon-circle-plus-outline"
                    @click="addOne"
                    >创建</el-button
                >
            </div>

            <tableList
                ref="table"
                style="margin: 0 30px"
                :columns="columns"
                :getDataWay="getDataWay"
                :pagination="pagination"
                :checkedData="checkedArr"
                selection
                index
            >
                <el-table-column
                    label="停/启用"
                    slot="automaticRunState"
                    align="center"
                >
                    <template v-slot="scope">
                        <el-switch
                            v-model="scope.row.automaticRunState"
                            active-value="0"
                            inactive-value="1"
                            active-color="#3397FF"
                            inactive-color="#ff4949"
                            @change="
                                ($event) => {
                                    switchVisible($event, scope.row);
                                }
                            "
                        ></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" slot="cgInfos" align="center">
                    <template v-slot="scope">
                        <i
                            @click="viewRow(scope.row.id)"
                            class="el-icon-view elIcon"
                            title="查看"
                        ></i>
                        <i
                            @click="editRow(scope.row)"
                            class="el-icon-edit-outline elIcon"
                            title="编辑"
                        ></i>
                        <i
                            @click="runRow(scope.row.id, scope.row.parallelism)"
                            class="el-icon-refresh-right elIcon"
                            title="运行"
                        ></i>
                        <i
                            v-if="scope.row.automaticRunState === '1'"
                            @click="delRow(scope.row.id)"
                            class="el-icon-delete elIcon"
                            title="删除"
                        ></i>
                        <!-- 停用的时候显示删除 automaticRunState 0是启用 1是停用 -->
                    </template>
                </el-table-column>
            </tableList>
        </div>
        <router-view v-else></router-view>
    </div>
</template>

<script>
import searchLayout from "@/components/grid/searchLayout";
import tableList from "@/components/grid/TableList";

export default {
    name: "autoRunProjectList", // 自动化测试列表
    components: { searchLayout, tableList },
    data() {
        return {
            searchParams: {
                //搜索参数
                projectId: "", //项目ID
                projectName: "", //项目名称
                createStartDate: "", //创建时间起
                createEndDate: "", //创建时间止
            },
            createDate: "",
            columns: [
                {
                    label: "项目ID",
                    prop: "projectId",
                },
                {
                    label: "项目名称",
                    prop: "projectName",
                },
                {
                    label: "创建时间",
                    prop: "createTimeFmt",
                },
                {
                    label: "算法名称",
                    prop: "algorithm",
                },
                {
                    label: "自动化测试次数",
                    prop: "automaticRunTimes",
                },
                {
                    label: "最近运行时间",
                    prop: "lastRunTimeFmt",
                },
                {
                    label: "停/启用",
                    prop: "automaticRunState",
                    template: true,
                },
                {
                    label: "操作",
                    prop: "cgInfos",
                    template: true,
                },
            ],
            pagination: {
                //分页使用
                currentPage: 1,
                pageSize: 10,
                position: "right",
                pageSizes: [10, 30, 50, 100, 200],
                layout: "sizes, total, prev, pager, next, jumper",
            },
            getDataWay: {
                //加载表格数据
                dataType: "url",
                type: "post",
                // firstRequest: false,
                data: this.$api.workManagement.selectAutomaticProject,
                param: {},
            },
            checkedArr: [],
            curRow: {}, // 当前row
            timer: null,
        };
    },
    methods: {
        doSearch() {
            let createStartDate = "";
            if (this.searchParams.createStartDate) {
                createStartDate = `${this.searchParams.createStartDate} 00:00:00`;
            }

            let createEndDate = "";
            if (this.searchParams.createEndDate) {
                createEndDate = `${this.searchParams.createEndDate} 23:59:59`;
            }

            if (
                createStartDate &&
                createEndDate &&
                createStartDate > createEndDate
            ) {
                this.$message.error("结束时间不能早于开始时间");
                return;
            }

            let pageMap = {
                projectId: this.searchParams.projectId,
                projectName: this.searchParams.projectName,
                createStartDate,
                createEndDate,
            };
            this.refreshList(pageMap);

            if (this.timer) clearInterval(this.timer);

            this.timer = setInterval(() => {
                if (this.$refs["table"]) this.doSearch();
            }, 1000 * 60);
        },
        //刷新table
        refreshList(param) {
            param
                ? this.$refs["table"].loadData(param)
                : this.$refs["table"].loadData();
        },
        doReset() {
            this.searchParams = {
                projectId: "",
                projectName: "",
                createStartDate: "",
                createEndDate: "",
            };
            // this.createDate = "";
            this.doSearch();
        },
        addOne() {
            this.$router.push({ path: "/autoRunProjectDetail" });
        },
        switchVisible(value, row) {
            // 停用
            if (value === "1") {
                row.automaticRunState = "0";
                this.$confirm("确认该项目停用自动化测试？", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }).then(() => {
                    this.$axios({
                        method: "POST",
                        url: this.$api.workManagement.updateAutomaticRunState,
                        data: {
                            id: row.id,
                            automaticRunState: "1",
                        },
                    }).then((res) => {
                        if (res.code == 200) {
                            row.automaticRunState = "1";
                            this.$message.success("停用成功");
                        } else {
                            this.$message.error(res.message || "停用失败");
                        }
                    });
                });
            } else {
                // 启用
                row.automaticRunState = "1";
                this.$confirm("确认该项目启用自动化测试？", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }).then(() => {
                    this.$axios({
                        method: "POST",
                        url: this.$api.workManagement.updateAutomaticRunState,
                        data: {
                            id: row.id,
                            automaticRunState: "0",
                        },
                    }).then((res) => {
                        if (res.code == 200) {
                            row.automaticRunState = "0";
                            this.$message.success("启用成功");
                        } else {
                            this.$message.error(res.message || "启用失败");
                        }
                    });
                });
            }
        },
        editRow(row) {
            this.$router.push({
                path: "/autoRunProjectDetail",
                query: {
                    id: row.id,
                },
            });
        },
        runRow(id, parallelism) {
            this.$confirm("确认是否运行？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                if (parallelism == "0") {
                    this.$message.error("并行度为0，不能运行");
                    return;
                }

                this.$axios({
                    method: "post",
                    url: this.$api.workManagement.createAutomaticSubProject,
                    data: { id },
                }).then((res) => {
                    if (res.code == 200) {
                        this.$message.success("运行成功");
                    } else {
                        this.$message.error(res.message || "运行失败");
                    }
                    this.doSearch();
                });
            });
        },
        delRow(ids) {
            this.$confirm("确认是否删除？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                this.$axios({
                    method: "post",
                    url: this.$api.workManagement.deleteAutomaticProjectByids,
                    data: {
                        ids,
                    },
                }).then((res) => {
                    if (res.code == 200) {
                        this.$message.success("删除成功");
                    } else {
                        this.$message.error(res.message || "删除失败");
                    }
                    this.doSearch();
                });
            });
        },
        delRows() {
            let checkedArr = this.checkedArr;
            if (checkedArr.length <= 0) {
                this.$message.info("请先选择数据");
                return;
            }

            let arr = [];

            for (let index = 0; index < checkedArr.length; index++) {
                const row = checkedArr[index];
                if (row.automaticRunState != "1") {
                    this.$message.error("存在未停用数据，请重新选择");
                    return;
                }
                arr.push(row.id);
            }

            this.delRow(arr.join(","));
        },

        viewRow(id) {
            this.$router.push({
                path: "/autoRunProjectList/autoRunSubProjectList",
                query: { id },
            });
        },
    },

    mounted() {
        if (this.timer) clearInterval(this.timer);

        this.timer = setInterval(() => {
            if (this.$refs["table"]) this.doSearch();
        }, 1000 * 60);
    },

    beforeDestroy() {
        clearInterval(this.timer);
    },
};
</script>

<style lang="less" scoped>
.btnsPanel {
    margin: 45px 40px 15px;
    text-align: right;
}

.checkboxPanel {
    text-align: center;

    .labelA {
        margin-right: 60px;
    }
}
</style>
