<template>
    <div>
        <el-row :gutter="10">
            <!-- 分组 -->
            <el-col :span="4" :xs="24">
                <el-card>
                    <template #header>
                        <div class="card-header">
                            <span style="font-size:20px;">站点数据[{{ state.stationNum }}]</span>
                            <div>
                                <el-button size="small" icon="el-icon-refresh" circle @click="handleRefresh" />
                                <el-button size="small" circle @click="state.isSearch = !state.isSearch">
                                    <el-icon style="vertical-align: middle">
                                        <Search />
                                    </el-icon>
                                </el-button>
                            </div>
                        </div>
                    </template>
                    <div class="div">
                        <div>
                            <el-select v-model="state.queryUnitCode" placeholder="选择或搜索相关单位(支持拼音)" @change="queryTreeList"
                                style="margin-bottom: 5px;margin-right:20px;width: 100%;" :filter-method="filterUnit"
                                v-if="state.isSearch && userType === '0'" filterable clearable ref="selectUnit">
                                <el-option v-for="item in state.unitData" :key="item.unitCode" :label="item.unitName"
                                    :value="item.unitCode"></el-option>
                            </el-select>
                            <el-input v-model="state.filterText" placeholder="关键词搜索(支持拼音首字母)" style="margin-bottom: 10px;"
                                clearable v-if="state.isSearch"></el-input>
                        </div>

                        <el-tree class="tree" :data="state.groupData" :property="defaultProps" ref="tree" node-key="id"
                            accordion :expand-on-click-node="false" @node-click="handleNodeClick"
                            :filter-node-method="filterNode">

                            <template #default="{ node, data }">
                                <el-icon v-if="data.type === '0' || data.type === '1'" :size="15" color="#409EFC">
                                    <Folder />
                                </el-icon>

                                <!-- 水表 -->
                                <el-icon v-else-if="data.deviceType === '1'" :size="20">
                                    <Odometer />
                                </el-icon>

                                <!-- 压力表 -->
                                <img v-else-if="data.deviceType === '2'" src="../../../assets/meter0.png"
                                    style="width: 18px; height: 18px" />

                                <!-- 煤气表 -->
                                <img v-else-if="data.deviceType === '3'" src="../../../assets/rqb.png"
                                    style="width: 20px; height: 20px" />

                                <span :title="node.label" class="custom-tree-node"> {{ node.label }}</span>
                            </template>
                        </el-tree>
                    </div>
                </el-card>
            </el-col>
            <!-- 遥测站信息 -->
            <el-col :span="20" :xs="24">
                <el-card>
                    <template #header>
                        <div class="card-header">
                            <!-- <span style="font-size:20px;">遥测站</span> -->
                            <span style="font-size:20px;color: green;" v-show="state.selectNode.id">{{
                                state.selectNode.label
                            }}</span>
                            <!-- 站点二维码 -->
                            <vue-qr v-if="state.selectNode.type === '2'" :text="state.selectNode.code" :size="35">
                            </vue-qr>
                        </div>
                    </template>
                    <el-table v-loading="loading" :data="state.tableData" border stripe style="width: 100%" ref="my_table"
                        :height="tableHeight" highlight-current-row @cell-dblclick="celldblclick"
                        @current-change="handleCurrentRowChange"
                        :header-cell-style="{ background: '#FF000000', color: '#000000' }">

                        <el-table-column fixed type="index" width="50" align="center" />

                        <!-- 先改成和工作数据一样的列了,内部方便看数据(后面一样是内部看详细,客户看简要) 2022-07-08 guozhao -->
                        <el-table-column fixed prop="deviceSn" label="设备" header-align="center" width="180">
                            <template #default="scope">
                                <el-space direction="vertical" alignment="start">
                                    <span :title="scope.row.stationName" @click="stationNameClick(scope.row)"
                                        v-if="state.queryType !== 2"
                                        style="color: blue;display: inline-block;font-size: 0.95em;cursor:pointer;text-decoration: underline;text-underline-offset: 3px;">{{
                                            scope.row.stationName
                                        }}</span>
                                    <span :title="scope.row.stationName" v-if="state.queryType === 2"
                                        style="color: black;font-size: 0.95em;">{{
                                            scope.row.stationName
                                        }}</span>
                                    <div style="display: flex;align-items: center;">
                                        <span title="点击查看设备配置" @click="showDevCfg(scope.row)"
                                        style="color: blue;display: inline-block;font-size: 0.95em;cursor:pointer;text-decoration: underline;text-underline-offset: 3px;">{{
                                            'SN:&nbsp' + scope.row.deviceSn
                                        }}</span>
                                    <el-icon style="margin-left: 8px;cursor: pointer;" title="点击快速添加远程配置任务" @click="openRemoteCfg(scope.row)" v-if="userType === '0'">
                                        <Tools/>
                                    </el-icon>
                                    </div>

                                    <span style="color: black;font-size: 0.95em;">{{
                                        'ID&nbsp&nbsp:&nbsp' + scope.row.stationCode
                                    }}</span>
                                    <!-- <el-tag size="small" style="width: 110px">SN:<span style="color: blue">{{
                                            scope.row.deviceSn
                                    }}</span></el-tag>
                                    <el-tag size="small" style="width: 110px">ID:<span style="color: green">{{
                                            scope.row.stationCode
                                    }}</span></el-tag> -->

                                    <!-- <el-tag size="small" style="width: 110px">MC:<span :title="scope.row.stationName"
                                            style="color: green;width: 63px;display: inline-block;">{{
                                                    scope.row.stationName != null && scope.row.stationName.length > 5 ?
                                                        scope.row.stationName.substring(0, 5) + '...' : scope.row.stationName
                                            }}</span>
                                    </el-tag> -->
                                </el-space>
                            </template>
                        </el-table-column>

                        <!-- <el-table-column fixed prop="deviceSn" label="设备SN" header-align="center" width="120" /> -->
                        <el-table-column label="图片" header-align="center" width="150" resizable="false">
                            <template #default="scope">
                                <div style="display: flex; align-items: center;">
                                    <el-image :src="scope.row.src" :preview-src-list="scope.row.srcList"
                                        :title="global.getImageNameTip(scope.row.smallJpgUrl)" :hide-on-click-modal="true"
                                        :close-on-press-escape="true" slot="error"
                                        :style="!tool.stringIsNullOrEmpty(scope.row.src) && scope.row.src.includes('bmp') ? 'border:1.5px solid #F00;' : ''">
                                        <template #error>
                                            <div slot="error" class="image-slot">
                                                <!-- <el-icon><icon-picture /></el-icon> -->
                                                <i class="el-icon-picture-outline"
                                                    style="font-size: 30px;text-align: center;display: block;width: 120px;"></i>
                                                <span style="color: red;text-align: center;display: block;"
                                                    v-if="scope.row.funCode === '52'">补发报(无图)</span>
                                                <span style="color: red;display:inline-block;width:120px;text-align:center;"
                                                    v-if="scope.row.funCode !== '52'">图片异常</span>
                                            </div>
                                        </template>
                                    </el-image>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="读数信息" header-align="center" width="135">
                            <template #default="scope">
                                <el-space direction="vertical" alignment="start">
                                    <el-tag size="small">结果：<span style="color: blue">{{ global.formatDecimal(userType
                                        === '0' ? scope.row.identValue : scope.row.resultValue,
                                        scope.row.decimalDigits)
                                    }}</span>
                                        <span v-if="scope.row.deviceType === '2'">&nbsp;{{ scope.row.deviceUnitName
                                        }}</span>
                                    </el-tag>
                                    <el-tag size="small" v-if="userType === '0' && scope.row.deviceType !== '2'">
                                        原始：<span style="color: green">{{
                                            global.formatDecimal(scope.row.rawValue, scope.row.decimalDigits)
                                        }}</span>
                                    </el-tag>
                                    <el-tag size="small"
                                        v-if="userType === '0' && scope.row.serverReadModel !== null && scope.row.serverReadModel.goodFlag !== '4' && scope.row.deviceType !== '2'">服务：<span
                                            style="color: red;cursor:pointer;" @click="openServerImage(scope.row)">{{
                                                global.getGoodFlagContent(scope.row.serverReadModel,
                                                    scope.row.decimalDigits)
                                            }}</span>
                                    </el-tag>

                                    <!-- 下面是内部用户发现服务侧识别显示没有配置时可快速创建召测配置 -->
                                    <el-tag size="small"
                                        v-if="userType === '0' && scope.row.serverReadModel !== null && scope.row.serverReadModel.goodFlag === '4' && scope.row.deviceType !== '2'">服务：<span
                                            @click="createTaskDown(scope.row)"
                                            style="color: red;cursor:pointer;text-decoration: underline;font-size: 15px;text-underline-offset: 3px;font-weight: bold;">{{
                                                global.getGoodFlagContent(scope.row.serverReadModel,
                                                    scope.row.decimalDigits)
                                            }}</span>
                                    </el-tag>
                                </el-space>
                            </template>
                        </el-table-column>
                        <el-table-column label="时间" header-align="center" width="186">
                            <template #default="scope">
                                <el-space direction="vertical" alignment="start">
                                    <!-- <el-tag size="small" style="font-weight: bold;width: 158px">采样：<span
                                            style="color: blue;font-weight: bold;">{{
                                                    tool.dateFormatYMDHm(scope.row.sampleTime)
                                            }}</span></el-tag>
                                    <el-tag size="small" v-if="userType === '0'">发报：<span style="color: green">{{
                                            tool.dateFormat(scope.row.rptTime)
                                    }}</span>
                                    </el-tag>
                                    <el-tag size="small" v-if="userType === '0'">接收：<span style="color: red">{{
                                            tool.dateFormat(scope.row.revTime)
                                    }}</span>
                                    </el-tag> -->
                                    <span style="color: blue;font-weight: normal;font-size: 0.95em;">{{
                                        "采样：" + tool.dateFormatYMDHm(scope.row.sampleTime, 'YYYYMMDDHHmmss', 'YY-MM-DD HH:mm:ss')
                                        }}<span v-if="scope.row.ip1SendStatus"
                                            :style="scope.row.ip1SendStatus == 1 ? 'color:limegreen' : 'color:red'"
                                            :title="global.getIp1SendStatusTip(scope.row.ip1SendStatus)">&nbsp●</span></span>
                                    <span style="color: green;font-size: 0.95em;">{{
                                        "发报：" + tool.dateFormat(scope.row.rptTime, 'YYYYMMDDHHmmss', 'YY-MM-DD HH:mm:ss')
                                    }}</span>
                                    <span style="color: #000000;;font-size: 0.95em;">{{
                                        "接收：" + tool.dateFormat(scope.row.revTime, 'YYYYMMDDHHmmss', 'YY-MM-DD HH:mm:ss')
                                    }}</span>
                                </el-space>
                            </template>
                        </el-table-column>
                        <el-table-column label="工作参数" header-align="center" width="110">
                            <template #default="scope">
                                <el-space direction="vertical" alignment="start">
                                    <!-- <el-tag size="small">信号：<span style="color: blue">{{ scope.row.rsrp }}</span>
                                    </el-tag>
                                    <el-tag size="small">电压：<span style="color: green">{{ scope.row.voltage }}</span>
                                    </el-tag>
                                    <el-tag size="small" v-if="userType === '0'">信噪比：<span style="color: red">{{
                                            scope.row.snr
                                    }}</span>
                                    </el-tag> -->
                                    <span style="color: blue;font-size: 0.95em;"
                                        :title="`NB位置信息:${scope.row.nbRegLocation}`">{{ "信号&nbsp&nbsp&nbsp&nbsp：" +
                                            scope.row.rsrp

                                        }}</span>
                                    <span style="color: green;font-size: 0.95em;"
                                        :title="`电池运行时间:${scope.row.batRumTime}`">{{ "电压&nbsp&nbsp&nbsp&nbsp：" +
                                            scope.row.voltage

                                        }}</span>
                                    <span v-if="userType === '0'" style="color: black;font-size: 0.95em;">信噪比&nbsp：{{
                                        scope.row.snr
                                    }}</span>
                                </el-space>
                            </template>
                        </el-table-column>

                        <el-table-column label="工作情况" header-align="center" width="100" v-if="userType === '0'">
                            <template #default="scope">
                                <el-space direction="vertical" alignment="start">
                                    <span style="color: blue;font-size: 0.95em;">{{ "工作:" +
                                        tool.getValueFormat(scope.row.intervalMinutes, 's')
                                    }}</span>
                                    <span style="color: green;font-size: 0.95em;">{{ "传输:" +
                                        tool.getValueFormat(scope.row.tranDuration, 's')
                                    }}</span>
                                    <span
                                        :style="scope.row.loseFlag === '1' ? 'color: Red;font-size: 0.95em;font-weight: bold' : 'color: black;font-size: 0.95em;'">{{
                                            "计次:" +
                                            tool.getValueFormat(scope.row.mcuRunNum, '')
                                        }}</span>
                                </el-space>
                            </template>
                        </el-table-column>

                        <el-table-column label="设备版本" header-align="center" width="180">
                            <template #default="scope">
                                <el-space direction="vertical" alignment="start">
                                    <el-tag size="small">MCU：<span style="color: blue">{{ scope.row.softVer
                                    }}</span></el-tag>
                                    <el-tag size="small">AI&nbsp&nbsp&nbsp&nbsp：<span style="color: green">{{
                                        scope.row.aiVersion
                                    }}</span></el-tag>
                                    <el-row v-if="userType === '0'">
                                        <el-col :span="13">
                                            <el-tag size="small">CPU：<span style="color: red">{{ scope.row.hardVersion
                                            }}</span></el-tag>
                                        </el-col>
                                        <el-col :span="11">
                                            <el-tag size="small" style="width: 75px;">NB：<span style="color: red">{{
                                                scope.row.nbVersion
                                            }}</span></el-tag>
                                        </el-col>
                                    </el-row>
                                    <!-- <div style="color: #606266;font-size: 0.95em;">MCU：
                                        <span style="color: green">{{scope.row.softVer
                                        }}</span>
                                    </div>
                                    <div style="color: #606266;font-size: 0.95em;">AI&nbsp&nbsp&nbsp&nbsp&nbsp：
                                        <span style="color: green">{{ 
                                            scope.row.aiVersion
                                        }}</span>
                                    </div>
                                    <el-row v-if="userType === '0'">
                                        <el-col>
                                            <div>
                                                <span style="font-size: 0.95em;width: 1px;">CPU \ NB：</span>
                                                <span style="color: green">{{ scope.row.hardVersion + ' \\ ' + scope.row.nbVersion
                                                }}</span>
                                            </div>
                                        </el-col>

                                    </el-row> -->
                                </el-space>
                            </template>
                        </el-table-column>
                        <el-table-column fit label="调试信息" header-align="center" width="400" v-if="userType === '0'">
                            <template #default="scope">
                                <el-row>
                                    <el-col>
                                        <span style="font-size:12px;" v-for="(item, i) in scope.row.alist">{{
                                            global.debugInfoFormat(item, i)
                                        }}</span>
                                    </el-col>
                                </el-row>

                                <el-row>
                                    <el-col>
                                        <span style="font-size:12px;" v-for="(item, i) in scope.row.blist">{{
                                            global.debugInfoFormat(item, i)
                                        }}</span>
                                    </el-col>
                                </el-row>
                                <el-row v-if="scope.row.serverAList">
                                    <el-divider style="margin-top: -2px;margin-bottom: -5px;height: 1px;" />
                                </el-row>
                                <el-row v-if="scope.row.serverAList">
                                    <el-col>
                                        <span style="font-size:12px;" v-for="(item, i) in scope.row.serverAList">{{
                                            global.debugInfoFormat(item, i)
                                        }}</span>
                                    </el-col>
                                </el-row>

                                <el-row v-if="scope.row.serverAList">
                                    <el-col>
                                        <span style="font-size:12px;" v-for="(item, i) in scope.row.serverBList">{{
                                            global.debugInfoFormat(item, i)
                                        }}</span>
                                    </el-col>
                                </el-row>
                                <!-- <el-descriptions direction="vertical" :column="12" :size='10'>
                                    <div v-for="(item, index) in scope.row.alist">
                                        <el-descriptions-item :label=item label-align="center" align=center>{{
                                        scope.row.blist[index]
                                        }}
                                        </el-descriptions-item>
                                    </div>
                                </el-descriptions> -->
                            </template>
                        </el-table-column>
                    </el-table>

                    <el-config-provider :locale="locale">
                        <el-pagination v-model:currentPage="tairead_queryParams.page"
                            :default-page-size="tairead_queryParams.rows" v-model:page-size="tairead_queryParams.rows"
                            :page-sizes="[10, 15, 20, 50, 100]" :small="state.small"
                            :disabled="state.disabled || selectNode.type !== '2'" :background="state.background"
                            layout="total, sizes, prev, pager, next, jumper" :total="state.total"
                            style="text-align: center; margin-top: 10px; height: 30px" @size-change="handleSizeChange"
                            @current-change="handleCurrentChange" />
                    </el-config-provider>
                </el-card>
            </el-col>
        </el-row>

        <el-dialog :title="cfgdialog.title" v-model="cfgdialog.visible" width="1500px" center>
            <DevCfgDialog :stationCode="state.cfgData.stationCode" :deviceSn="state.cfgData.deviceSn"
                v-if="cfgdialog.visible"></DevCfgDialog>
        </el-dialog>
        <el-dialog width="1300px" :title="CfgFormDialog.title" v-model="CfgFormDialog.visible" center>
            <CfgForm :device-sn="state.cfgData.deviceSn" @change="childMethod" v-if="CfgFormDialog.visible"/>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, toRefs, onMounted } from "vue";
