<template>
    <div>
        <search-layout :needBox="true">
            <template slot="searchItem1">
                <span class="label">任务名称</span>
                <el-input
                    v-model="searchParams.name"
                    size="small"
                    clearable
                    placeholder="请输入"
                    maxlength="60"
                    @keyup.enter.native="doSearch"
                >
                </el-input>
            </template>
            <template slot="searchItem2">
                <span class="label">上传时间</span>
                <!-- <el-date-picker
                    v-model="uploadDate"
                    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.timeBegin"
                    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.timeEnd"
                    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"
                icon="el-icon-circle-plus-outline"
                @click="addOne"
                >新增</el-button
            >
        </div>

        <tableList
            ref="table"
            style="margin: 0 30px"
            :columns="columns"
            :getDataWay="getDataWay"
            :pagination="pagination"
            index
        >
            <el-table-column label="操作" slot="cgInfos" align="center">
                <template v-slot="scope">
                    <span
                        v-if="scope.row.errorMessage"
                        @click="viewRow(scope.row.errorMessage)"
                        class="errRecord"
                        >错误记录</span
                    >
                </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="uploadCancel"
        >
            <el-form
                ref="form"
                :model="form"
                :rules="rules"
                label-width="108px"
            >
                <el-form-item label="任务名称:" prop="name">
                    <el-input
                        placeholder="请输入"
                        maxlength="60"
                        v-autoTrim="{ obj: form, key: 'name' }"
                        v-model="form.name"
                    >
                    </el-input>
                </el-form-item>

                <el-form-item label="场景分类:" prop="sceneType">
                    <el-select
                        v-model="form.sceneType"
                        @change="sceneTypeChange"
                    >
                        <el-option
                            v-for="item in sceneTypeList"
                            :label="item.caption"
                            :value="item.code"
                            :key="item.code"
                        ></el-option>
                    </el-select>
                </el-form-item>

                <!-- 三个真实场景时展示 -->
                <el-form-item
                    v-if="form.sceneType != '4'"
                    label="场景路径:"
                    prop="dataDirectory"
                >
                    <el-input
                        placeholder="请输入"
                        maxlength="300"
                        v-autoTrim="{ obj: form, key: 'dataDirectory' }"
                        v-model="form.dataDirectory"
                    >
                    </el-input>
                </el-form-item>

                <!-- 泛化时展示 -->
                <el-form-item
                    v-if="form.sceneType === '4'"
                    label="文件上传:"
                    prop="fileName"
                >
                    <el-input
                        placeholder="请输入"
                        maxlength="600"
                        v-autoTrim="{ obj: form, key: 'fileName' }"
                        v-model="form.fileName"
                        disabled
                    >
                    </el-input>
                    <upload
                        ref="upload"
                        class="upload"
                        @handleChange="handleChange"
                    ></upload>
                </el-form-item>
            </el-form>
            <span slot="footer">
                <el-button type="primary" @click="uploadConfirm"
                    >确 定</el-button
                >
                <el-button @click="uploadCancel">取 消</el-button>
            </span>
        </el-dialog>

        <el-dialog
            title="错误记录"
            :visible.sync="errRocordVisible"
            width="690px"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            :before-close="errClose"
        >
            <div>{{ errorMessage }}</div>
            <span slot="footer">
                <el-button type="primary" @click="errClose">关 闭</el-button>
            </span>
        </el-dialog>
    </div>
</template>

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

