<template>
    <div>
        <div v-if="!$route.path.includes('projectInfo')">

        <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-select v-model="searchParams.nowRunState">
                    <el-option
                        v-for="item in nowRunStateList"
                        :label="item.caption"
                        :value="item.code"
                        :key="item.code"
                    ></el-option>
                </el-select>
            </template>
            <template slot="searchItem4">
                <span class="label">评测等级</span>
                <el-select v-model="searchParams.evaluationLevel">
                    <el-option
                        v-for="item in evaluationLevelList"
                        :label="item.caption"
                        :value="item.code"
                        :key="item.code"
                    ></el-option>
                </el-select>
            </template>
            <template slot="searchItem5">
                <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>
            </template>
            <template slot="searchItem6">
                <span class="label">完成时间</span>
                <el-date-picker
                    v-model="finishDate"
                    type="daterange"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                >
                </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="cgInfos" align="center">
                <template v-slot="scope">
                    <i
                        v-if="
                            scope.row.nowRunState === '10' ||
                            scope.row.nowRunState === '30' ||
                            scope.row.nowRunState === '40'
                        "
                        @click="runRow(scope.row.id)"
                        class="el-icon-video-play elIcon"
                        title="运行"
                    ></i>
                    <i
                        v-if="
                            scope.row.nowRunState === '10' ||
                            scope.row.nowRunState === '40'
                        "
                        @click="editRow(scope.row)"
                        class="el-icon-edit-outline elIcon"
                        title="编辑"
                    ></i>
                    <i
                        @click="viewRow(scope.row.id)"
                        class="el-icon-view elIcon"
                        title="查看"
                    ></i>
                    <i
                        v-if="scope.row.nowRunState === '20'"
                        @click="stopRow(scope.row.id)"
                        class="el-icon-video-pause elIcon"
                        title="中止"
                    ></i>
                    <i
                        v-if="
                            scope.row.nowRunState === '10' ||
                            scope.row.nowRunState === '30' ||
                            scope.row.nowRunState === '40'
                        "
                        @click="delRow(scope.row.id)"
                        class="el-icon-delete elIcon"
                        title="删除"
                    ></i>
                    <i
                        v-if="scope.row.nowRunState != '10'"
                        @click="downRow(scope.row)"
                        class="el-icon-download elIcon"
                        title="下载"
                    ></i>
                </template>
            </el-table-column>
        </tableList>

        <el-dialog
            title="下载"
            :visible.sync="dialogVisible"
            width="690px"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            :before-close="cancelDown"
        >
            <div class="checkboxPanel">
                <el-checkbox-group v-model="downType">
                    <el-checkbox
                        label="工作报告"
                        class="labelA"
                        :disabled="downDisabled"
                    ></el-checkbox>
                    <el-checkbox label="任务文件包"></el-checkbox>
                </el-checkbox-group>
            </div>
            <span slot="footer">
                <el-button type="primary" @click="confirmDown">确 定</el-button>
                <el-button @click="cancelDown">取 消</el-button>
            </span>
        </el-dialog>

        </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: "manualRunProjectList", // 手动运行项目列表
    components: { searchLayout, tableList },
    data() {
        return {
            searchParams: {
                //搜索参数
                projectId: "", //项目ID
                projectName: "", //项目名称
                nowRunState: "", //进度
                evaluationLevel: "", //测评等级
                createStartDate: "", //创建时间起
                createEndDate: "", //创建时间止
                finishDateStart: "", //完成时间起
                finishDateEnd: "", //完成时间止
            },
            nowRunStateList: [],
            evaluationLevelList: [],
            createDate: "",
            finishDate: "",
            columns: [
                {
                    label: "项目ID",
                    prop: "projectId",
                },
                {
                    label: "项目名称",
                    prop: "projectName",
                },
                {
                    label: "算法名称",
                    prop: "algorithm",
                },
                {
                    label: "创建时间",
                    prop: "createTimeFmt",
                },
                {
                    label: "进度",
                    prop: "nowRunStateDict",
                },
                {
                    label: "评测等级",
                    prop: "evaluationLevelDict",
                },
                // {
                //     label: "停/启用",
                //     prop: "asd",
                //     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.selectProject,
                param: {},
            },
            checkedArr: [],
            downType: [],
            dialogVisible: false,
            curRow: {}, // 当前row
            downDisabled: false, // 用于判断是否可下载工作报告
        };
    },
    methods: {
        doSearch() {
            if (this.createDate) {
                this.searchParams.createStartDate = `${this.createDate[0]}`;
                this.searchParams.createEndDate = `${this.createDate[1]}`;
            } else {
                this.searchParams.createStartDate = "";
                this.searchParams.createEndDate = "";
            }

            if (this.finishDate) {
                this.searchParams.finishDateStart = `${this.finishDate[0]}`;
                this.searchParams.finishDateEnd = `${this.finishDate[1]}`;
            } else {
                this.searchParams.finishDateStart = "";
                this.searchParams.finishDateEnd = "";
            }

            let pageMap = {
                projectId: this.searchParams.projectId,
                projectName: this.searchParams.projectName,
                nowRunState: this.searchParams.nowRunState,
                evaluationLevel: this.searchParams.evaluationLevel,
                createStartDate: this.searchParams.createStartDate,
                createEndDate: this.searchParams.createEndDate,
                finishDateStart: this.searchParams.finishDateStart,
                finishDateEnd: this.searchParams.finishDateEnd,
            };
            this.refreshList(pageMap);
        },
        //刷新table
        refreshList(param) {
            param
                ? this.$refs["table"].loadData(param)
                : this.$refs["table"].loadData();
        },
        doReset() {
            this.searchParams = {
                projectId: "",
                projectName: "",
                nowRunState: "",
                evaluationLevel: "",
                createStartDate: "",
                createEndDate: "",
                finishDateStart: "",
                finishDateEnd: "",
            };
            this.createDate = "";
            this.finishDate = "";
            this.doSearch();
        },
        addOne() {
            this.$router.push({ path: "/manualRunProjectDetail" });
        },
        editRow(row) {
            this.$router.push({
                path: "/manualRunProjectDetail",
                query: {
                    id: row.id,
                },
            });
        },
        runRow(id) {
            this.$confirm("确认是否运行？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                this.$axios({
                    method: "post",
                    url: this.$api.workManagement.updateProjectNowRunState,
                    data: {
                        id,
                        nowRunState: "20",
                    },
                }).then((res) => {
                    if (res.code == 200) {
                        this.$message.success("运行成功");
                    } else {
                        this.$message.error(res.message || "运行失败");
                    }
                    this.doSearch();
                });
            });
        },
        stopRow(id) {
            this.$confirm("确认是否中止？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                this.$axios({
                    method: "post",
                    url: this.$api.workManagement.updateProjectNowRunState,
                    data: {
                        id,
                        nowRunState: "40",
                    },
                }).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.deleteProjectByids,
                    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.nowRunState != "10") {
                    this.$message.error("存在已执行数据，请重新选择");
                    return;
                }
                arr.push(row.id);
            }

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

        viewRow(id) {
            this.$router.push({ path: "/manualRunProjectList/projectInfo", query: { id } });
        },
        downRow(row) {
            this.curRow = row;
            this.downDisabled = row.nowRunState === "30" ? false : true;
            this.dialogVisible = true;
        },
        confirmDown() {
            let url = "";
            let fileName = this.curRow.projectName;

            if (this.downType.length === 0) {
                this.$message.info("请先选择下载类型");
                return;
            } else if (this.downType.length === 1) {
                if (this.downType[0] === "工作报告") {
                    url = this.$api.workManagement.exportProjectReportById;
                    fileName += ".pdf";
                } else {
                    url = this.$api.workManagement.exportProjectTaskFileById;
                    fileName += ".zip";
                }
            } else {
                url =
                    this.$api.workManagement.exportProjectReportAndTaskFileById;
                fileName += ".zip";
            }

            let id = this.curRow.id;
            this.curRow = {};

            this.$axios({
                method: "post",
                url,
                responseType: "blob",
                data: {
                    id,
                },
            }).then((res) => {
                let blob = new Blob([res]);
                if ("download" in document.createElement("a")) {
                    // 非IE下载
                    let emlink = document.createElement("a");
                    emlink.download = fileName;
                    emlink.style.display = "none";
                    emlink.href = URL.createObjectURL(blob);
                    document.body.appendChild(emlink);
                    emlink.click();
                    URL.revokeObjectURL(emlink.href);
                    document.body.removeChild(emlink);
                } else {
                    // IE下载
                    navigator.msSaveBlob(blob, fileName);
                }
            });

            this.downType = [];
            this.dialogVisible = false;
        },
        cancelDown() {
            this.downType = [];
            this.dialogVisible = false;
        },
    },

    async mounted() {
        console.log(666);
        await this.$dicsListsInit({
            nowRunStateList: "projectRunState",
            evaluationLevelList: "evaluationLevel",
        });
        console.log(this.$route);
    },
    activated(){
        console.log(6);
    }
};
</script>

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

.checkboxPanel {
    text-align: center;

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