import TAireadAction from "@/api/tairead";
import StationAccAction from "@/api/station/stationacc"
import { GroupAndStationTree, StationGroupModel, StationAccModel, StationGroupQueryParam, TAireadModel, TAireadQueryParam, PageResult, UnitQueryParam, TUsingunitGroupModel, TAffiliatedunitModel, TAffiliatedunitQueryParam, TTaskDown, Dialog, TServerReadModel } from "@/types";
import arrayToTree from "array-to-tree";
import tool from "@/until/tool"
import Moment from "moment";
import { ElMessage, ElMessageBox } from "element-plus";
import zhCn from "element-plus/lib/locale/lang/zh-cn";
import type Node from "element-plus/es/el-tree/src/model/node";
import TAffAction from "@/api/customermanagement/taffiliatedunit";
import { watch } from 'vue';
import global from "@/until/global";
import TTaskDownAction from "@/api/downlinktask/ttaskdown";
import DevCfgDialog from "@/components/devcfg/index.vue";
import vueQr from 'vue-qr/src/packages/vue-qr.vue';
import CfgForm from '@/components/remotecfg/index.vue';

let locale = ref(zhCn);

const my_table = ref();
//const tableHeight = ref(document.documentElement.clientHeight - 280);
const tableHeight = ref(document.documentElement.clientHeight - 185);
const loading = ref(false);
// const defaultDate = new Date();
const tree_loading = ref(false);
const currentRow = ref();
const tree: any = ref(null);
const selectUnit = ref(null);
let userType = localStorage.getItem("UserType") + '';
let pageSize = (localStorage.getItem("PageSize") == null ? 10 : localStorage.getItem("PageSize") as unknown as number) * 1;

