<template>
    <div>
        <div v-show="!$route.path.includes('scenePacketDetail')">
            <search-layout :needBox="true">
                <template slot="searchItem1">
                    <span class="label">场景包名称</span>
                    <el-input
                        v-model="searchParams.packageName"
                        size="small"
                        clearable
                        placeholder="请输入"
                        maxlength="60"
                        @keyup.enter.native="doSearch(false)"
                    >
                    </el-input>
                </template>
                <template slot="searchItem2">
                    <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.yearMin"
                        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.yearMax"
                        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(false)">查询</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">
                        <i
                            @click="editRow(scope.row)"
                            class="el-icon-edit-outline elIcon"
                            title="编辑"
                        ></i>
                        <i
                            @click="delRow(scope.row.id, scope.row.packageName)"
                            class="el-icon-delete elIcon"
                            title="删除"
                        ></i>
                        <i
                            @click="handleRow(scope.row)"
                            class="el-icon-setting elIcon"
                            title="配置账户"
                        ></i>
                    </template>
                </el-table-column>
            </tableList>
    
            <el-dialog
                title="账户分配"
                :visible.sync="dialogVisible"
                width="780px"
                :close-on-click-modal="false"
                :close-on-press-escape="false"
                :before-close="cancelDown"
            >
                <div class="infoBox">
                    <div class="info">
                        <span>场景包名称:</span>
                        <b>{{ packetInfo.packageName }}</b>
                    </div>
                    <div class="info">
                        <span>场景包描述:</span>
                        <b>{{ packetInfo.sceneDescribe }}</b>
                    </div>
                    <div class="boxA">
                        <div class="info">
                            <span>自然驾驶场景:</span>
                            <b>{{
                                packetInfo.zrSceneNames
                                    ? packetInfo.zrSceneNames.length
                                    : 0
                            }}</b>
                        </div>
                        <div class="info">
                            <span>交通事故场景:</span>
                            <b>{{
                                packetInfo.jtSceneNames
                                    ? packetInfo.jtSceneNames.length
                                    : 0
                            }}</b>
                        </div>
                    </div>
                    <div class="boxA">
                        <div class="info">
                            <span>标准法规场景:</span>
                            <b>{{
                                packetInfo.bzSceneNames
                                    ? packetInfo.bzSceneNames.length
                                    : 0
                            }}</b>
                        </div>
                        <div class="info">
                            <span>泛化场景模板:</span>
                            <b>{{
                                packetInfo.fhSceneNames
                                    ? packetInfo.fhSceneNames.length
                                    : 0
                            }}</b>
                        </div>
                    </div>
                    <div class="transferBox">
                        <el-transfer
                            v-model="transferValue"
                            :data="transferData"
                            :titles="['未分配', '已分配']"
                            @change="selectUserChange"
                        ></el-transfer>
                    </div>
                </div>
                <span slot="footer">
                    <el-button type="primary" @click="cancelDown">关 闭</el-button>
                </span>
            </el-dialog>
        </div>

        <router-view v-show="$route.path.includes('scenePacketDetail')"></router-view>
    </div>
</template>

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