export default {
    name: "sceneUploadList", // 场景上传
    components: { searchLayout, tableList, upload },
    data() {
        let formatSeconds = function formatSeconds(value) {
            var theTime = parseInt(value); // 秒
            var theTime1 = 0; // 分
            var theTime2 = 0; // 小时
            if (theTime > 60) {
                theTime1 = parseInt(theTime / 60);
                theTime = parseInt(theTime % 60);
                if (theTime1 > 60) {
                    theTime2 = parseInt(theTime1 / 60);
                    theTime1 = parseInt(theTime1 % 60);
                }
            }
            var result = "" + parseInt(theTime) + "秒";
            if (theTime1 > 0) {
                result = "" + parseInt(theTime1) + "分" + result;
            }
            if (theTime2 > 0) {
                result = "" + parseInt(theTime2) + "小时" + result;
            }
            return result;
        };

        return {
            searchParams: {
                //搜索参数
                name: "", // 任务名称
                timeBegin: "", // 上传时间起
                timeEnd: "", // 上传时间止
            },
            uploadDate: "",
            columns: [
                {
                    label: "任务名称",
                    prop: "name",
                },
                {
                    label: "场景分类",
                    prop: "sceneType",
                },
                {
                    label: "上传时间",
                    prop: "createTime",
                },
                {
                    label: "上传状态",
                    prop: "status",
                },
                {
                    label: "总用时长",
                    prop: "totalTime",
                    formatter: (row) => {
                        if (row.totalTime)
                            if (row.totalTime && !isNaN(row.totalTime)) {
                                return formatSeconds(row.totalTime);
                            }
                    },
                },
                {
                    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.systemManagement.getSceneImporPagetList,
                param: {},
            },
            form: {
                name: "", // 任务名称
                sceneType: "", // 场景分类
                dataDirectory: "", // 场景路径
                fileName: "", // 文件名称
            },
            rules: {
                name: [{ required: true, message: "请输入", trigger: "blur" }],
                sceneType: [
                    { required: true, message: "请选择", trigger: "change" },
                ],
                dataDirectory: [
                    { required: true, message: "请输入", trigger: "blur" },
                ],
                fileName: [
                    { required: true, message: "请上传", trigger: "change" },
                ],
            },
            sceneTypeList: [],
            dialogVisible: false,
            file: null,
            errRocordVisible: false,
            errorMessage: "",
        };
    },

    methods: {
        doSearch() {
            // if (this.uploadDate) {
            //     this.searchParams.timeBegin = `${this.uploadDate[0]}`;
            //     this.searchParams.timeEnd = `${this.uploadDate[1]}`;
            // } else {
            //     this.searchParams.timeBegin = "";
            //     this.searchParams.timeEnd = "";
            // }

            let timeBegin = "";
            if (this.searchParams.timeBegin) {
                timeBegin = `${this.searchParams.timeBegin} 00:00:00`;
            }

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

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

            let pageMap = {
                name: this.searchParams.name,
                timeBegin,
                timeEnd,
            };
            this.refreshList(pageMap);
        },
        //刷新table
        refreshList(param) {
            param
                ? this.$refs["table"].loadData(param)
                : this.$refs["table"].loadData();
        },
        doReset() {
            this.searchParams = {
                name: "",
                timeBegin: "",
                timeEnd: "",
            };
            // this.uploadDate = "";
            this.doSearch();
        },
        addOne() {
            this.form = {
                name: "",
                sceneType: "",
                dataDirectory: "",
                fileName: "",
            };
            this.file = null;

            this.dialogVisible = true;

            this.$nextTick(() => {
                this.$refs.form.clearValidate();
            });
        },
        viewRow(errorMessage) {
            this.errorMessage = errorMessage;
            this.errRocordVisible = true;
        },
        errClose() {
            this.errRocordVisible = false;
            this.errorMessage = "";
        },
        uploadConfirm() {
            this.$refs.form.validate(async (valid) => {
                if (valid) {
                    if (this.form.sceneType === "4") {
                        let formData = new FormData();
                        await formData.append("taskName", this.form.name);
                        await formData.append("name", this.file.name);
                        await formData.append("file", this.file.raw);

                        await this.$axios({
                            method: "post",
                            url: this.$api.systemManagement
                                .saveSceneGeneralTemplateAll,
                            data: formData,
                            withCredentials: true,
                            headers: {
                                "Content-type": "multipart/form-data",
                            },
                        }).then((res) => {
                            if (res.code == 200) {
                                this.$message.success("保存成功");
                                this.uploadCancel();
                                this.doSearch();
                            } else {
                                this.$message.error(res.message || "保存失败");
                            }
                        });
                    } else {
                        this.$axios({
                            method: "post",
                            url: this.$api.systemManagement.saveTask,
                            data: { ...this.form },
                        }).then((res) => {
                            if (res.code == 200) {
                                this.$message.success("保存成功");
                                this.uploadCancel();
                                this.doSearch();
                            } else {
                                this.$message.error(res.message || "保存失败");
                            }
                        });
                    }
                }
            });
        },
        uploadCancel() {
            this.dialogVisible = false;
        },
        attachmentChange(obj) {
            this.attachmentList = obj;
        },
        handleChange(file) {
            this.file = file;
            this.form.fileName = file.name;
        },
        sceneTypeChange(v) {
            if (v === "4") {
                this.$refs.form.clearValidate("dataDirectory");
            } else {
                this.file = null;
                this.form.fileName = "";
                this.$refs.form.clearValidate("fileName");
            }
        },
    },

    async mounted() {
        await this.$dicsListsInit({
            sceneTypeList: "sceneType",
        });
    },
};
</script>

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

.errRecord {
    color: @themeColor;
    cursor: pointer;
}

.upload {
    margin-top: 15px;
}
</style>