const handleRefresh = () => {
    state.groupData = [] as GroupAndStationTree[];
    state.tableData = [] as TAireadModel[];
    state.group_queryParams = { page: 1, rows: pageSize, customerId: localStorage.getItem("CustomerId"), groupCode: "1" } as StationGroupQueryParam;
    state.tairead_queryParams = { page: 1, rows: pageSize } as TAireadQueryParam;
    state.total = 0;
    state.selectNode = {} as GroupAndStationTree;
    state.unitQueryParam = { page: 1, rows: pageSize } as UnitQueryParam;
    queryTreeList();
};

const state = reactive({
    total: 0,
    small: false,
    background: true,
    disabled: false,
    searchDisabled: false,
    groupData: [] as GroupAndStationTree[],
    group_queryParams: { page: 1, rows: pageSize, customerId: localStorage.getItem("CustomerId"), groupCode: "1" } as StationGroupQueryParam,
    tairead_queryParams: { page: 1, rows: pageSize } as TAireadQueryParam,
    tableData: [] as TAireadModel[],
    selectNode: {} as GroupAndStationTree,
    unitQueryParam: { page: 1, rows: pageSize } as UnitQueryParam,
    queryType: 0,
    stationNum: 0,
    filterText: "",
    isSearch: false,
    queryUnitCode: "",
    unitData: [] as TAffiliatedunitModel[],                 //筛选过滤的
    unitDataAll: [] as TAffiliatedunitModel[],               //全部单位
    cfgdialog: {} as Dialog,
    cfgData: {} as TAireadModel,
    CfgFormDialog: {} as Dialog,
    // defaultTime: [] as string[],
    // defaultTime: [Moment(defaultDate.getTime() - 1000 * 3600 * 24 * 7).format("YYYY-MM-DD HH:mm:ss"), Moment(defaultDate).format("YYYY-MM-DD HH:mm:ss"),],
});