export default {
    name: "scenePacketListManagement", // 场景包管理
    components: { searchLayout, tableList },
    data() {
        return {
            searchParams: {
                //搜索参数
                packageName: "", // 场景包名称
                yearMin: "", // 创建时间起
                yearMax: "", // 创建时间止
            },
            createDate: "",
            columns: [
                {
                    label: "场景包名称",
                    prop: "packageName",
                    showOverflowTooltip: true,
                },
                {
                    label: "描述",
                    prop: "sceneDescribe",
                    showOverflowTooltip: true,
                },
                {
                    label: "自然驾驶场景",
                    prop: "zrCount",
                },
                {
                    label: "标准法规场景",
                    prop: "bzCount",
                },
                {
                    label: "交通事故场景",
                    prop: "jtCount",
                },
                {
                    label: "泛化场景模板",
                    prop: "fhCount",
                },
                {
                    label: "操作时间",
                    prop: "createTime",
                },
                {
                    label: "已配置账户",
                    prop: "userCount",
                },
                {
                    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.querySystemScenePackageList,
                param: {},
            },
            dialogVisible: false,
            packetInfo: {}, // 场景包信息
            transferData: [], // 穿梭框data
            transferValue: [], // 穿梭框value
            userList: [], // 用户数据
            curRow: "", // 当前操作row
        };
    },

    watch: {
        $route(to, from) {
            if (to.name === "scenePacketListManagement") {
                this.$nextTick(() => {
                    this.doSearch(true);
                });
            }
        },
    },

    methods: {
        // isBack为解决从详情回退时列表在当前页刷新
        doSearch(isBack = false) {
            let yearMin = "";
            if (this.searchParams.yearMin) {
                yearMin = `${this.searchParams.yearMin} 00:00:00`;
            }

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

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

            let pageMap = {
                packageName: this.searchParams.packageName,
                yearMin,
                yearMax,
                resetPageNum: !isBack ? false : (this.pagination.currentPage || 1),
            };

            if (!isBack) this.pagination.currentPage = 1;

            this.refreshList(pageMap);
        },
        //刷新table
        refreshList(param) {
            param
                ? this.$refs["table"].loadData(param)
                : this.$refs["table"].loadData();
        },
        doReset() {
            this.searchParams = {
                packageName: "",
                yearMin: "",
                yearMax: "",
            };
            // this.createDate = "";
            this.doSearch();
        },
        addOne() {
            this.$store.commit("getTabname", "scenePacketDetailTabName", "");
            localStorage.setItem("scenePacketDetailTabName", "");

            this.$router.push({ path: "/scenePacketDetail" });
        },
        editRow(row) {
            this.$store.commit("getTabname", "scenePacketDetailTabName", row.packageName);
            localStorage.setItem("scenePacketDetailTabName", row.packageName);

            this.$router.push({
                path: "/scenePacketDetail",
                query: {
                    id: row.id,
                },
            });
        },
        delRow(id, packageName) {
            this.$confirm("确认是否删除？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                this.$axios({
                    method: "post",
                    url: this.$api.systemManagement.deleteSystemScenePackage,
                    data: { id, packageName },
                }).then((res) => {
                    if (res.code == 200) {
                        this.$message.success("删除成功");
                    } else {
                        this.$message.error(res.message || "删除失败");
                    }
                    this.doSearch();
                });
            });
        },
        async handleRow(row) {
            this.curRow = row;
            this.dialogVisible = true;
            this.transferData = [];
            this.userList = [];
            this.transferValue = [];

            await this.$axios({
                method: "post",
                url: this.$api.systemManagement.getUserPageList,
                data: { currentPage: 1, pageNum: 1, pageSize: 100000 },
            }).then((res) => {
                if (res.code == 200 && res.info) {
                    this.userList = res.info.list;
                    res.info.list.forEach((i) => {
                        this.transferData.push({
                            key: i.id,
                            label: i.username,
                        });
                    });
                } else {
                    this.$message.error(res.message || "获取信息失败");
                }
            });

            await this.$axios({
                method: "post",
                url: this.$api.systemManagement.querySystemScenePackageById,
                data: { id: row.id },
            }).then((res) => {
                if (res.code == 200 && res.info) {
                    this.packetInfo = res.info;
                    res.info.userIds.forEach((i) => {
                        this.transferValue.push(i.userId);
                    });
                } else {
                    this.$message.error(res.message || "获取信息失败");
                }
            });
        },
        /**
         * 当前值、数据移动的方向（'left' / 'right'）、发生移动的数据 key 数组
         */
        selectUserChange(value, direction, movedKeys) {
            let ids = [];
            movedKeys.forEach((i) => {
                let user = this.userList.find((u) => i === u.id);
                if (user)
                    ids.push({ userId: user.id, userName: user.username });
            });

            let data = {
                packageId: this.curRow.id,
                packageName: this.curRow.packageName,
                userIds: ids,
            };

            // add
            if (direction === "right") {
                this.$axios({
                    method: "post",
                    url: this.$api.systemManagement.saveUserByPackageId,
                    data,
                }).then((res) => {
                    if (res.code == 200) {
                        this.$message.success("增加成功");
                    } else {
                        this.$message.error(res.message || "增加失败");
                    }
                });
            } else {
                // del
                this.$axios({
                    method: "post",
                    url: this.$api.systemManagement.deleteUserByPackageId,
                    data,
                }).then((res) => {
                    if (res.code == 200) {
                        this.$message.success("删除成功");
                    } else {
                        this.$message.error(res.message || "删除失败");
                    }
                });
            }
        },
        cancelDown() {
            this.dialogVisible = false;
        },
    },

    mounted() {},
};
</script>

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

.infoBox {
    padding: 0 10px;
    .info {
        display: flex;
        padding-bottom: 10px;
        word-break: break-all;

        span {
            display: block;
            width: 100px;
        }

        b {
            flex: 1;
            font-weight: normal;
        }
    }

    .boxA {
        display: flex;

        .info {
            flex: 1;
        }
    }

    .transferBox {
        padding-top: 10px;
        text-align: center;

        /deep/ .el-transfer-panel {
            text-align: start;
        }
    }
}
</style>