<template>
	<el-container class="is-vertical">
        <sc-page-header>
            <template #extra-right>
                <el-button type="warning" @click="refreshState">刷新状态</el-button>
            </template>
        </sc-page-header>

        <scTable ref="xGridTable" :apiObj="$API.system.device" :formConfig="formConfig" :paramsColums="paramsColums" :toolbarConfig="toolbarConfig" :columns="columns"></scTable>
	</el-container>
</template>

<script setup>
import moment from "moment";
import XEUtils from "xe-utils";
import API from "@/api";
import TOOL from "@/utils/tool";
import { gateTypeDic, deviceStateDic } from "@/utils/basicDic";
import { mapFormItemInput, mapFormItemSelect } from "@/components/scTable/helper";

const deviceState = ref({});
const refreshTime = ref(moment().add(20, "second").valueOf());
const interval = ref(null);

const formatGate = ({ projectId, deviceNum }) => XEUtils.find(TOOL.data.get("PASSQRCODE_GATE"), item => XEUtils.findIndexOf(item.devices, d => d.project_id == projectId && d.device_num === deviceNum) !== -1);

const projectConfig = reactive({
    options: TOOL.data.get("PROJECT"),
    optionProps: { label: "projectName", value: "fpiId" },
    events: {
        change: data => XEUtils.merge(formConfig.data, data)
    }
})

const toolbarConfig = reactive({
    enabled: true,
    print: false
})

const formConfig = reactive({
    data: {
        categoryId: 22,
        modelId: 29
    },
    items: [
        mapFormItemSelect("projectId", "所属项目", projectConfig),
        mapFormItemInput("deviceNum", "设备唯一标识")
    ]
})

const paramsColums = reactive([
    { column: "categoryId" },
    { column: "modelId" },
    { column: "projectId" },
    { column: "deviceNum" }
])

const columns = reactive([
    { type: "seq", fixed: "left", width: 60 },
    { type: "html", field: "deviceCode", title: "设备唯一标识", minWidth: 150, sortable: true, formatter: ({ cellValue, row }) => cellValue || row.deviceNum },
    { type: "html", field: "projectName", title: "所属项目", minWidth: 200, sortable: true, formatter: ({ cellValue, row }) => cellValue || XEUtils.get(XEUtils.find(TOOL.data.get("PROJECT"), item => item.fpiId === row.projectId), "projectName") },
    { type: "html", field: "groundName", title: "工地场区", minWidth: 150, sortable: true, formatter: ({ cellValue, row }) => cellValue || XEUtils.get(formatGate(row), "ground.groundName") },
    { type: "html", field: "gateName", title: "闸口名称", minWidth: 150, sortable: true, formatter: ({ cellValue, row }) => cellValue || XEUtils.get(formatGate(row), "gateName") },
    { type: "html", field: "gateType", title: "闸口类型", minWidth: 150, sortable: true, formatter: ({ cellValue, row }) => cellValue || XEUtils.get(gateTypeDic, XEUtils.get(formatGate(row), "gateType")) },
    { field: "state", title: "在线状态", minWidth: 100, align: "center", formatter: ({ row }) => XEUtils.get(deviceStateDic, XEUtils.get(deviceState.value, row.deviceNum), "离线"), editRender: { name: "$cell-tag" } },
    // { title: "操作", fixed: "right", minWidth: 400, slots: { default: "action" } }
])

// 显示隐藏 筛选表单
const xGridTable = ref();

// const tableLength = computed(() => xGridTable.value?.getTableData().fullData.length);
// watch(tableLength, value => value > 0 && getDeviceState());

onMounted(() => window.addEventListener("setItemEvent", ({ key, newValue }) => key == "PASSQRCODE_GATE" && newValue && xGridTable.value?.reloadColumn(columns)));
onUnmounted(() => window.removeEventListener("setItemEvent", () => {}));

const getDeviceState = () => {
    if (interval.value) {
        clearInterval(interval.value);
        interval.value = null;
    }
    stateCheck();
    refreshTime.value = moment().add(20, "second").valueOf();
    interval.value = setInterval(() => {
        stateCheck();
        refreshTime.value = moment().add(20, "second").valueOf();
    }, 120 * 1000);
}

const stateCheck = XEUtils.throttle(function() {
    API.passqrcode.check.get({ expands: XEUtils.zipObject(xGridTable.value.getTableData().fullData.map(f => f.deviceNum), new Array(xGridTable.value.getTableData().fullData.map(f => f.deviceNum).length).fill("ask")) }).then(res => {
        XEUtils.assign(deviceState.value, res.expands);
        xGridTable.value.reloadColumn(columns);
    });
}, 500, { trailing: true, leading: false });

onUnmounted(() => {
    if (interval.value) {
        clearInterval(interval.value);
        interval.value = null;
    }
})

const refreshState = () => {
    if (moment().diff(refreshTime.value, "second") < 0) return ElMessage.warning("请勿重复刷新！(间隔时间至少20秒)");
    // getDeviceState();
}
</script>