const {
    groupData,
    total,
    group_queryParams,
    tairead_queryParams,
    tableData,
    selectNode,
    cfgdialog,
    CfgFormDialog,
} = toRefs(state);

const defaultProps = {
    children: "children", //"children"内的每个对象解析为一个子项;
    label: "label", //所有"label"所在的对象解析为一个父项
};

const handleCurrentRowChange = (val: StationAccModel | StationGroupModel | undefined) => {
    currentRow.value = val;
};

const handleNodeClick = (node: GroupAndStationTree) => {
    state.selectNode = node;
    state.group_queryParams.groupCode = node.code;

    if (node.type === "2") {
        //state.defaultTime = [Moment((new Date()).getTime() - 1000 * 3600 * 24 * 7).format("YYYY-MM-DD HH:mm:ss"), Moment((new Date())).format("YYYY-MM-DD HH:mm:ss"),];
        state.tairead_queryParams.startTime = Moment((new Date()).getTime() - 1000 * 3600 * 24 * 90).format("YYYYMMDDHHmmss");// tool.dateFormat(state.defaultTime[0].toString(), "YYYY-MM-DD HH:mm:ss", "YYYYMMDDHHmmss");
        state.tairead_queryParams.endTime = Moment((new Date())).format("YYYYMMDDHHmmss");// tool.dateFormat(state.defaultTime[1].toString(), "YYYY-MM-DD HH:mm:ss", "YYYYMMDDHHmmss");
        //state.tairead_queryParams.stationCode = (node.data as StationAccModel).stationCode;
        state.tairead_queryParams.stationCode = node.code;
        state.tairead_queryParams.page = 1;
        state.queryType = 2;
        queryData();
        if (Object.keys(my_table).length > 0) { if (my_table.value != null) { (my_table.value as any).$refs.bodyWrapper.scrollTop = 0; } }
    }
    else if (node.type === "0") {
        //一级
        state.queryType = 0;
        state.unitQueryParam.type = 1;
        state.tairead_queryParams.page = 1;
        state.unitQueryParam.code = node.code;
        state.unitQueryParam.page = 1;
        state.unitQueryParam.rows = 1000;
        queryDataByStationCodes();
        if (Object.keys(my_table).length > 0) { if (my_table.value != null) { (my_table.value as any).$refs.bodyWrapper.scrollTop = 0; } }
    }
    else if (node.type === "1" || node.parentcode !== '0') {
        //二级+
        //let model=node.data as TUsingunitGroupModel;
        state.queryType = 1;
        state.unitQueryParam.type = 2;
        state.unitQueryParam.code = node.code;
        state.unitQueryParam.page = 1;
        state.tairead_queryParams.page = 1;
        state.unitQueryParam.rows = 1000;
        queryDataByStationCodes();
        if (Object.keys(my_table).length > 0) { if (my_table.value != null) { (my_table.value as any).$refs.bodyWrapper.scrollTop = 0; } }
    }
};

const queryData = () => {
    loading.value = true;
    TAireadAction.QueryTAireadListByStation(state.tairead_queryParams)
        .then((result) => {
            if (result.status === 200) {
                const { res, flag, error } = result.data;
                if (flag === "1") {
                    const pageData = res as PageResult<TAireadModel[]>;

                    pageData.list.forEach(element => {
                        element.srcList = [];
                        element.alist = [];
                        element.blist = [];
                        if (element.smallJpgUrl) {
                            element.src = element.smallJpgUrl;
                            element.srcList.push(element.smallJpgUrl);
                        }

                        if (element.bigJpgUrl) {
                            element.src = element.bigJpgUrl;
                            element.srcList.push(element.bigJpgUrl);
                        }

                        if (element.szsbz) {
                            let alist = element.szsbz.split(",");
                            element.alist = alist;
                        }

                        if (element.szsbgl) {
                            let blist = element.szsbgl.split(",");

                            element.blist = blist;
                        }

                        if (element.serverReadModel != null) {
                            if (!tool.stringIsNullOrEmpty(element.serverReadModel.jpgUrl)) {
                                element.srcList.push(element.serverReadModel.jpgUrl);
                            }

                            if (!tool.stringIsNullOrEmpty(element.serverReadModel.smallJpgUrl)) {
                                element.srcList.push(element.serverReadModel.smallJpgUrl);
                            }
                            if (element.serverReadModel.szsbz) {
                                element.serverAList = element.serverReadModel.szsbz.split(",");
                            }
                            if (element.serverReadModel.szsbgl) {
                                element.serverBList = element.serverReadModel.szsbgl.split(",");
                            }
                        }
                    });

                    state.tableData = pageData.list;
                    state.total = pageData.total;
                    loading.value = false;

                } else {
                    ElMessage.warning(error);
                    loading.value = false;
                }
            }
            else {
                loading.value = false;
            }
        })
        .catch((error) => {
            //请求失败时的操作
            ElMessage.error(error || "未知异常...");
            loading.value = false;
        });
}

const queryDataByStationCodes = () => {
    loading.value = true;
    TAireadAction.QueryLatestDataByStation(state.unitQueryParam)
        .then((result) => {
            if (result.status === 200) {
                const { res, flag, error } = result.data;
                if (flag === "1") {
                    const pageData = res as PageResult<TAireadModel[]>;

                    pageData.list.forEach(element => {
                        element.srcList = [];
                        element.alist = [];
                        element.blist = [];
                        if (element.smallJpgUrl) {
                            element.src = element.smallJpgUrl;
                            element.srcList.push(element.smallJpgUrl);

                            //把BMP图加到预览列表 2022-11-09 guozhao
                            // if (element.picType && element.picType === 1) {
                            //     element.srcList.push(element.smallJpgUrl.replace('.jpg','.bmp'));
                            // }
                        }

                        if (element.bigJpgUrl) {
                            element.src = element.bigJpgUrl;
                            element.srcList.push(element.bigJpgUrl);
                        }

                        if (element.szsbz) {
                            let alist = element.szsbz.split(",");
                            element.alist = alist;
                        }

                        if (element.szsbgl) {
                            let blist = element.szsbgl.split(",");

                            element.blist = blist;
                        }
                        if (element.serverReadModel != null) {
                            // if (!tool.stringIsNullOrEmpty(element.serverReadModel.jpgUrl)) {
                            //     element.srcList.push(element.serverReadModel.jpgUrl);
                            // }
                            // if (!tool.stringIsNullOrEmpty(element.serverReadModel.smallJpgUrl)) {
                            //     element.srcList.push(element.serverReadModel.smallJpgUrl);
                            // }
                            if (element.serverReadModel.szsbz) {
                                element.serverAList = element.serverReadModel.szsbz.split(",");
                            }
                            if (element.serverReadModel.szsbgl) {
                                element.serverBList = element.serverReadModel.szsbgl.split(",");
                            }
                        }
                    });

                    state.tableData = pageData.list;
                    state.total = pageData.total;
                    loading.value = false;

                } else {
                    ElMessage.warning(error);
                    loading.value = false;
                }
            }
            else {
                loading.value = false;
            }
        })
        .catch((error) => {
            //请求失败时的操作
            ElMessage.error(error || "未知异常...");
            loading.value = false;
        });
}

const queryTreeList = () => {
    state.groupData = [] as GroupAndStationTree[];
    let ax = null;
    if (state.queryUnitCode) {
        ax = StationAccAction.QueryStationTreeByUnitCode(state.queryUnitCode);
    } else if (userType === '0') {
        ax = StationAccAction.QueryAllStationTree();
    } else {
        let userId = localStorage.getItem("CustomerId") + '';
        ax = StationAccAction.QueryStationTree(userId)
    }

    ax.then((result) => {
        if (result.status === 200) {
            const { res, flag, error } = result.data;
            if (flag === "1") {
                if (res !== null) {
                    let treeArray = res as GroupAndStationTree[];
                    let treeArrayNew = [] as GroupAndStationTree[];
                    state.stationNum = 0;
                    treeArray.forEach(eleme => {
                        treeArrayNew.push(eleme);
                        //console.log(eleme);
                        if (eleme.type === '2') {
                            state.stationNum++;
                        }
                    });

                    state.groupData = arrayToTree(treeArrayNew, {
                        parentProperty: "parentcode",
                        customID: "code",
                        childrenProperty: "children",
                    });
                }
            } else {
                ElMessage.error(error || "未知异常...")
            }
        }
    })
        .catch((error) => {
            //请求失败时的操作
            ElMessage.error(error || "未知异常...")
        });
};

const handleSizeChange = (val: number) => {
    if (state.queryType === 2) {
        state.tairead_queryParams.rows = val;
        queryData();
    } else {
        state.unitQueryParam.rows = val;
        queryDataByStationCodes();
    }
    localStorage.setItem("PageSize", val.toString());
};

const handleCurrentChange = (val: number) => {
    if (state.queryType === 2) {
        state.tairead_queryParams.page = val;
        queryData();
    } else {
        state.unitQueryParam.page = val;
        queryDataByStationCodes();
    }
    if (Object.keys(my_table).length > 0) { if (my_table.value != null) { (my_table.value as any).$refs.bodyWrapper.scrollTop = 0; } }
};

onMounted(() => {
    window.onresize = function () {
        //tableHeight.value = document.documentElement.clientHeight - 280;
        tableHeight.value = document.documentElement.clientHeight - 185;
    };
    handleRefresh();
    queryUnit();
});

//监听树筛选条件
watch(() => state.filterText, (val) => { tree.value!.filter(val); }, { deep: true })

const filterNode = (value: string, data: GroupAndStationTree) => {
    if (!value) return true;
    if (global.isChinese(value)) {
        return data.label.includes(value);
    } else {
        if (data.labelpy == null) {
            return false;
        } else {
            return data.labelpy.includes(value.toUpperCase());
        }
    }
}

//过滤单位下拉框
const filterUnit = (value: string) => {
    if (!value) {
        state.unitData = { ...state.unitDataAll };
        return;
    }
    if (global.isChinese(value)) {
        state.unitData = state.unitDataAll.filter(s => s.unitName.includes(value));
    } else {
        state.unitData = state.unitDataAll.filter(s => s.unitNamePy != null && s.unitNamePy.includes(value.toUpperCase()));
    }
}

//查询单位列表
const queryUnit = () => {
    let queryModel = {} as TAffiliatedunitQueryParam;
    TAffAction.QueryTAffiliatedunitList(queryModel).then(result => {
        if (result.status === 200) {
            const { res, flag, error } = result.data;
            if (flag === "1") {
                const pageData = res as PageResult<TAffiliatedunitModel[]>;
                state.unitDataAll = pageData.list;
                state.unitData = { ...state.unitDataAll };
            } else {
                ElMessage.error(error);
            }
        }
        loading.value = false;
    }).catch(error => {
        //请求失败时的操作     
        ElMessage.error(error);
        loading.value = false;
    })
}

//站点名称点击事件
const stationNameClick = (row: any) => {
    if (row && state.selectNode && state.selectNode.children !== undefined) {
        let model = row as TAireadModel;
        state.selectNode.children.forEach(s => {
            if (s.code === model.stationCode) {
                handleNodeClick(s);
                tree.value.setCurrentKey(s.id);
            }
        })
    }
}

//创建召测配置的下行任务
const createTaskDown = (row: any) => {
    let model = row as TAireadModel;
    ElMessageBox.confirm(
        ' 是否快速创建[' + model.stationName + ']的召测配置任务? ',
        '提示',
        {
            cancelButtonText: '取消',
            confirmButtonText: '确认',
            type: 'warning',
            center: true,
        }
    ).then(() => {
        let addModel = {} as TTaskDown;
        addModel.createMan = localStorage.getItem("UserName") + "";
        addModel.deviceSn = model.deviceSn;
        addModel.stationCode = model.stationCode;
        addModel.taskType = '3';
        addModel.finishedFlag = '0';
        addModel.taskLevel = 2;
        TTaskDownAction.AddTTaskDown(addModel).then((result) => {
            const { res, flag, error } = result.data;
            if (flag === "1") {
                ElMessage.success("新增召测配置任务成功");
            }
            else {
                ElMessage.warning(error);
            }
        });
    })
        .catch(() => {
        })
};

//显示参数配置
const showDevCfg = (row: any) => {
    state.cfgData = row as TAireadModel;

    state.cfgdialog = {
        title: "设备参数预览[" + state.cfgData.deviceSn + "]",
        visible: true,
        disabled: false,
    };
}

//双击复制调试信息
const celldblclick = (row: any, column: any, cell: any, event: any) => {
    let colInfo = JSON.parse(JSON.stringify(column));
    if (event.type === "dblclick" && colInfo.label === '调试信息') {
        let airead = row as TAireadModel;
        var save = function (e: any) {
            let strC = airead.alist + '\r\n' + airead.blist;

            e.clipboardData.setData('text/plain', strC);
            //e.clipboardData.setData('text/plain',event.target.innerText); 
            e.preventDefault();//阻止默认行为
        }
        document.addEventListener('copy', save);
        document.execCommand("copy");
        document.removeEventListener('copy', save);
        ElMessage.success("复制成功");
    }
}

//新标签页打开服务侧图片
const openServerImage = (row: any) => {
    window.open(row.serverReadModel.jpgUrl, "_blank")
}

const openRemoteCfg = (row: any) => {
    state.cfgData = row as TAireadModel;
    state.CfgFormDialog = {
        title: "远程配置[" + state.cfgData.deviceSn + "]",
        visible: true,
        disabled: false,
    };
}

//子组件保存或取消的返回值
const childMethod = (val: Boolean) => {
    state.CfgFormDialog = {
        title: "",
        visible: false,
        disabled: true,
    };
}
</script>

<style lang="scss" scoped>
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 25px;
}

.div {
    height: calc(100vh - 140px);
}

.tree {
    overflow-y: scroll;
    overflow-x: auto;
    width: 100%;
    height: calc(100vh - 140px);
    overflow: auto;
}

::v-deep .el-tree-node.is-current>.el-tree-node__content {
    background-color: rgb(255, 255, 255);
    color: rgb(64, 158, 255);
    font-weight: bold;
}

.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 16px;
    padding-right: 0px;
    margin-left: 5px;
}

.el-dropdown-link {
    cursor: pointer;
    color: var(--el-color-primary);
    display: flex;
    align-items: center;
}

.el-card ::v-deep .el-card__header {
    padding: 10px 10px;
    background-color: white;
}

.el-card ::v-deep .el-card__body {
    padding: 1px;
    background-color: white;
}

.el-icon-my-export {
    background: url("~@/assets/meter0.png") center no-repeat;
    background-size: cover;
}

// .el-table th.el-table__cell {
//     overflow: hidden;
//     -webkit-user-select: none;
//     -moz-user-select: none;
//     user-select: none;
//     background-color: #FFF;
//     background: cadetblue;
//     color: #000;
//     border: 1px solid rosybrown;
//     font-size: 20px;
//     text-align: center;
// }
</style>