<template>
    <div>
        <el-card>
            <div class="flowBox" style="height: 100%">
                <div class="flowTopBox" v-loading="saveLoading">
                    <div class="leftFlowBox">
                        <el-scrollbar>
                            <div style="height: 100%" class="flowdiv">
                                <el-input v-model="filterCatalogueText" placeholder="search" />
                                <br />
                                <br />
                                <el-tree ref="catalogueTreeRef" :data="catalogueTreeList" default-expand-all
                                    node-key="id" :filter-node-method="filterNode">
                                    <template #default="{ node, data }">
                                        <div v-if="data.ifLeaf == '1'" class="flow-tree-node">
                                            <span>
                                                <img v-show="data.ifLeaf == '1'" src="@/assets/folder.png" />
                                                <span style="margin-left: 8px">{{ data.name }}</span>
                                            </span>
                                        </div>
                                        <div v-else @mousedown="startDrag(data)" class="flow-tree-drag—node">
                                            <span>
                                                <img v-show="data.taskType == '4'" src="@/assets/flinkenv.png" />
                                                <img v-show="data.taskType == '3'" src="@/assets/jar.png" />
                                                <img v-show="data.taskType == '2'" src="@/assets/flink.png" />
                                                <img v-show="data.taskType == '1'" src="@/assets/sql.png" />
                                                <span style="margin-left: 8px">{{ data.name }}</span>
                                            </span>
                                        </div>
                                    </template>
                                </el-tree>
                            </div>
                        </el-scrollbar>
                    </div>
                    <div class="rightFlowBox">
                        <div style="height: 800px; width: 100%" @dragover="allowDropOver" ref="flowContainer"
                            id="flowContainer"></div>
                    </div>
                </div>
                <!-- 上下侧边 -->
                <div v-show="runFlag" title="上下侧边栏" class="flowBottomResize"></div>
                <div class="flowBottomBox" v-show="runFlag"></div>
            </div>
        </el-card>

        <!-- 下载流程图 -->
        <div id="snapshotDownloadId" v-show="false"></div>

        <!-- 节点框 -->
        <el-drawer :visible.sync="nodeVisable" direction="rtl" :append-to-body="true" size="45%">
            <template #header>
                <h4>编辑调度</h4>
            </template>
            <template #default>
                <el-card class="scene-config-dialog" style="margin: 20px; width: 800px" shadow="never">
                    <el-form ref="nodeDataFormRef" :model="form" :rules="rules" label-width="90px">
                        <el-row :gutter="50">
                            <el-col :span="12">
                                <el-form-item :label="$t('alert.index.236501-18')" prop="sceneName">
                                    <el-input v-model="form.sceneName" :placeholder="$t('alert.scene-list.591934-2')" />
                                </el-form-item>
                                <el-form-item :label="$t('scene.index.670805-8')">
                                    <el-switch v-model="form.enable" :active-value="1" :inactive-value="2" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item :label="$t('alert.index.236501-11')" prop="remark">
                                    <el-input v-model="form.remark" type="textarea" rows="4"
                                        :placeholder="$t('plzInput')" />
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <div style="height: 1px; background-color: #ddd; margin: 0 0 20px 0"></div>
                        <div class="condition-wrap" v-if="nodeDataForm.properties.props == 'condition'">
                            <el-form-item :label="$t('scene.index.670805-9')" prop="triggers">
                                <div class="item-wrap" style="background-color: #eef3f7">
                                    <el-row :gutter="16">
                                        <el-col :span="24">
                                            <span>{{ $t('scene.index.670805-10') }}</span>
                                            <el-select v-model="form.cond" :placeholder="$t('scene.index.670805-11')"
                                                size="small" style="width: 160px">
                                                <el-option key="1" :label="$t('alert.index.236501-20')" :value="1" />
                                                <el-option key="2" :label="$t('alert.index.236501-21')" :value="2" />
                                                <el-option key="3" :label="$t('scene.index.670805-12')" :value="3"
                                                    :disabled="formJson.triggers.length > 1" />
                                            </el-select>
                                            <span style="margin-left: 20px; font-size: 12px">{{
                                                $t('scene.index.670805-13') }}</span>
                                        </el-col>
                                    </el-row>
                                </div>
                                <div class="item-wrap" v-for="(item, index) in formJson.triggers" :key="index">
                                    <el-row :gutter="16">
                                        <el-col :span="5">
                                            <el-select v-model="item.source" :placeholder="$t('pleaseSelect')"
                                                size="small" @change="handleTriggerSource($event, index)">
                                                <el-option v-for="subItem in triggerSource" :key="subItem.value"
                                                    :label="subItem.label" :value="subItem.value"></el-option>
                                            </el-select>
                                        </el-col>
                                        <!-- {{ item.source }} -->
                                        <el-col :span="10" v-if="item.source == 1 || item.source == 6">
                                            <el-input readonly v-model="item.deviceCount" size="small"
                                                :placeholder="$t('product.product-things-model.142341-83')"
                                                style="margin-top: 3px">
                                                <span slot="prepend" disabled>{{ $t('scene.index.670805-14') }}</span>
                                                <el-button slot="append"
                                                    @click="handleSelectDevice('trigger', item, index)" size="small">{{
                                                        $t('firmware.index.222541-31') }}</el-button>
                                            </el-input>
                                        </el-col>
                                        <el-col :span="10" v-if="item.source == 3">
                                            <el-input readonly v-model="item.productName" size="small"
                                                :placeholder="$t('device.allot-import-dialog.060657-1')"
                                                style="margin-top: 3px">
                                                <el-button slot="append"
                                                    @click="handleSelectProduct('trigger', item, index)" size="small">{{
                                                        $t('sip.product-list.998536-0') }}</el-button>
                                            </el-input>
                                        </el-col>
                                        <div class="delete-wrap" v-if="index != 0">
                                            <el-button size="small" plain type="danger" style="padding: 5px"
                                                icon="el-icon-delete" @click="handleRemoveTrigger(index)">{{ $t('del')
                                                }}</el-button>
                                        </div>
                                    </el-row>

                                    <!--定时-->
                                    <el-row v-if="item.source == 2" :gutter="16">
                                        <el-col :span="5">
                                            <el-time-picker v-model="item.timerTimeValue"
                                                :disabled="item.isAdvance == 1" format="HH:mm" size="small"
                                                style="width: 100%" :placeholder="$t('device.device-timer.433369-19')"
                                                @change="timeChange($event, index)"
                                                value-format="HH:mm"></el-time-picker>
                                        </el-col>
                                        <el-col :span="19">
                                            <el-select v-model="item.timerWeekValue" :placeholder="$t('pleaseSelect')"
                                                multiple style="width: 100%" @change="weekChange($event, index)"
                                                size="small" :disabled="item.isAdvance == 1">
                                                <el-option v-for="subItem in timerWeeks" :key="subItem.value"
                                                    :label="subItem.label" :value="subItem.value"></el-option>
                                            </el-select>
                                        </el-col>
                                        <el-col :span="5" style="margin-top: 5px">
                                            <el-checkbox v-model="item.isAdvance" :false-label="0" :true-label="1"
                                                border size="small" style="width: 100%"
                                                @change="customerCronChange(($event, index))">
                                                {{ $t('scene.index.670805-15') }}
                                            </el-checkbox>
                                        </el-col>
                                        <el-col :span="19" style="margin-top: 10px">
                                            <el-input v-model="item.cronExpression"
                                                :placeholder="$t('scene.index.670805-16')"
                                                :disabled="item.isAdvance == 0" size="small">
                                                <template slot="append">
                                                    <el-button :disabled="item.isAdvance == 0" type="primary"
                                                        @click="handleShowCron(item, index)">
                                                        {{ $t('scene.index.670805-17') }}
                                                        <i class="el-icon-time el-icon--right"></i>
                                                    </el-button>
                                                </template>
                                            </el-input>
                                        </el-col>
                                    </el-row>

                                    <div v-if="item.thingsModel && item.source != 5">
                                        <!--类型和父级物模型-->
                                        <el-row :gutter="16">
                                            <el-col :span="5">
                                                <el-select v-model="item.type"
                                                    :placeholder="$t('scene.index.670805-18')" size="small"
                                                    @change="handleTriggerTypeChange($event, index)">
                                                    <el-option v-for="(subItem, subIndex) in triggerTypes"
                                                        :key="subIndex + 'type'" :label="subItem.label"
                                                        :value="subItem.value"></el-option>
                                                </el-select>
                                            </el-col>

                                            <el-col :span="10">
                                                <el-select v-model="item.parentId" style="width: 100%"
                                                    :placeholder="$t('scene.index.670805-19')" size="small"
                                                    v-if="item.type === 1"
                                                    @change="handleTriggerParentModelChange($event, index)">
                                                    <el-option
                                                        v-for="(subItem, subIndex) in item.thingsModel.properties"
                                                        :key="subIndex + 'triggerProperty'" :label="subItem.name"
                                                        :value="subItem.id"></el-option>
                                                </el-select>
                                                <el-select v-model="item.parentId" style="width: 100%"
                                                    :placeholder="$t('scene.index.670805-19')" size="small"
                                                    v-else-if="item.type == 2"
                                                    @change="handleTriggerParentModelChange($event, index)">
                                                    <el-option v-for="(subItem, subIndex) in item.thingsModel.functions"
                                                        :key="subIndex + 'triggerFunc'" :label="subItem.name"
                                                        :value="subItem.id"></el-option>
                                                </el-select>
                                                <el-select v-model="item.parentId" style="width: 100%"
                                                    :placeholder="$t('scene.index.670805-19')" size="small"
                                                    v-else-if="item.type == 3"
                                                    @change="handleTriggerParentModelChange($event, index)">
                                                    <el-option v-for="(subItem, subIndex) in item.thingsModel.events"
                                                        :key="subIndex + 'triggerEvents'" :label="subItem.name"
                                                        :value="subItem.id"></el-option>
                                                </el-select>
                                            </el-col>
                                        </el-row>
                                        <el-row v-if="tpyeopen && item.source === 6">
                                            <el-col :span="6">
                                                <el-select v-model="item.energtype" placeholder="能源" size="small"
                                                    @change="handleTriggerEnergy($event, index, item)">
                                                    <el-option v-for="energy in energyList" :key="energy.id"
                                                        :label="energy.number" :value="energy.id"></el-option>
                                                </el-select>
                                            </el-col>
                                        </el-row>
                                        <!--数组索引/物模型/操作符和值-->
                                        <el-row :gutter="16">
                                            <el-col
                                                v-if="item.parentModel && item.parentModel.datatype.type === 'array'"
                                                :span="5">
                                                <el-select v-model="item.arrayIndex" :placeholder="$t('pleaseSelect')"
                                                    size="small" @change="handleTriggerIndexChange($event, index)">
                                                    <el-option v-for="subItem in item.parentModel.datatype.arrayModel"
                                                        :key="subItem.id" :label="subItem.name"
                                                        :value="subItem.id"></el-option>
                                                </el-select>
                                            </el-col>
                                            <el-col
                                                v-if="item.parentModel && item.parentModel.datatype.type === 'array' && item.parentModel.datatype.arrayType === 'object'"
                                                :span="5">
                                                <el-select v-model="item.id" :placeholder="$t('pleaseSelect')"
                                                    size="small" @change="handleTriggerModelChange($event, index)">
                                                    <el-option
                                                        v-for="(subItem, subIndex) in item.parentModel.datatype.params"
                                                        :key="subIndex" :label="subItem.name"
                                                        :value="subItem.id"></el-option>
                                                </el-select>
                                            </el-col>
                                            <el-col
                                                v-if="item.parentModel && item.parentModel.datatype.type === 'object'"
                                                :span="5">
                                                <el-select v-model="item.id" :placeholder="$t('pleaseSelect')"
                                                    size="small" @change="handleTriggerModelChange($event, index)">
                                                    <el-option
                                                        v-for="(subItem, subIndex) in item.parentModel.datatype.params"
                                                        :key="subIndex" :label="subItem.name"
                                                        :value="subItem.id"></el-option>
                                                </el-select>
                                            </el-col>
                                            <el-col
                                                v-if="item.model && (item.model.datatype.type === 'integer' || item.model.datatype.type === 'decimal' || item.model.datatype.type === 'string') && item.source !== 5"
                                                :span="5">
                                                <el-select v-model="item.operator"
                                                    :placeholder="$t('scene.index.670805-20')" size="small">
                                                    <el-option key="=" label="等于（=）" value="=" />
                                                    <el-option key="!=" label="不等于（!=）" value="!=" />
                                                    <el-option
                                                        v-if="item.model.datatype.type === 'integer' || item.model.datatype.type === 'decimal'"
                                                        key=">" label="大于（>）" value=">" />
                                                    <el-option
                                                        v-if="item.model.datatype.type === 'integer' || item.model.datatype.type === 'decimal'"
                                                        key="<" label="小于（<）" value="<" />
                                                    <el-option
                                                        v-if="item.model.datatype.type === 'integer' || item.model.datatype.type === 'decimal'"
                                                        key=">=" label="大于等于（>=）" value=">=" />
                                                    <el-option
                                                        v-if="item.model.datatype.type === 'integer' || item.model.datatype.type === 'decimal'"
                                                        key="<=" label="小于等于（<=）" value="<=" />
                                                    <el-option
                                                        v-if="item.model.datatype.type === 'integer' || item.model.datatype.type === 'decimal'"
                                                        key="between" label="在...之间（between）" value="between" />
                                                    <el-option
                                                        v-if="item.model.datatype.type === 'integer' || item.model.datatype.type === 'decimal'"
                                                        key="notBetween" label="不在...之间（notBetween）"
                                                        value="notBetween" />
                                                    <el-option v-if="item.model.datatype.type === 'string'"
                                                        key="contain" label="包含（contain）" value="contain" />
                                                    <el-option v-if="item.model.datatype.type === 'string'"
                                                        key="notContain" label="不包含（notContain）" value="notContain" />
                                                </el-select>
                                            </el-col>
                                            <el-col
                                                v-if="item.model && (item.model.datatype.type === 'integer' || item.model.datatype.type === 'decimal' || item.model.datatype.type === 'string') && item.source == 5"
                                                :span="5">
                                                <el-select v-model="item.operator" placeholder="请选择操作符" size="small">
                                                    <el-option key="+" label="加" value="+" />
                                                    <el-option key="-" label="减" value="-" />
                                                    <el-option key="*" label="乘" value="*" />
                                                    <el-option key="/" label="除" value="/" />
                                                </el-select>
                                            </el-col>
                                            <el-col :span="9" v-if="item.model">
                                                <div v-if="item.model.datatype.type === 'integer' || item.model.datatype.type === 'decimal'"
                                                    v-show="item.operator === 'between' || item.operator === 'notBetween'">
                                                    <el-input v-model="item.valueA" :max="item.model.datatype.max"
                                                        :min="item.model.datatype.min"
                                                        :placeholder="$t('scene.index.670805-21')" size="small"
                                                        style="width: 95px; vertical-align: baseline" type="number"
                                                        @input="valueChange($event, item)"></el-input>
                                                    <span style="padding: 0 3px; color: #999">-</span>
                                                    <el-input v-model="item.valueB" :max="item.model.datatype.max"
                                                        :min="item.model.datatype.min"
                                                        :placeholder="$t('scene.index.670805-21')" size="small"
                                                        style="width: 165px; vertical-align: baseline" type="number"
                                                        @input="valueChange($event, item)">
                                                        <template slot="append">{{ item.model.datatype.unit
                                                            }}</template>
                                                    </el-input>
                                                </div>

                                                <div v-if="item.model.datatype.type === 'integer' || item.model.datatype.type === 'decimal'"
                                                    v-show="item.operator !== 'between' && item.operator !== 'notBetween'">
                                                    <el-input style="vertical-align: baseline" v-model="item.value"
                                                        :placeholder="$t('scene.index.670805-21')" size="small">
                                                        <template slot="append">{{ item.model.datatype.unit
                                                            }}</template>
                                                    </el-input>
                                                </div>
                                                <div v-else-if="item.model.datatype.type === 'bool'">
                                                    <el-switch v-model="item.value"
                                                        :inactive-text="item.model.datatype.falseText"
                                                        :active-text="item.model.datatype.trueText" active-value="1"
                                                        inactive-value="0" size="mini"
                                                        style="vertical-align: sub"></el-switch>
                                                </div>
                                                <div v-else-if="item.model.datatype.type === 'enum'">
                                                    <el-select v-model="item.value" :placeholder="$t('pleaseSelect')"
                                                        style="width: 100%" size="small">
                                                        <el-option
                                                            v-for="(subItem, subIndex) in item.model.datatype.enumList"
                                                            :key="subIndex + 'things'" :label="subItem.text"
                                                            :value="subItem.value"></el-option>
                                                    </el-select>
                                                </div>
                                                <div v-else-if="item.model.datatype.type === 'string'">
                                                    <el-input v-model="item.value" :max="item.model.datatype.maxLength"
                                                        :placeholder="$t('scene.index.670805-22')" size="small" />
                                                </div>
                                            </el-col>
                                        </el-row>
                                    </div>
                                    <div v-for="(ite, inx) in item.sceneOperation" v-if="item.source == 5" :key="inx">
                                        <el-row :gutter="16">
                                            <el-col :span="11">
                                                <el-input v-model="ite.productName" placeholder="请选择设备" readonly
                                                    size="small" style="margin-top: 3px">
                                                    <span slot="prepend" disabled>名称</span>
                                                    <el-button slot="append" size="small"
                                                        @click="handleSelectDevice1('trigger', ite, inx, index)">选择设备</el-button>
                                                </el-input>
                                            </el-col>
                                            <el-col v-if="ite.thingsModel" :span="4">
                                                <el-select v-model="ite.id" placeholder="请选择父级物模型" size="small"
                                                    style="width: 100%"
                                                    @change="handleActionParentModelChange1($event, inx, ite, index, item)">
                                                    <el-option v-for="(subItem, subIndex) in ite.thingsModel.properties"
                                                        :key="subIndex + 'actionProperty'" :label="subItem.name"
                                                        :value="subItem.id"></el-option>
                                                </el-select>
                                            </el-col>
                                            <el-col v-if="ite.id && item.sceneOperation.length > inx + 1" :span="4">
                                                <el-select v-model="ite.operator" placeholder="请选择操作符" size="small"
                                                    @change="operatorChange(index)">
                                                    <el-option key="+" label="加" value="+" />
                                                    <el-option key="-" label="减" value="-" />
                                                    <el-option key="*" label="乘" value="*" />
                                                    <el-option key="/" label="除" value="/" />
                                                </el-select>
                                            </el-col>
                                            <el-col :span="5" style="float: right">
                                                <el-button icon="el-icon-plus" plain size="small" style="padding: 8px"
                                                    type="primary" @click="handleAddOne(index)">{{ $t('add')
                                                    }}</el-button>
                                                <el-button v-if="item.sceneOperation.length > 1" icon="el-icon-delete"
                                                    plain size="small" style="padding: 8px" type="danger"
                                                    @click="handleDelOne(index, inx)">
                                                    删除
                                                </el-button>
                                            </el-col>
                                        </el-row>
                                    </div>

                                    <div v-if="item.showOperator && item.source == 5">
                                        <el-row :gutter="16">
                                            <el-col :span="5">
                                                <el-select v-model="item.operator" placeholder="请选择操作符" size="small">
                                                    <el-option key="=" label="等于（=）" value="=" />
                                                    <el-option key="!=" label="不等于（!=）" value="!=" />
                                                    <el-option key=">" label="大于（>）" value=">" />
                                                    <el-option key="<" label="小于（<）" value="<" />
                                                    <el-option key=">=" label="大于等于（>=）" value=">=" />
                                                    <el-option key="<=" label="小于等于（<=）" value="<=" />
                                                </el-select>
                                            </el-col>
                                            <el-col :span="9">
                                                <div>
                                                    <el-input v-model="item.value" placeholder="值" size="small"
                                                        style="width: 165px; vertical-align: baseline" type="number">
                                                        <!-- <template slot="append">{{ jumpUnit(index) }}</template> -->
                                                    </el-input>
                                                </div>
                                            </el-col>
                                        </el-row>
                                    </div>
                                    <div v-if="[1, 3, 5].includes(item.source)">
                                        <el-row :gutter="16">
                                            <el-col :span="5">
                                                <el-select v-model="item.sceneRule[0].ruleType" placeholder="请选择"
                                                    size="small" @change="handleSceneRule($event, index, item)">
                                                    <el-option v-for="subItem in sceneRuleList" :key="subItem.value"
                                                        :label="subItem.label" :value="subItem.value"></el-option>
                                                </el-select>
                                            </el-col>
                                            <el-col v-if="item.sceneRule[0].ruleType" :span="5">
                                                <el-input v-model="item.sceneRule[0].ruleValue" placeholder="请输入"
                                                    rows="1" type="number">
                                                    <template slot="append">{{ item.sceneRule[0].unit }}</template>
                                                </el-input>
                                            </el-col>
                                            <el-col v-if="item.sceneRule[0].ruleType == 1" :span="5">
                                                <el-input v-model="item.sceneRule[0].ruleMun" placeholder="请输入" rows="1"
                                                    type="number">
                                                    <template slot="append">数量</template>
                                                </el-input>
                                            </el-col>
                                        </el-row>
                                    </div>
                                </div>
                                <div v-if="!(form.cond == 3 && formJson.triggers.length > 0)">
                                    +
                                    <a style="color: #409eff" @click="handleAddTrigger()">{{ $t('scene.index.670805-23')
                                        }}</a>
                                </div>
                            </el-form-item>
                        </div>
                        <div class="action-wrap" v-if="nodeDataForm.properties.props == 'action'">
                            <el-form-item :label="$t('scene.index.670805-24')">
                                <div class="item-wrap" style="background-color: #eef3f7">
                                    <el-row :gutter="16">
                                        <el-col :span="8">
                                            <span>
                                                <el-tooltip class="item" effect="dark"
                                                    :content="$t('scene.index.670805-25')" placement="top">
                                                    <i class="el-icon-question"></i>
                                                </el-tooltip>
                                                {{ $t('scene.index.670805-26') }}
                                            </span>
                                            <el-input v-model="form.silentPeriod" size="small"
                                                :placeholder="$t('scene.index.670805-4')" type="number"
                                                style="width: 140px">
                                                <template slot="append">{{ $t('scene.index.670805-4') }}</template>
                                            </el-input>
                                        </el-col>
                                        <el-col :span="8">
                                            <span>{{ $t('scene.index.670805-27') }}</span>
                                            <el-select v-model="form.executeMode"
                                                :placeholder="$t('scene.index.670805-28')" size="small"
                                                style="width: 160px">
                                                <el-option key="1" :label="$t('scene.index.670805-29')" :value="1" />
                                                <el-option key="2" :label="$t('scene.index.670805-30')" :value="2" />
                                            </el-select>
                                        </el-col>
                                        <el-col :span="8">
                                            <span>
                                                <el-tooltip class="item" effect="dark"
                                                    c:content="$t('scene.index.670805-31')" placement="top">
                                                    <i class="el-icon-question"></i>
                                                </el-tooltip>
                                                {{ $t('scene.index.670805-32') }}
                                            </span>
                                            <el-input v-model="form.executeDelay" prop="executeDelay" size="small"
                                                :placeholder="$t('scene.index.670805-5')" :max="90" :min="0"
                                                oninput="if(value>90)value=90;if(value<0)value=0" type="number"
                                                style="width: 140px">
                                                <template slot="append">{{ $t('scene.index.670805-5') }}</template>
                                            </el-input>
                                        </el-col>
                                    </el-row>
                                </div>

                                <div class="item-wrap" v-for="(item, index) in formJson.actions" :key="index">
                                    <el-row :gutter="16">
                                        <el-col :span="4">
                                            <el-select v-model="item.source" :placeholder="$t('pleaseSelect')"
                                                size="small" @change="handleActionSourceChange($event, index)">
                                                <el-option v-for="subItem in actionSource" :key="subItem.value"
                                                    :label="subItem.label" :value="subItem.value"></el-option>
                                            </el-select>
                                        </el-col>
                                        <el-col :span="10" v-if="item.source == 1">
                                            <el-input readonly v-model="item.deviceCount" size="small"
                                                :placeholder="$t('scene.index.670805-33')" style="margin-top: 3px">
                                                <span slot="prepend" disabled>{{ $t('scene.index.670805-14') }}</span>
                                                <el-button slot="append"
                                                    @click="handleSelectDevice('action', item, index)" size="small">{{
                                                        $t('scene.index.670805-34') }}</el-button>
                                            </el-input>
                                        </el-col>
                                        <el-col :span="10" v-if="item.source == 3">
                                            <el-input readonly v-model="item.productName" size="small"
                                                :placeholder="$t('scene.index.670805-35')" style="margin-top: 3px">
                                                <el-button slot="append"
                                                    @click="handleSelectProduct('action', item, index)" size="small">{{
                                                        $t('scene.index.670805-36') }}</el-button>
                                            </el-input>
                                        </el-col>
                                        <el-col :span="10" v-if="item.source == 5">
                                            <el-input readonly v-model="form.recoverSceneName" size="small"
                                                :placeholder="$t('scene.index.670805-75')" style="margin-top: 3px">
                                                <el-button slot="append"
                                                    @click="handleSelectRecoverScenes('action', item, index)"
                                                    size="small">{{ $t('scene.index.670805-76') }}</el-button>
                                            </el-input>
                                        </el-col>
                                        <el-col :span="10" v-if="item.source === 6">
                                            <el-form-item>
                                                <el-input v-model="item.userName" placeholder="请输入执行人"
                                                    @click.native="selectUser(index)" />
                                            </el-form-item>
                                        </el-col>
                                        <div class="delete-wrap">
                                            <el-button size="small" v-if="index != 0" plain type="danger"
                                                style="padding: 5px" icon="el-icon-delete"
                                                @click="handleRemoveAction(index)">{{ $t('del') }}</el-button>
                                        </div>
                                    </el-row>

                                    <div v-if="item.thingsModel">
                                        <!--类型和父级物模型-->
                                        <el-row :gutter="16">
                                            <el-col :span="5">
                                                <el-select v-model="item.type" :placeholder="$t('scene.index.670805-1')"
                                                    size="small" @change="handleActionTypeChange($event, index)">
                                                    <el-option v-for="(subItem, subIndex) in actionTypes"
                                                        :key="subIndex + 'type'" :label="subItem.label"
                                                        :value="subItem.value"></el-option>
                                                </el-select>
                                            </el-col>
                                            <el-col :span="10">
                                                <el-select style="width: 100%" v-model="item.parentId"
                                                    placeholder="$t('scene.index.670805-19')" v-if="item.type == 1"
                                                    size="small" @change="handleActionParentModelChange($event, index)">
                                                    <el-option
                                                        v-for="(subItem, subIndex) in item.thingsModel.properties"
                                                        :key="subIndex + 'actionProperty'" :label="subItem.name"
                                                        :value="subItem.id"></el-option>
                                                </el-select>
                                                <el-select v-model="item.parentId" size="small"
                                                    :placeholder="$t('scene.index.670805-19')"
                                                    v-else-if="item.type == 2" style="width: 100%"
                                                    @change="handleActionParentModelChange($event, index)">
                                                    <el-option v-for="(subItem, subIndex) in item.thingsModel.functions"
                                                        :key="subIndex + 'actionFunc'" :label="subItem.name"
                                                        :value="subItem.id"></el-option>
                                                </el-select>
                                            </el-col>
                                        </el-row>

                                        <!--数组索引/物模型/值-->
                                        <el-row :gutter="16">
                                            <el-col
                                                v-if="item.parentModel && item.parentModel.datatype.type === 'array'"
                                                :span="5">
                                                <el-select v-model="item.arrayIndex" :placeholder="$t('pleaseSelect')"
                                                    size="small" @change="handleActionIndexChange($event, index)">
                                                    <el-option v-for="subItem in item.parentModel.datatype.arrayModel"
                                                        :key="subItem.id" :label="subItem.name"
                                                        :value="subItem.id"></el-option>
                                                </el-select>
                                            </el-col>
                                            <el-col
                                                v-if="item.parentModel && item.parentModel.datatype.type === 'array' && item.parentModel.datatype.arrayType === 'object'"
                                                :span="5">
                                                <el-select v-model="item.id" :placeholder="$t('pleaseSelect')"
                                                    size="small" @change="handleActionModelChange($event, index)">
                                                    <el-option
                                                        v-for="(subItem, subIndex) in item.parentModel.datatype.params"
                                                        :key="subIndex" :label="subItem.name"
                                                        :value="subItem.id"></el-option>
                                                </el-select>
                                            </el-col>
                                            <el-col
                                                v-if="item.parentModel && item.parentModel.datatype.type === 'object'"
                                                :span="5">
                                                <el-select v-model="item.id" :placeholder="$t('pleaseSelect')"
                                                    size="small" @change="handleActionModelChange($event, index)">
                                                    <el-option
                                                        v-for="(subItem, subIndex) in item.parentModel.datatype.params"
                                                        :key="subIndex" :label="subItem.name"
                                                        :value="subItem.id"></el-option>
                                                </el-select>
                                            </el-col>
                                            <el-col :span="10" v-if="item.model">
                                                <div
                                                    v-if="item.model.datatype.type === 'integer' || item.model.datatype.type === 'decimal'">
                                                    <el-input style="vertical-align: baseline" v-model="item.value"
                                                        :placeholder="$t('scene.index.670805-21')"
                                                        :max="item.model.datatype.max" :min="item.model.datatype.min"
                                                        type="number" size="small">
                                                        <template slot="append">{{ item.model.datatype.unit
                                                            }}</template>
                                                    </el-input>
                                                </div>
                                                <div v-else-if="item.model.datatype.type === 'bool'">
                                                    <el-switch v-model="item.value"
                                                        :inactive-text="item.model.datatype.falseText"
                                                        :active-text="item.model.datatype.trueText" active-value="1"
                                                        inactive-value="0" style="vertical-align: baseline"></el-switch>
                                                </div>
                                                <div v-else-if="item.model.datatype.type === 'enum'">
                                                    <el-select v-model="item.value" :placeholder="$t('pleaseSelect')"
                                                        style="width: 100%" size="small">
                                                        <el-option
                                                            v-for="(subItem, subIndex) in item.model.datatype.enumList"
                                                            :key="subIndex + 'things'" :label="subItem.text"
                                                            :value="subItem.value"></el-option>
                                                    </el-select>
                                                </div>
                                                <div v-else-if="item.model.datatype.type === 'string'">
                                                    <el-input v-model="item.value"
                                                        :placeholder="$t('scene.index.670805-22')" size="small"
                                                        :max="item.model.datatype.maxLength" />
                                                </div>
                                            </el-col>
                                        </el-row>
                                    </div>
                                </div>
                                <div>
                                    +
                                    <a style="color: #409eff" @click="handleAddAction()">{{ $t('scene.index.670805-37')
                                        }}</a>
                                </div>
                            </el-form-item>
                        </div>
                    </el-form>
                    <div class="flex-center">
                        <el-button @click="nodeVisable = false">取消</el-button>
                        <el-button type="primary" @click="nodeSubmit()">确定</el-button>
                    </div>
                </el-card>
            </template>
        </el-drawer>
        <deviceList ref="deviceList1" :chooesOne="true" @deviceEvent="getSelectProductDevice1($event, 1)"></deviceList>
        <!-- 调度任务保存 -->
        <el-dialog v-model="configVisible" title="调度配置" @keyup.enter="scheduleSubmit(false)">
            <el-form ref="scheduleFormRef" :model="scheduleForm" :rules="scheduleRules" label-width="100px">
                <el-form-item prop="orgId" label="所属机构" label-width="auto">
                    <el-tree-select clearable v-model="scheduleForm.orgId" :data="orgList" check-strictly value-key="id"
                        :props="{ label: 'name', children: 'children' }" style="width: 100%" />
                </el-form-item>
                <el-form-item label="调度名称" prop="name" label-width="auto">
                    <el-input v-model="scheduleForm.name" placeholder="调度名称"></el-input>
                </el-form-item>
                <el-form-item label="周期执行" prop="ifCycle" label-width="auto">
                    <fast-select v-model="scheduleForm.ifCycle" dict-type="yes_or_no" placeholder="请选择" clearable
                        filterable></fast-select>
                </el-form-item>
                <el-form-item label="cron表达式" prop="cron" label-width="auto" v-if="scheduleForm.ifCycle == '1'">
                    <el-input v-model="scheduleForm.cron" placeholder="cron表达式"></el-input>
                    <!-- <el-popover ref="cronPopover" :width="550" trigger="click">
						<Cron @submit="changeCron" @close="cronPopover.hide()"></Cron>
						<template #reference>
							<el-input v-model="scheduleForm.cron" placeholder="cron表达式"></el-input>
						</template>
					</el-popover> -->
                </el-form-item>
                <el-form-item label="备注" prop="note" label-width="auto">
                    <el-input :rows="2" type="textarea" v-model="scheduleForm.note" placeholder="备注"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="configVisible = false">取消</el-button>
                <el-button type="primary" @click="scheduleSubmit(false)">确定</el-button>
            </template>
        </el-dialog>

        <!-- 设备列表 -->
        <deviceList ref="deviceList" @deviceEvent="getSelectProductDevice($event, 1)"></deviceList>

        <!-- 设备列表运算触发专用 -->
        <deviceList ref="deviceList1" :chooesOne="true" @deviceEvent="getSelectProductDevice1($event, 1)"></deviceList>
        <!-- 产品列表 -->
        <productList ref="productList" @productEvent="getSelectProductDevice($event, 2)"></productList>
        <!-- 选择场景对话框 -->
        <scene-list ref="sceneList" @sceneEvent="getSceneData($event)" />

        <!-- CRON表达式生成器 -->
        <el-dialog :title="$t('scene.index.670805-38')" :visible.sync="openCron" append-to-body destroy-on-close
            class="scrollbar">
            <crontab :expression="expression" style="padding-bottom: 10px" @fill="crontabFill" @hide="openCron = false">
            </crontab>
        </el-dialog>

        <!-- 选择用户 -->
        <user-list ref="userList" @userEvent="getUserData($event)" />
    </div>
</template>
<script>
import treeData from './tree.json';
import scheduleData from './schedule.json';
import { listDeviceShort } from '@/api/iot/device';
import LogicFlow from '@logicflow/core';
import { Menu, Control, SelectionSelect, DndPanel, Snapshot } from '@logicflow/extension';
import TaskModel from './UserTaskNode.js';
import FlowLink from './FlowLink.js';
import { cacheJsonThingsModel } from '@/api/iot/model';
import { findPurchasing } from '@/views/energy/api/energy/deviceAreaBinding.js';
import { addScene, delScene, getEnergyType, getScene, listScene, runScene, updateScene } from '@/api/iot/scene';
import Crontab from '@/components/Crontab';
import deviceList from './device-list';
import productList from './product-list';
import sceneList from './scene-list';
import AceEditor from '@/views/components/editor/editor.vue';
import userList from '@/views/iot/sip/user-list.vue';
import { Message } from 'element-ui';
export default {
    name: 'flow',
    components: {
        AceEditor,
        deviceList,
        productList,
        sceneList,
        Crontab,
        userList,
    },
    data() {
        return {
            scheduleForm: {
                orgId: '',
                id: '',
                name: '',
                ifCycle: '',
                cron: '',
                note: '',
                nodes: [],
                edges: [],
            },
            scheduleRules: {
                orgId: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
                name: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
                ifCycle: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
                cron: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
            },
            configVisible: false,
            cronPopover: null,
            orgList: [],
            graphData: {
                nodes: [],
                edges: [],
            },
            runFlag: false,
            saveLoading: false,
            nodeVisable: false,
            nodeDataForm: {
                id: '',
                properties: {
                    name: '',
                    taskType: '',
                    taskTypeVal: '',
                    taskId: '',
                    note: '',
                    failGoOn: '',
                    weight: 1,
                },
                type: '',
                x: 490,
                y: 230,
            },
            nodeDataRules: {
                properties: {
                    name: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
                    taskTypeVal: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
                    failGoOn: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
                    weight: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
                },
            },
            lf: null,
            catalogueTreeList: [],
            filterCatalogueText: '',
            form: {
                sceneId: null,
                recoverId: null,
                recoverSceneName: null,
                sceneName: null,
                userId: null,
                userName: null,
                remark: null,
                enable: 1,
                cond: 1,
                silentPeriod: 0,
                executeMode: 1,
                executeDelay: 0,
                checkDelay: 0,
                hasAlert: 2, // 1=包含告警，2=不包含告警
                applicationName: 'yanfan', // 固定值
            },

            triggerSource: [
                {
                    value: '1',
                    label: this.$t('scene.index.670805-46'),
                },
                {
                    value: '2',
                    label: this.$t('scene.index.670805-47'),
                },
                {
                    value: '3',
                    label: this.$t('scene.index.670805-48'),
                },
                {
                    value: '4',
                    label: this.$t('scene.index.670805-49'),
                },
                {
                    value: '5',
                    label: '运算触发',
                },
                {
                    value: '6',
                    label: '能源触发',
                },
            ],
            deviceList: [],
            openDeviceList: false,
            thingsModel: [],
            actionSource: [
                {
                    value: 1,
                    label: this.$t('scene.index.670805-55'),
                },
                {
                    value: 3,
                    label: this.$t('scene.index.670805-56'),
                },
                {
                    value: 4,
                    label: this.$t('scene.index.670805-57'),
                },
                {
                    value: 5,
                    label: this.$t('scene.index.670805-58'),
                },
                {
                    value: 6,
                    label: '工单执行',
                },
            ],
            openCron: false,
            expression: '',
            confirmLoading: false,
            // 更新按钮
            updateBtnDisabled: false,
            // 当前选择设备时的类型（trigger/action）
            currentType: null,
            // 当前选择设备时的类型索引
            currentIndex: null,
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 场景联动表格数据
            sceneList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            logs: '',
            logChainID: '',
            // 是否显示Cron表达式弹出层
            openCron: false,
            openLog: false,
            logLoading: false,
            // 传入的表达式
            expression: '',
            // 触发器的索引，用于接收传入的表达式
            triggerIndex: 0,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                sceneName: null,
                userId: null,
                userName: null,
            },
            timerWeeks: [
                {
                    value: 1,
                    label: this.$t('scene.index.670805-39'),
                },
                {
                    value: 2,
                    label: this.$t('scene.index.670805-40'),
                },
                {
                    value: 3,
                    label: this.$t('scene.index.670805-41'),
                },
                {
                    value: 4,
                    label: this.$t('scene.index.670805-42'),
                },
                {
                    value: 5,
                    label: this.$t('scene.index.670805-43'),
                },
                {
                    value: 6,
                    label: this.$t('scene.index.670805-44'),
                },
                {
                    value: 7,
                    label: this.$t('scene.index.670805-45'),
                },
            ],
            // 触发器源 1=设备，2=定时
            triggerSource: [
                {
                    value: 1,
                    label: this.$t('scene.index.670805-46'),
                },
                {
                    value: 2,
                    label: this.$t('scene.index.670805-47'),
                },
                {
                    value: 3,
                    label: this.$t('scene.index.670805-48'),
                },
                {
                    value: 4,
                    label: this.$t('scene.index.670805-49'),
                },
                {
                    value: 5,
                    label: this.$t('index.scene.20250324-8'),
                },
                {
                    value: 6,
                    label: this.$t('index.scene.20250324-9'),
                },
            ],
            sceneRuleList: [
                {
                    value: 0,
                    unit: '',
                    label: this.$t('index.scene.20250324-2'),
                },
                {
                    value: 1,
                    unit: this.$t('index.scene.20250324-5'),
                    label: this.$t('index.scene.20250324-3'),
                },
                {
                    value: 2,
                    unit: this.$t('index.scene.20250324-6'),
                    label: this.$t('index.scene.20250324-4'),
                },
            ],
            // 触发器类别
            triggerTypes: [
                {
                    value: 1,
                    label: this.$t('scene.index.670805-50'),
                },
                {
                    value: 2,
                    label: this.$t('scene.index.670805-51'),
                },
                {
                    value: 3,
                    label: this.$t('scene.index.670805-52'),
                },
                {
                    value: 5,
                    label: this.$t('scene.index.670805-53'),
                },
                {
                    value: 6,
                    label: this.$t('scene.index.670805-54'),
                },
            ],
            // 动作源 1=设备，3=产品执行，4=告警执行
            actionSource: [
                {
                    value: 1,
                    label: this.$t('scene.index.670805-55'),
                },
                {
                    value: 3,
                    label: this.$t('scene.index.670805-56'),
                },
                {
                    value: 4,
                    label: this.$t('scene.index.670805-57'),
                },
                {
                    value: 5,
                    label: this.$t('scene.index.670805-58'),
                },
                {
                    value: 6,
                    label: this.$t('index.scene.20250324-28'),
                },
            ],
            // 动作类别
            actionTypes: [
                {
                    value: 1,
                    label: this.$t('scene.index.670805-50'),
                },
                {
                    value: 2,
                    label: this.$t('scene.index.670805-51'),
                },
            ],
            // 表单参数
            formJson: {
                triggers: [],
                actions: [],
            },
            actionIndex: null,
            form: {},
            // 表单校验
            rules: {
                sceneName: [
                    {
                        required: true,
                        message: this.$t('scene.index.670805-59'),
                        trigger: 'blur',
                    },
                ],
                executeDelay: [
                    {
                        required: true,
                        max: 90,
                        min: 0,
                        message: this.$t('scene.index.670805-60'),
                        trigger: 'blur',
                    },
                ],
                checkDelay: [
                    {
                        required: true,
                        max: 600,
                        min: 0,
                        message: this.$t('scene.index.670805-61'),
                        trigger: 'blur',
                    },
                ],
            },
            // 运算出发专用
            currentType1: null,
            // 当前选择设备时的类型索引
            currentIndex1: null,
            // 父级的索引
            currentIndexItem: null,
            // 能源列表
            energyList: [],
            tpyeopen: false,
        };
    },

    created() { },
    computed: {
        // 计算两个周期值
        jumpIsShowOperator() {
            let isShow = false;
            if (this.formJson.triggers[index].sceneOperation) {
                this.formJson.triggers[index].sceneOperation.map((item) => {
                    if (item.id) {
                        isShow = true;
                    }
                });
            }
            return isShow;
        },
    },
    methods: {
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        getUserData(user) {
            // console.log('user', userName);

            this.formJson.actions[this.actionIndex].userId = user.userId;
            this.formJson.actions[this.actionIndex].userName = user.nickName;
            this.nodeDataForm.properties.form;
            console.log(this.formJson.actions, this.formJson.actions);

            /* if (user) {
                this.$set(this.formData.repair, 'repairPerson', user.userId)
                this.$set(this.formData.repair, 'repairPersonName', user.nickName)
            }*/
        },
        // 添加动作
        handleAddAction() {
            if (this.formJson.actions[this.formJson.actions.length - 1].source == 6) {
                if (this.formJson.actions[this.formJson.actions.length - 1].userName.length <= 0) {
                    return Message.error('请输入执行人！');
                }
            }
            this.formJson.actions.push({
                source: 1, //1=设备，3=产品，4=告警
                type: 2, // 类型
                id: '',
                name: '',
                value: '',
                model: null,
                parentId: '', // 物模id
                parentName: '',
                parentModel: null,
                arrayIndex: '', // 索引，数组才有
                arrayIndexName: '',
                productId: 0,
                productName: '',
                deviceNums: [],
                deviceCount: 0,
                scriptPurpose: 3, // scriptPurpose:脚本用途(1=数据流，2=触发器，3=执行动作)
                userName: '',
            });
        },
        // 删除动作
        handleRemoveAction(index) {
            this.formJson.actions.splice(index, 1);
        },
        /** 确定后回传值 */
        crontabFill(value) {
            this.formJson.triggers[this.triggerIndex].cronExpression = value;
        },
        init(id, ifRun) {
            this.scheduleForm = {
                orgId: '',
                id: '',
                name: '',
                ifCycle: '',
                cron: '',
                note: '',
                nodes: [],
                edges: [],
            };
            // flowConsoleLogRef.value.setEditorValue('');
            this.flowEnd = false;
            var bottomResize = document.getElementsByClassName('flowBottomResize');
            var topBox = document.getElementsByClassName('flowTopBox');
            var downBox = document.getElementsByClassName('flowBottomBox');
            bottomResize[0].style.height = '0';
            topBox[0].style.height = '800px';
            downBox[0].style.height = '0';

            //获取部门列表
            // useOrgListApi().then((res) => {
            //     orgList.value = res.data;
            // });

            //如果id不为空，给scheduleForm赋值
            if (id) {
                this.scheduleForm = this.scheduleData;
                this.graphData.nodes = this.scheduleForm.nodes;
                this.graphData.edges = this.scheduleForm.edges;
                this.lf.render(this.graphData);
                if (ifRun) {
                    bottomResize[0].style.height = '10px';
                    topBox[0].style.height = '70%';
                    downBox[0].style.height = 'calc(30% - 10px)';
                    this.runFlag = true;
                    this.runFlow(id);
                }
            } else {
                //渲染
                this.graphData = {
                    nodes: [],
                    edges: [],
                };
                console.log('开始挂载');

                this.lf.render(this.graphData);
            }
        },
        changeCron(val) {
            this.scheduleForm.cron = val;
        },
        scheduleSubmit(submit) {
            if (submit) {
                //校验
                if (!scheduleForm.name || scheduleForm.ifCycle === '' || (scheduleForm.ifCycle == '1' && !scheduleForm.cron)) {
                    this.$modal.warning('请点击配置，配置完调度信息再保存！');
                    return;
                }
                this.saveLoading = true;
                let graphData = this.lf.getGraphData();
                this.scheduleForm.nodes = graphData.nodes;
                this.scheduleForm.edges = graphData.edges;
                this.scheduleForm.cron = scheduleForm.ifCycle == '1' ? scheduleForm.cron : '';
                // useScheduleSubmitApi(scheduleForm)
                //     .then(() => {
                //         ElMessage.success({
                //             message: '保存成功',
                //             duration: 500,
                //             onClose: () => {
                //                 //刷新分页
                //                 emit('refreshDataList');
                //             },
                //         });
                //     })
                //     .finally(() => {
                //         saveLoading.value = false;
                //     });
            } else {
                console.log('ththhththt', this.nodeDataForm);
                console.log('ththhththt', this.formJson);
                return;
                if (this.formJson.source == 1) {
                }
                this.$refs['scheduleFormRef'].validate((valid) => {
                    if (!valid) {
                        return false;
                    }
                    this.$modal.success({
                        message: '操作成功',
                        duration: 500,
                        onClose: () => {
                            this.configVisible = false;
                        },
                    });
                });
            }
        },
        getCatalogueTreeList() {
            this.catalogueTreeList = treeData.data;
        },
        filterNode(value, data) {
            if (!value) return true;
            return data.label.includes(value) || data.label.includes(value.toUpperCase()) || data.label.includes(value.toLowerCase());
        },
        allowDropOver(ev) {
            ev.preventDefault();
        },
        startDrag(item) {
            console.log('this.formJson', this.formJson);
            if (this.formJson.actions.length >= 1 && item.props == 'action') {
                return;
            } else if (this.formJson.actions.length == 0 && item.props == 'action') {
                this.formJson.actions = [
                    {
                        productId: 0,
                        productName: '',
                        deviceCount: 0,
                        deviceNums: [],
                        source: 1, //1=设备，3=产品，4=告警，5=告警恢复
                        type: 2, // 类型1=属性/2=功能，3=事件
                        parentId: '', // 物模父级id
                        parentName: '',
                        parentModel: null, // 父级物模型
                        model: null, // 物模型
                        id: '',
                        name: '',
                        value: '',
                        arrayIndex: '', // 索引，数组才有
                        arrayIndexName: '',
                        scriptPurpose: 3, // scriptPurpose:脚本用途(1=数据流，2=触发器，3=执行动作)
                        userId: '',
                        userName: '',
                    },
                ];
            }
            this.lf.dnd.startDrag({
                type: 'base-node',
                properties: {
                    ...item,
                    note: '',
                    weight: 1,
                    failGoOn: 0,
                    width: 220,
                    height: 120,
                },
            });
        },
        nodeEdit(data) {
            this.nodeDataForm = data;
            console.log('dataaaaaa', data);
            if (data.properties.props == 'device') {
                this.nodeDataForm = data;
                return this.handleSelectDevice1();
            }
            this.nodeVisable = true;
            this.nodeDataForm.id = '';
            this.reset();
            // 重置表单数据
            if (this.$refs['nodeDataFormRef']) {
                this.$refs['nodeDataFormRef'].resetFields();
            }
            //赋值

            // Object.assign(nodeDataForm, data);
        },
        nodeSubmit() {
            this.$refs['nodeDataFormRef'].validate((valid) => {
                if (!valid) {
                    return false;
                }
                if (this.nodeDataForm.properties.props == 'condition') {
                    this.nodeDataForm.properties.value = this.nodeDataForm.properties.formValue == '1' ? '任意条件' : this.nodeDataForm.properties.formValue == '2' ? '所有条件' : '不满足';
                } else if (this.nodeDataForm.properties.props == 'rules') {
                    this.nodeDataForm.properties.value = this.triggerSource.find((item) => {
                        return item.value == this.nodeDataForm.properties.formValue;
                    }).label;
                } else if (this.nodeDataForm.properties.props == 'device') {
                    this.nodeDataForm.properties.value = this.deviceList.find((item) => {
                        return item.deviceId == this.nodeDataForm.properties.formValue;
                    }).deviceName;
                } else if (this.nodeDataForm.properties.props == 'action') {
                    this.nodeDataForm.properties.value = this.actionSource.find((item) => {
                        return item.value == this.formJson.actions[0].source;
                    }).label;
                }
                if (this.lf.getNodeModelById(this.nodeDataForm.id)) {
                    this.lf.getNodeModelById(this.nodeDataForm.id).setProperties(this.nodeDataForm.properties);
                }

                // this.$modal.success('操作成功');
                this.nodeVisable = false;
            });
        },
        runFlow(id) {
            //提示
            this.$notify({
                title: '提示',
                message: '正在提交流程。。。',
                duration: 0,
                zIndex: 9999,
                type: 'success',
            });
            //获取recordId
            // const { data } = await runFlowApi(id);
            //console.log(data)
            this.$notify.closeAll();
            //提示
            this.$notify({
                title: '提示',
                message: '正在执行流程，请耐心等待。。。',
                duration: 0,
                zIndex: 9999,
                type: 'success',
            });
            //获取日志
        },
        dragControllerUD() {
            var bottomResize = document.getElementsByClassName('flowBottomResize');
            var topBox = document.getElementsByClassName('flowTopBox');
            var downBox = document.getElementsByClassName('flowBottomBox');
            var box = document.getElementsByClassName('flowBox');
            for (let i = 0; i < bottomResize.length; i++) {
                // 鼠标按下事件
                bottomResize[i].onmousedown = function (e) {
                    console.log(bottomResize[i].top);
                    //颜色改变提醒
                    bottomResize[i].style.background = '#818181';
                    var startY = e.clientY;
                    bottomResize[i].top = bottomResize[i].offsetTop;
                    // 鼠标拖动事件
                    document.onmousemove = function (e) {
                        var endY = e.clientY;
                        var moveLen = bottomResize[i].top + (endY - startY); // （endY - startY）=移动的距离。resize[i].top+移动的距离=上边区域最后的高度
                        var maxT = box[i].clientHeight - bottomResize[i].offsetHeight; // 容器高度 - 上边区域的高度 = 下边区域的高度

                        if (moveLen < 100) moveLen = 100; // 上边区域的最小高度为100px
                        if (moveLen > maxT - 80) moveLen = maxT - 80; //下边区域最小高度为80px

                        bottomResize[i].style.top = moveLen; // 设置上边区域的高度

                        for (let j = 0; j < topBox.length; j++) {
                            topBox[j].style.height = moveLen + 'px';
                            downBox[j].style.height = box[i].clientHeight - moveLen - bottomResize[i].offsetHeight + 'px';
                        }
                    };
                    // 鼠标松开事件
                    document.onmouseup = function () {
                        //颜色恢复
                        bottomResize[i].style.background = '#d6d6d6';
                        document.onmousemove = null;
                        document.onmouseup = null;
                        bottomResize[i].releaseCapture && bottomResize[i].releaseCapture(); //当你不在需要继续获得鼠标消息就要应该调用ReleaseCapture()释放掉
                    };
                    bottomResize[i].setCapture && bottomResize[i].setCapture(); //该函数在属于当前线程的指定窗口里设置鼠标捕获
                    return false;
                };
            }
        },
        handleSelectDevice1(type, item, index, index1) {
            listDeviceShort({ pageNum: 1, pageSize: 1000 }).then((response) => {
                if (response.rows) {
                    this.deviceList = response.rows;
                }
                this.nodeVisable = true;
                this.nodeDataForm.properties.formValue = this.deviceList[0].deviceId;
                this.getThingsModel();
            });
            // this.openDeviceList = true;
        },
        getThingsModel() {
            let productId = this.deviceList.find((item) => {
                return item.deviceId == this.nodeDataForm.properties.formValue;
            }).productId;
            cacheJsonThingsModel(productId).then((response) => {
                // console.log('response', response);
                if (response.data) {
                    let thingsModel = JSON.parse(response.data);
                    console.log('thingsModel', thingsModel);
                    this.thingsModel = thingsModel.properties;
                    // this.nodeDataForm.properties.valueThings = this.thingsModel[0].name;
                    // this.nodeDataForm.properties.formThings = '';
                }
            });
        },
        handleActionSourceChange(source, index) {
            console.log('this.formJson.actions[index]', this.formJson.actions[index]);
            this.formJson.actions[index].deviceCount = 0;
            this.formJson.actions[index].productId = '';
            this.formJson.actions[index].productName = '';
            this.formJson.actions[index].thingsModel = null;
            this.formJson.actions[index].id = '';
            this.formJson.actions[index].name = '';
            this.formJson.actions[index].value = '';
            this.formJson.actions[index].valueA = '';
            this.formJson.actions[index].valueB = '';
            this.formJson.actions[index].parentId = '';
            this.formJson.actions[index].parentName = '';
            this.formJson.actions[index].model = null;
            this.formJson.actions[index].parentModel = null;
            this.formJson.actions[index].operator = '';
            this.formJson.actions[index].deviceNums = [];
            // 定时
            this.formJson.actions[index].timerTimeValue = ''; // 时间
            this.formJson.actions[index].timerWeekValue = [1, 2, 3, 4, 5, 6, 7]; // 星期
        },
        handleSelectDevice(type, item, index) {
            this.currentType = type;
            this.currentIndex = index;
            // 刷新子组件
            this.$refs.deviceList.queryParams.pageNum = 1;
            this.$refs.deviceList.openDeviceList = true;
            this.$refs.deviceList.selectDeviceNums = item.deviceNums;
            this.$refs.deviceList.productId = item.productId;
            this.$refs.deviceList.productName = item.productName;
            this.$refs.deviceList.queryParams.productId = item.productId;
            this.$refs.deviceList.getList();
        },
        /**选择产品 */
        handleSelectProduct(type, item, index) {
            this.currentType = type;
            this.currentIndex = index;
            // 刷新子组建
            this.$refs.productList.queryParams.pageNum = 1;
            this.$refs.productList.open = true;
            this.$refs.productList.selectProductId = item.productId;
            this.$refs.productList.getList();
        },
        /**添加场景*/
        handleSelectRecoverScenes() {
            this.$refs.sceneList.queryParams.pageNum = 1;
            this.$refs.sceneList.openScene = true;
            this.$refs.sceneList.selectSceneId = this.form.recoverId;
            this.$refs.sceneList.getList();
        },
        selectUser(index) {
            console.log('this.formJson', this.formJson);
            // return;
            this.actionIndex = index;
            this.$refs.userList.open = true;
            if (this.formJson.actions[index].userId) {
                this.$refs.userList.getList(this.formJson.actions[index].userId);
            } else {
                this.$refs.userList.getList();
            }
        },
        getSelectProductDevice(data, type) {
            console.log(data, type, '9999999');
            if (this.currentType == null) {
                return;
            }
            if (this.currentType == 'trigger') {
                if (type == 1) {
                    this.formJson.triggers[this.currentIndex].deviceNums = data.deviceNums;
                    this.formJson.triggers[this.currentIndex].deviceCount = data.deviceNums.length;
                    this.formJson.triggers[this.currentIndex].productId = data.productId;
                    this.formJson.triggers[this.currentIndex].productName = data.productName;
                } else if (type == 2) {
                    this.formJson.triggers[this.currentIndex].deviceNums = [];
                    this.formJson.triggers[this.currentIndex].deviceCount = 0;
                    this.formJson.triggers[this.currentIndex].productId = data.productId;
                    this.formJson.triggers[this.currentIndex].productName = data.productName;
                }

                // 获取物模型
                cacheJsonThingsModel(data.productId).then((response) => {
                    let data = JSON.parse(response.data);
                    this.formJson.triggers[this.currentIndex].thingsModel = this.formatArrayIndex(data);
                    // 清楚之前数据
                    this.formJson.triggers[this.currentIndex].type = 1;
                    this.formJson.triggers[this.currentIndex].parentId = '';
                    this.formJson.triggers[this.currentIndex].parentName = '';
                    this.formJson.triggers[this.currentIndex].parentModel = null;
                    this.formJson.triggers[this.currentIndex].model = null;
                    this.formJson.triggers[this.currentIndex].operator = '';
                    this.formJson.triggers[this.currentIndex].id = '';
                    this.formJson.triggers[this.currentIndex].name = '';
                    this.formJson.triggers[this.currentIndex].value = '';
                    this.formJson.triggers[this.currentIndex].arrayIndex = '';
                    this.formJson.triggers[this.currentIndex].arrayIndexName = '';
                    // 解决数组在界面中不更新问题
                    this.$set(this.formJson.triggers, this.currentIndex, this.formJson.triggers[this.currentIndex]);
                });
            } else if (this.currentType == 'action') {
                if (type == 1) {
                    this.formJson.actions[this.currentIndex].deviceNums = data.deviceNums;
                    this.formJson.actions[this.currentIndex].deviceCount = data.deviceNums.length;
                    this.formJson.actions[this.currentIndex].productId = data.productId;
                    this.formJson.actions[this.currentIndex].productName = data.productName;
                } else if (type == 2) {
                    this.formJson.actions[this.currentIndex].deviceNums = [];
                    this.formJson.actions[this.currentIndex].deviceCount = 0;
                    this.formJson.actions[this.currentIndex].productId = data.productId;
                    this.formJson.actions[this.currentIndex].productName = data.productName;
                }

                // 获取物模型
                cacheJsonThingsModel(data.productId).then((response) => {
                    let data = JSON.parse(response.data);
                    this.formJson.actions[this.currentIndex].thingsModel = this.formatArrayIndex(data);
                    // 清楚之前数据
                    this.formJson.actions[this.currentIndex].type = 1;
                    this.formJson.actions[this.currentIndex].parentId = '';
                    this.formJson.actions[this.currentIndex].parentModel = null;
                    this.formJson.actions[this.currentIndex].parentName = '';
                    this.formJson.actions[this.currentIndex].model = null;
                    this.formJson.actions[this.currentIndex].operator = '';
                    this.formJson.actions[this.currentIndex].id = '';
                    this.formJson.actions[this.currentIndex].name = '';
                    this.formJson.actions[this.currentIndex].value = '';
                    this.formJson.actions[this.currentIndex].arrayIndex = '';
                    this.formJson.actions[this.currentIndex].arrayIndexName = '';
                    // 过滤监测数据和只读数据
                    if (this.formJson.actions[this.currentIndex].thingsModel.properties) {
                        this.formJson.actions[this.currentIndex].thingsModel.properties = this.formJson.actions[this.currentIndex].thingsModel.properties.filter((item) => item.isMonitor == 0 && item.isReadonly == 0);
                        for (let i = 0; i < this.formJson.actions[this.currentIndex].thingsModel.properties.length; i++) {
                            if (this.formJson.actions[this.currentIndex].thingsModel.properties[i].datatype.params) {
                                this.formJson.actions[this.currentIndex].thingsModel.properties[i].datatype.params = this.formJson.actions[this.currentIndex].thingsModel.properties[i].datatype.params.filter(
                                    (item) => item.isMonitor == 0 && item.isReadonly == 0
                                );
                            }
                        }
                    }
                    if (this.formJson.actions[this.currentIndex].thingsModel.functions) {
                        this.formJson.actions[this.currentIndex].thingsModel.functions = this.formJson.actions[this.currentIndex].thingsModel.functions.filter((item) => item.isReadonly == 0);
                        for (let i = 0; i < this.formJson.actions[this.currentIndex].thingsModel.functions.length; i++) {
                            if (this.formJson.actions[this.currentIndex].thingsModel.functions[i].datatype.params) {
                                this.formJson.actions[this.currentIndex].thingsModel.functions[i].datatype.params = this.formJson.actions[this.currentIndex].thingsModel.functions[i].datatype.params.filter(
                                    (item) => item.isMonitor == 0 && item.isReadonly == 0
                                );
                            }
                        }
                    }
                    // 解决数组在界面中不更新问题
                    this.$set(this.formJson.actions, this.currentIndex, this.formJson.actions[this.currentIndex]);
                });
            }
        },
        getSelectProductDevice1(data, type) {
            if (this.currentType1 == null) {
                return;
            }
            const currentIndexItem = this.currentIndexItem;
            this.formJson.triggers[currentIndexItem].deviceNums = data.deviceNums;
            this.formJson.triggers[currentIndexItem].deviceCount = data.deviceNums.length;
            this.formJson.triggers[currentIndexItem].productId = data.productId;
            this.formJson.triggers[currentIndexItem].productName = data.productName;
            console.log(this.formJson.triggers, this.currentIndex1);
            this.formJson.triggers[currentIndexItem].sceneOperation[this.currentIndex1].deviceNums = data.deviceNums;
            this.formJson.triggers[currentIndexItem].sceneOperation[this.currentIndex1].serialNumber = data.deviceNums[0];
            this.formJson.triggers[currentIndexItem].sceneOperation[this.currentIndex1].deviceCount = data.deviceNums.length;
            this.formJson.triggers[currentIndexItem].sceneOperation[this.currentIndex1].productId = data.productId;
            this.formJson.triggers[currentIndexItem].sceneOperation[this.currentIndex1].productName = data.productName;
            // 获取物模型
            cacheJsonThingsModel(data.productId).then((response) => {
                let data = JSON.parse(response.data);
                this.formJson.triggers[currentIndexItem].sceneOperation[this.currentIndex1].thingsModel = this.formatArrayIndex(data);
                // 清楚之前数据
                this.formJson.triggers[currentIndexItem].sceneOperation[this.currentIndex1].type = 1;
                this.formJson.triggers[currentIndexItem].sceneOperation[this.currentIndex1].parentId = '';
                this.formJson.triggers[currentIndexItem].sceneOperation[this.currentIndex1].parentName = '';
                this.formJson.triggers[currentIndexItem].sceneOperation[this.currentIndex1].parentModel = null;
                this.formJson.triggers[currentIndexItem].sceneOperation[this.currentIndex1].model = null;
                this.formJson.triggers[currentIndexItem].sceneOperation[this.currentIndex1].operator = '';
                this.formJson.triggers[currentIndexItem].sceneOperation[this.currentIndex1].id = '';
                this.formJson.triggers[currentIndexItem].sceneOperation[this.currentIndex1].name = '';
                this.formJson.triggers[currentIndexItem].sceneOperation[this.currentIndex1].value = '';
                this.formJson.triggers[currentIndexItem].sceneOperation[this.currentIndex1].arrayIndex = '';
                this.formJson.triggers[currentIndexItem].sceneOperation[this.currentIndex1].arrayIndexName = '';
                // 解决数组在界面中不更新问题
                this.$set(this.formJson.triggers, this.currentIndexItem, this.formJson.triggers[this.currentIndexItem]);
                console.log(this.formJson.triggers, '11111111111111');
            });
        },
        getSceneData(data) {
            this.form.recoverId = data.sceneId;
            this.form.recoverSceneName = data.sceneName;
        },
        saveFrom(lf, ev) {
            this.handleSubmitForm();
        },
        // 获取能源列表
        getEnergyList() {
            findPurchasing().then((response) => {
                this.energyList = response.data;
            });
        },
        getUserData(user) {
            // console.log('user', userName);

            this.formJson.actions[this.actionIndex].userId = user.userId;
            this.formJson.actions[this.actionIndex].userName = user.userName;
            console.log(this.formJson.actions, this.formJson.actions);

            /* if (user) {
                this.$set(this.formData.repair, 'repairPerson', user.userId)
                this.$set(this.formData.repair, 'repairPersonName', user.nickName)
            }*/
        },
        selectUser(index) {
            console.log('this.formJson', this.formJson);
            // return;
            this.actionIndex = index;
            this.$refs.userList.open = true;
            if (this.formJson.actions[index].userId) {
                this.$refs.userList.getList(this.formJson.actions[index].userId);
            } else {
                this.$refs.userList.getList();
            }
        },
        /* 连接Mqtt消息服务器 */
        async connectMqtt() {
            if (this.$mqttTool.client == null) {
                await this.$mqttTool.connect();
            }
            // 删除所有message事件监听器
            this.$mqttTool.client.removeAllListeners('message');
            // 添加message事件监听器
            this.mqttCallback();
        },
        /** 查询场景联动列表 */
        getList() {
            this.loading = true;
            listScene(this.queryParams).then((response) => {
                this.sceneList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                sceneId: null,
                recoverId: null,
                recoverSceneName: null,
                sceneName: this.form.sceneName,
                userId: null,
                userName: null,
                remark: this.form.remark,
                enable: 1,
                cond: 1,
                silentPeriod: 0,
                executeMode: 1,
                executeDelay: 0,
                checkDelay: 0,
                hasAlert: 2, // 1=包含告警，2=不包含告警
                applicationName: 'yanfan', // 固定值
            };

            if (!this.formJson.triggers || this.formJson.triggers.length == 0) {
                this.formJson.triggers = [
                    {
                        productId: 0,
                        productName: '',
                        deviceCount: 0,
                        deviceNums: [],
                        source: 1, //1=设备，2=定时，3=产品
                        type: 1, // 类型1=属性/2=功能，3=事件
                        parentId: '', // 物模父级id
                        parentName: '',
                        parentModel: null,
                        model: null,
                        operator: '',
                        id: '',
                        name: '',
                        value: '', // between操作符时，值=值A-值B
                        valueA: '',
                        valueB: '',
                        arrayIndex: '', // 索引，数组才有
                        arrayIndexName: '',
                        isAdvance: 0, // 自定义CRON
                        cronExpression: '', // cron表达式
                        timerTimeValue: '', // 时间
                        timerWeekValue: [1, 2, 3, 4, 5, 6, 7], // 星期
                        scriptPurpose: 3, // scriptPurpose:脚本用途(1=数据流，2=触发器，3=执行动作)
                        sceneRule: [
                            {
                                ruleType: 0,
                                unit: '',
                                ruleValue: '',
                            },
                        ],
                    },
                ];
            }
            // console.log('this.formJson.triggers00');
            // if (!this.formJson.actions || this.formJson.actions.length == 0) {
            //     this.formJson.actions = [
            //         {
            //             productId: 0,
            //             productName: '',
            //             deviceCount: 0,
            //             deviceNums: [],
            //             source: 1, //1=设备，3=产品，4=告警，5=告警恢复
            //             type: 2, // 类型1=属性/2=功能，3=事件
            //             parentId: '', // 物模父级id
            //             parentName: '',
            //             parentModel: null, // 父级物模型
            //             model: null, // 物模型
            //             id: '',
            //             name: '',
            //             value: '',
            //             arrayIndex: '', // 索引，数组才有
            //             arrayIndexName: '',
            //             scriptPurpose: 3, // scriptPurpose:脚本用途(1=数据流，2=触发器，3=执行动作)
            //             userId: '',
            //             userName: '',
            //         },
            //     ];
            // }
            this.confirmLoading = false;
            this.updateBtnDisabled = false;
            this.resetForm('form');
        },
        // 触发器中，选择between操作符，值是A值和B值用中划线分割
        valueChange(value, item) {
            item.value = item.valueA + '-' + item.valueB;
        },
        // 搜索按钮操作value,item
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        // 重置按钮操作
        handleResetQuery() {
            this.resetForm('queryForm');
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.sceneId);
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },
        // 新增按钮操
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = this.$t('scene.index.670805-62');
        },
        // 修改按钮操作
        handleUpdate(row) {
            this.reset();
            const sceneId = row.sceneId || this.ids;
            getScene(sceneId).then((response) => {
                const datas = JSON.parse(JSON.stringify(response));
                this.form = response.data;
                // triggers赋值
                this.formJson.triggers = this.form.triggers;
                for (let i = 0; i < this.formJson.triggers.length; i++) {
                    // 定时
                    if (this.formJson.triggers[i].source == 2) {
                        if (this.formJson.triggers[i].isAdvance == 0) {
                            let arrayValue = this.formJson.triggers[i].cronExpression.substring(12).split(',').map(Number);
                            this.formJson.triggers[i].timerWeekValue = arrayValue;
                            let timerTimeValue = this.formJson.triggers[i].cronExpression.substring(5, 7) + ':' + this.formJson.triggers[i].cronExpression.substring(2, 4);
                            // 解决时间选择器不能编辑问题
                            this.$set(this.formJson.triggers[i], 'timerTimeValue', timerTimeValue);
                        }
                    } else if (this.formJson.triggers[i].source == 4) {
                    } else if (this.formJson.triggers[i].source == 5) {
                        this.formJson.triggers[i].sceneOperation.map((item, index) => {
                            item.deviceCount = 1;
                            item.deviceNums = [item.serialNumber];
                            item.scriptPurpose = 2;
                            this.formatSceneScript(this.formJson.triggers[i].sceneOperation[index], i);
                        });
                        console.log(this.formJson.triggers[i].sceneOperation, '9999999');
                        // 获取设备和物模型详情

                        this.$set(this.formJson.triggers[i], 'showOperator', true);
                    } else if (this.formJson.triggers[i].source === 6) {
                        this.formJson.triggers[i].energtype = this.formJson.triggers[i].sceneEneregy.energtype;
                        this.formatSceneScript(this.formJson.triggers[i], i);
                    } else {
                        // 获取设备和物模型详情
                        this.formatSceneScript(this.formJson.triggers[i], i);
                    }
                }
                // actions赋值
                this.formJson.actions = this.form.actions;
                for (let i = 0; i < this.formJson.actions.length; i++) {
                    // 获取设备和物模型详情
                    this.formatSceneScript(this.formJson.actions[i], i);
                }
                // 按钮可用
                setTimeout(() => {
                    this.updateBtnDisabled = false;
                }, 2000);
                this.open = true;
                this.title = this.$t('scene.index.670805-63');
            });
        },
        /**
         * 格式化显示场景脚本（触发器和执行动作）
         * sceneScript:触发器或动作
         * sceneScript.scriptPurpose：脚本用途(1=数据流，2=触发器，3=执行动作)
         */
        formatSceneScript(sceneScript, index) {
            if (sceneScript.scriptPurpose == 2) {
                // 获取物模型
                cacheJsonThingsModel(sceneScript.productId).then((response) => {
                    let data = JSON.parse(response.data);
                    sceneScript.thingsModel = this.formatArrayIndex(data);
                    // value赋值，value=valueA-valueB
                    if (sceneScript.value && sceneScript.value.indexOf('-') != -1) {
                        let values = sceneScript.value.split('-');
                        sceneScript.valueA = values[0];
                        sceneScript.valueB = values[1];
                    }
                    let sceneScripts = [];
                    if (sceneScript.type == 1) {
                        // 属性
                        sceneScripts = sceneScript.thingsModel.properties;
                    } else if (sceneScript.type == 2) {
                        // 功能
                        sceneScripts = sceneScript.thingsModel.functions;
                    } else if (sceneScript.type == 3) {
                        // 事件
                        sceneScripts = sceneScript.thingsModel.events;
                    }
                    // 父级物模型和物模型赋值
                    this.setParentAndModelData(sceneScript, sceneScripts);
                    // 解决数组在界面中不更新问题
                    this.$set(this.formJson.triggers, index, this.formJson.triggers[index]);
                });
            } else if (sceneScript.scriptPurpose == 3) {
                // 执行告警，没有物模型
                if (sceneScript.source == 4 || sceneScript.source == 6) {
                    return;
                }
                // 获取物模型
                cacheJsonThingsModel(sceneScript.productId).then((response) => {
                    let data = JSON.parse(response.data);
                    sceneScript.thingsModel = this.formatArrayIndex(data);
                    // 过滤监测数据和只读数据
                    if (sceneScript.thingsModel.properties) {
                        sceneScript.thingsModel.properties = sceneScript.thingsModel.properties.filter((item) => item.isMonitor == 0 && item.isReadonly == 0);
                        for (let i = 0; i < sceneScript.thingsModel.properties.length; i++) {
                            if (sceneScript.thingsModel.properties[i].datatype.params) {
                                sceneScript.thingsModel.properties[i].datatype.params = sceneScript.thingsModel.properties[i].datatype.params.filter((item) => item.isReadonly == 0);
                            }
                        }
                    }
                    if (sceneScript.thingsModel.functions) {
                        sceneScript.thingsModel.functions = sceneScript.thingsModel.functions.filter((item) => item.isReadonly == 0);
                        for (let i = 0; i < sceneScript.thingsModel.functions.length; i++) {
                            if (sceneScript.thingsModel.functions[i].datatype.params) {
                                sceneScript.thingsModel.functions[i].datatype.params = sceneScript.thingsModel.functions[i].datatype.params.filter((item) => item.isReadonly == 0);
                            }
                        }
                    }

                    let sceneScripts = [];
                    if (sceneScript.type == 1) {
                        // 属性
                        sceneScripts = sceneScript.thingsModel.properties;
                    } else if (sceneScript.type == 2) {
                        // 功能
                        sceneScripts = sceneScript.thingsModel.functions;
                    }
                    // 父级物模型和物模型赋值
                    this.setParentAndModelData(sceneScript, sceneScripts);
                    // 解决数组在界面中不更新问题
                    this.$set(this.formJson.actions, index, this.formJson.actions[index]);
                });
            }
        },
        // 设置父级物模型和物模型值
        setParentAndModelData(sceneScript, sceneScripts) {
            for (let i = 0; i < sceneScripts.length; i++) {
                if (sceneScript.parentId == sceneScripts[i].id) {
                    sceneScript.parentModel = sceneScripts[i];
                    if (sceneScript.parentModel.datatype.type === 'object') {
                        // 对象类型，物模型赋值
                        for (let j = 0; j < sceneScript.parentModel.datatype.params.length; j++) {
                            if (sceneScript.id == sceneScript.parentModel.datatype.params[j].id) {
                                sceneScript.model = sceneScript.parentModel.datatype.params[j];
                            }
                        }
                    } else if (sceneScript.parentModel.datatype.arrayType === 'object' && sceneScript.parentModel.datatype.type === 'array') {
                        // 对象数组类型，物模型集合移除索引前缀
                        if (sceneScript.id.indexOf('array_') != -1) {
                            sceneScript.id = sceneScript.id.substring(9);
                        }
                        // 物模型赋值
                        for (let j = 0; j < sceneScript.parentModel.datatype.params.length; j++) {
                            if (sceneScript.id == sceneScript.parentModel.datatype.params[j].id) {
                                sceneScript.model = sceneScript.parentModel.datatype.params[j];
                            }
                        }
                    } else if (sceneScript.parentModel.datatype.arrayType !== 'object' && sceneScript.parentModel.datatype.type === 'array') {
                        // 普通数组类型，物模型集合移除索引前缀
                        if (sceneScript.id.indexOf('array_') != -1) {
                            sceneScript.id = sceneScript.id.substring(9);
                        }
                        sceneScript.model = {
                            datatype: {
                                type: sceneScript.parentModel.datatype.arrayType,
                                maxLength: -1,
                                min: -1,
                                max: -1,
                                unit: this.$t('scene.index.670805-64'),
                            },
                        };
                    } else {
                        // 普通类型
                        sceneScript.model = sceneScript.parentModel;
                    }
                    break;
                }
            }
        },
        // 删除按钮操作
        handleDelete(row) {
            const sceneIds = row.sceneId || this.ids;
            this.$modal
                .confirm(this.$t('scene.index.670805-65', [sceneIds]))
                .then(function () {
                    return delScene(sceneIds);
                })
                .then(() => {
                    this.getList();
                    this.$modal.msgSuccess(this.$t('scene.index.670805-66'));
                })
                .catch(() => { });
        },
        // 执行一次
        handleRun(data) {
            const params = { sceneId: data.sceneId };
            runScene(params).then((res) => {
                this.$modal.msgSuccess(res.msg);
            });
        },

        /* Mqtt回调处理  */
        mqttCallback() {
            this.$mqttTool.client.on('message', (topic, message, buffer) => {
                if (message instanceof Uint8Array) {
                    // 创建TextDecoder对象来转换Uint8Array到字符串
                    const decoder = new TextDecoder('utf-8');
                    const str = decoder.decode(message);
                    message = str; //转换后的字符串
                }
                console.log('🚀 ~ this.$mqttTool.client.on ~ message:', message);
                console.log('🚀 ~ this.$mqttTool.client.on ~ topic:', topic);
                if (topic.indexOf('/' + this.logChainID + '/ruleengine/test') != -1) {
                    message = JSON.parse(message.toString());
                    this.logs += '[' + message.time + ']' + '-' + '[' + message.requestId + ']:' + message.log + '\n';
                }
            });
        },
        handleLog(data) {
            this.logLoading = true;
            openPublishLog(data.chainName).then((response) => {
                this.openLog = true;
                this.title = this.$t('scene.index.670805-67');
                this.logLoading = false;
                this.logChainID = data.chainName;
                let topic = '/' + c + '/ruleengine/test';
                this.$mqttTool.subscribe(topic);
            });
        },
        // 取消日志按钮
        cancelLog() {
            this.logs = '';
            this.openLog = false;
            closePublishLog(this.logChainID).then((response) => {
                let topic = '/' + this.logChainID + '/ruleengine/test';
                this.$mqttTool.unsubscribe(topic);
                this.logChainID = '';
            });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download(
                'iot/scene/export',
                {
                    ...this.queryParams,
                },
                `scene_${new Date().getTime()}.xlsx`
            );
        },
        // 选择能源
        handleTriggerEnergy(v, index) {
            // const energy = this.energyList.find(item => item.energyId == v)
            // this.formJson.triggers[index].energtype = v
            // console.log('v', v, 'index', index, energy)
            this.formJson.triggers[index].energtype = v;
        },
        // 触发器源改变事件
        handleTriggerSource(source, index) {
            this.formJson.triggers[index].deviceCount = 0;
            this.formJson.triggers[index].productId = '';
            this.formJson.triggers[index].productName = '';
            this.formJson.triggers[index].thingsModel = null;
            this.formJson.triggers[index].id = '';
            this.formJson.triggers[index].name = '';
            this.formJson.triggers[index].value = '';
            this.formJson.triggers[index].valueA = '';
            this.formJson.triggers[index].valueB = '';
            this.formJson.triggers[index].parentId = '';
            this.formJson.triggers[index].parentName = '';
            this.formJson.triggers[index].model = null;
            this.formJson.triggers[index].parentModel = null;
            this.formJson.triggers[index].operator = '';
            this.formJson.triggers[index].deviceNums = [];
            this.formJson.triggers[index].sceneOperation = [
                {
                    deviceCount: 0,
                },
            ];
            this.formJson.triggers[index].sceneRule = [
                {
                    ruleType: 0,
                    unit: '',
                    ruleValue: '',
                },
            ];
            // 定时
            this.formJson.triggers[index].timerTimeValue = ''; // 时间
            this.formJson.triggers[index].timerWeekValue = [1, 2, 3, 4, 5, 6, 7]; // 星期
        },
        handleActionSourceChange(source, index) {
            console.log('this.formJson.actions[index]', this.formJson.actions[index]);
            this.formJson.actions[index].deviceCount = 0;
            this.formJson.actions[index].productId = '';
            this.formJson.actions[index].productName = '';
            this.formJson.actions[index].thingsModel = null;
            this.formJson.actions[index].id = '';
            this.formJson.actions[index].name = '';
            this.formJson.actions[index].value = '';
            this.formJson.actions[index].valueA = '';
            this.formJson.actions[index].valueB = '';
            this.formJson.actions[index].parentId = '';
            this.formJson.actions[index].parentName = '';
            this.formJson.actions[index].model = null;
            this.formJson.actions[index].parentModel = null;
            this.formJson.actions[index].operator = '';
            this.formJson.actions[index].deviceNums = [];
            // 定时
            this.formJson.actions[index].timerTimeValue = ''; // 时间
            this.formJson.actions[index].timerWeekValue = [1, 2, 3, 4, 5, 6, 7]; // 星期
        },
        /* 选择设备
         *  type : 'trigger','action'
         */
        handleSelectDevice(type, item, index) {
            this.currentType = type;
            this.currentIndex = index;
            // 刷新子组件
            this.$refs.deviceList.queryParams.pageNum = 1;
            this.$refs.deviceList.openDeviceList = true;
            this.$refs.deviceList.selectDeviceNums = item.deviceNums;
            this.$refs.deviceList.productId = item.productId;
            this.$refs.deviceList.productName = item.productName;
            this.$refs.deviceList.queryParams.productId = item.productId;
            this.$refs.deviceList.getList();
        },
        /**选择产品 */
        handleSelectProduct(type, item, index) {
            this.currentType = type;
            this.currentIndex = index;
            // 刷新子组建
            this.$refs.productList.queryParams.pageNum = 1;
            this.$refs.productList.open = true;
            this.$refs.productList.selectProductId = item.productId;
            this.$refs.productList.getList();
        },
        /**添加场景*/
        handleSelectRecoverScenes() {
            this.$refs.sceneList.queryParams.pageNum = 1;
            this.$refs.sceneList.openScene = true;
            this.$refs.sceneList.selectSceneId = this.form.recoverId;
            this.$refs.sceneList.getList();
        },
        /**获取选中的产品或设备
         * type 1=设备集合，2=产品
         */
        getSelectProductDevice(data, type) {
            console.log(data, type, '9999999');
            if (this.currentType == null) {
                return;
            }
            if (this.currentType == 'trigger') {
                if (type == 1) {
                    this.formJson.triggers[this.currentIndex].deviceNums = data.deviceNums;
                    this.formJson.triggers[this.currentIndex].deviceCount = data.deviceNums.length;
                    this.formJson.triggers[this.currentIndex].productId = data.productId;
                    this.formJson.triggers[this.currentIndex].productName = data.productName;
                } else if (type == 2) {
                    this.formJson.triggers[this.currentIndex].deviceNums = [];
                    this.formJson.triggers[this.currentIndex].deviceCount = 0;
                    this.formJson.triggers[this.currentIndex].productId = data.productId;
                    this.formJson.triggers[this.currentIndex].productName = data.productName;
                }

                // 获取物模型
                cacheJsonThingsModel(data.productId).then((response) => {
                    let data = JSON.parse(response.data);
                    this.formJson.triggers[this.currentIndex].thingsModel = this.formatArrayIndex(data);
                    // 清楚之前数据
                    this.formJson.triggers[this.currentIndex].type = 1;
                    this.formJson.triggers[this.currentIndex].parentId = '';
                    this.formJson.triggers[this.currentIndex].parentName = '';
                    this.formJson.triggers[this.currentIndex].parentModel = null;
                    this.formJson.triggers[this.currentIndex].model = null;
                    this.formJson.triggers[this.currentIndex].operator = '';
                    this.formJson.triggers[this.currentIndex].id = '';
                    this.formJson.triggers[this.currentIndex].name = '';
                    this.formJson.triggers[this.currentIndex].value = '';
                    this.formJson.triggers[this.currentIndex].arrayIndex = '';
                    this.formJson.triggers[this.currentIndex].arrayIndexName = '';
                    // 解决数组在界面中不更新问题
                    this.$set(this.formJson.triggers, this.currentIndex, this.formJson.triggers[this.currentIndex]);
                });
            } else if (this.currentType == 'action') {
                if (type == 1) {
                    this.formJson.actions[this.currentIndex].deviceNums = data.deviceNums;
                    this.formJson.actions[this.currentIndex].deviceCount = data.deviceNums.length;
                    this.formJson.actions[this.currentIndex].productId = data.productId;
                    this.formJson.actions[this.currentIndex].productName = data.productName;
                } else if (type == 2) {
                    this.formJson.actions[this.currentIndex].deviceNums = [];
                    this.formJson.actions[this.currentIndex].deviceCount = 0;
                    this.formJson.actions[this.currentIndex].productId = data.productId;
                    this.formJson.actions[this.currentIndex].productName = data.productName;
                }

                // 获取物模型
                cacheJsonThingsModel(data.productId).then((response) => {
                    let data = JSON.parse(response.data);
                    this.formJson.actions[this.currentIndex].thingsModel = this.formatArrayIndex(data);
                    // 清楚之前数据
                    this.formJson.actions[this.currentIndex].type = 1;
                    this.formJson.actions[this.currentIndex].parentId = '';
                    this.formJson.actions[this.currentIndex].parentModel = null;
                    this.formJson.actions[this.currentIndex].parentName = '';
                    this.formJson.actions[this.currentIndex].model = null;
                    this.formJson.actions[this.currentIndex].operator = '';
                    this.formJson.actions[this.currentIndex].id = '';
                    this.formJson.actions[this.currentIndex].name = '';
                    this.formJson.actions[this.currentIndex].value = '';
                    this.formJson.actions[this.currentIndex].arrayIndex = '';
                    this.formJson.actions[this.currentIndex].arrayIndexName = '';
                    // 过滤监测数据和只读数据
                    if (this.formJson.actions[this.currentIndex].thingsModel.properties) {
                        this.formJson.actions[this.currentIndex].thingsModel.properties = this.formJson.actions[this.currentIndex].thingsModel.properties.filter((item) => item.isMonitor == 0 && item.isReadonly == 0);
                        for (let i = 0; i < this.formJson.actions[this.currentIndex].thingsModel.properties.length; i++) {
                            if (this.formJson.actions[this.currentIndex].thingsModel.properties[i].datatype.params) {
                                this.formJson.actions[this.currentIndex].thingsModel.properties[i].datatype.params = this.formJson.actions[this.currentIndex].thingsModel.properties[i].datatype.params.filter(
                                    (item) => item.isMonitor == 0 && item.isReadonly == 0
                                );
                            }
                        }
                    }
                    if (this.formJson.actions[this.currentIndex].thingsModel.functions) {
                        this.formJson.actions[this.currentIndex].thingsModel.functions = this.formJson.actions[this.currentIndex].thingsModel.functions.filter((item) => item.isReadonly == 0);
                        for (let i = 0; i < this.formJson.actions[this.currentIndex].thingsModel.functions.length; i++) {
                            if (this.formJson.actions[this.currentIndex].thingsModel.functions[i].datatype.params) {
                                this.formJson.actions[this.currentIndex].thingsModel.functions[i].datatype.params = this.formJson.actions[this.currentIndex].thingsModel.functions[i].datatype.params.filter(
                                    (item) => item.isMonitor == 0 && item.isReadonly == 0
                                );
                            }
                        }
                    }
                    // 解决数组在界面中不更新问题
                    this.$set(this.formJson.actions, this.currentIndex, this.formJson.actions[this.currentIndex]);
                });
            }
        },
        getSceneData(data) {
            this.form.recoverId = data.sceneId;
            this.form.recoverSceneName = data.sceneName;
        },
        handleSelectDevice1(type, item, index, index1) {
            this.currentType1 = type;
            this.currentIndex1 = index;
            this.currentIndexItem = index1;
            this.$refs.deviceList1.queryParams.pageNum = 1;
            this.$refs.deviceList1.openDeviceList = true;
            this.$refs.deviceList1.selectDeviceNums = item.deviceNums;
            this.$refs.deviceList1.productId = item.productId;
            this.$refs.deviceList1.productName = item.productName;
            this.$refs.deviceList1.queryParams.productId = item.productId;
            console.log(this.$refs.deviceList.queryParams, '1111111');
            this.$refs.deviceList1.getList();
        },
        handleActionParentModelChange1(identifier, index, val, itemIndex, item) {
            const nowData = val.thingsModel.properties.find((item) => {
                return item.id == identifier;
            });
            this.formJson.triggers[itemIndex].sceneOperation[index].name = nowData.name;
            item.showOperator = true;

            this.$set(this.formJson.triggers, itemIndex, this.formJson.triggers[itemIndex]);
        },
        jumpUnit(index) {
            const datas = this.formJson.triggers[index].sceneOperation && this.formJson.triggers[index].sceneOperation[0].thingsModel;
            let units = '';
            if (datas) {
                datas.properties &&
                    datas.properties.map((item) => {
                        if (item.id == this.formJson.triggers[index].sceneOperation[0].id) {
                            units = item.datatype.unit;
                        }
                    });
            }
            return units;
        },
        operatorChange(itemIndex) {
            this.$set(this.formJson.triggers, itemIndex, this.formJson.triggers[itemIndex]);
        },
        getSelectProductDevice1(data, type) {
            if (this.currentType1 == null) {
                return;
            }
            const currentIndexItem = this.currentIndexItem;
            this.formJson.triggers[currentIndexItem].deviceNums = data.deviceNums;
            this.formJson.triggers[currentIndexItem].deviceCount = data.deviceNums.length;
            this.formJson.triggers[currentIndexItem].productId = data.productId;
            this.formJson.triggers[currentIndexItem].productName = data.productName;
            console.log(this.formJson.triggers, this.currentIndex1);
            this.formJson.triggers[currentIndexItem].sceneOperation[this.currentIndex1].deviceNums = data.deviceNums;
            this.formJson.triggers[currentIndexItem].sceneOperation[this.currentIndex1].serialNumber = data.deviceNums[0];
            this.formJson.triggers[currentIndexItem].sceneOperation[this.currentIndex1].deviceCount = data.deviceNums.length;
            this.formJson.triggers[currentIndexItem].sceneOperation[this.currentIndex1].productId = data.productId;
            this.formJson.triggers[currentIndexItem].sceneOperation[this.currentIndex1].productName = data.productName;
            // 获取物模型
            cacheJsonThingsModel(data.productId).then((response) => {
                let data = JSON.parse(response.data);
                this.formJson.triggers[currentIndexItem].sceneOperation[this.currentIndex1].thingsModel = this.formatArrayIndex(data);
                // 清楚之前数据
                this.formJson.triggers[currentIndexItem].sceneOperation[this.currentIndex1].type = 1;
                this.formJson.triggers[currentIndexItem].sceneOperation[this.currentIndex1].parentId = '';
                this.formJson.triggers[currentIndexItem].sceneOperation[this.currentIndex1].parentName = '';
                this.formJson.triggers[currentIndexItem].sceneOperation[this.currentIndex1].parentModel = null;
                this.formJson.triggers[currentIndexItem].sceneOperation[this.currentIndex1].model = null;
                this.formJson.triggers[currentIndexItem].sceneOperation[this.currentIndex1].operator = '';
                this.formJson.triggers[currentIndexItem].sceneOperation[this.currentIndex1].id = '';
                this.formJson.triggers[currentIndexItem].sceneOperation[this.currentIndex1].name = '';
                this.formJson.triggers[currentIndexItem].sceneOperation[this.currentIndex1].value = '';
                this.formJson.triggers[currentIndexItem].sceneOperation[this.currentIndex1].arrayIndex = '';
                this.formJson.triggers[currentIndexItem].sceneOperation[this.currentIndex1].arrayIndexName = '';
                // 解决数组在界面中不更新问题
                this.$set(this.formJson.triggers, this.currentIndexItem, this.formJson.triggers[this.currentIndexItem]);
                console.log(this.formJson.triggers, '11111111111111');
            });
        },
        handleSceneRule(val, index, item) {
            const choosed = this.sceneRuleList.find((item) => {
                return item.value == val;
            });
            if (!val) {
                item.sceneRule[0].ruleValue = '';
            }
            item.sceneRule[0].unit = choosed.unit;
        },
        handleDelOne(index, inx) {
            this.formJson.triggers[index].sceneOperation.splice(inx, 1);
            this.$set(this.formJson.triggers, index, this.formJson.triggers[index]);
        },
        handleAddOne(index) {
            this.formJson.triggers[index].sceneOperation.push({
                deviceCount: 0,
            });
            this.$set(this.formJson.triggers, index, this.formJson.triggers[index]);
        },
        // 物模型格式化处理
        formatArrayIndex(data) {
            let obj = { ...data };
            for (let o in obj) {
                obj[o] = obj[o].map((item) => {
                    if (item.datatype.type === 'array') {
                        let arrayModel = [];
                        for (let k = 0; k < item.datatype.arrayCount; k++) {
                            let index = k > 9 ? String(k) : '0' + k;
                            if (item.datatype.arrayType === 'object') {
                                arrayModel.push({
                                    id: index,
                                    name: item.name + ' ' + (k + 1),
                                });
                            } else {
                                arrayModel.push({
                                    id: index,
                                    name: item.name + ' ' + (k + 1),
                                });
                            }
                        }
                        item.datatype.arrayModel = arrayModel;
                    }
                    return item;
                });
            }
            return obj;
        },
        // 触发器类型改变事件
        handleTriggerTypeChange(source, index) {
            this.formJson.triggers[index].id = '';
            this.formJson.triggers[index].name = '';
            this.formJson.triggers[index].model = null;
            this.formJson.triggers[index].operator = '';
            this.formJson.triggers[index].value = '';
            this.formJson.triggers[index].valueA = '';
            this.formJson.triggers[index].valueB = '';
            this.formJson.triggers[index].parentId = '';
            this.formJson.triggers[index].parentName = '';
            this.formJson.triggers[index].parentModel = null;
            this.formJson.triggers[index].arrayIndex = '';
            this.formJson.triggers[index].arrayIndexName = '';
        },
        // 触发器父级物模型选择
        handleTriggerParentModelChange(identifier, index) {
            this.formJson.triggers[index].operator = '';
            this.formJson.triggers[index].value = '';
            this.formJson.triggers[index].valueA = '';
            this.formJson.triggers[index].valueB = '';
            this.formJson.triggers[index].arrayIndex = '';
            this.formJson.triggers[index].arrayIndexName = '';
            this.formJson.triggers[index].model = null;

            let sceneScripts = [];
            if (this.formJson.triggers[index].type == 1) {
                // 属性
                sceneScripts = this.formJson.triggers[index].thingsModel.properties;
            } else if (this.formJson.triggers[index].type == 2) {
                //功能
                sceneScripts = this.formJson.triggers[index].thingsModel.functions;
            } else if (this.formJson.triggers[index].type == 3) {
                //事件
                sceneScripts = this.formJson.triggers[index].thingsModel.events;
            }
            // 物模型赋值
            for (let i = 0; i < sceneScripts.length; i++) {
                if (sceneScripts[i].id == identifier) {
                    this.formJson.triggers[index].parentName = sceneScripts[i].name;
                    this.formJson.triggers[index].parentModel = sceneScripts[i];
                    if (sceneScripts[i].datatype.type === 'object') {
                        // 对象类型
                        this.formJson.triggers[index].id = '';
                        this.formJson.triggers[index].name = '';
                    } else if (sceneScripts[i].datatype.type === 'array' && sceneScripts[i].datatype.arrayType === 'object') {
                        // 对象数组类型
                        this.formJson.triggers[index].id = '';
                        this.formJson.triggers[index].name = '';
                    } else if (sceneScripts[i].datatype.type === 'array' && sceneScripts[i].datatype.arrayType !== 'object') {
                        // 普通类型，数组类
                        this.formJson.triggers[index].id = sceneScripts[i].id;
                        this.formJson.triggers[index].name = sceneScripts[i].name;
                        // 用于减少界面判断
                        this.formJson.triggers[index].model = {
                            datatype: {
                                type: this.formJson.triggers[index].parentModel.datatype.arrayType,
                                maxLength: -1,
                                min: -1,
                                max: -1,
                                unit: this.$t('scene.index.670805-64'),
                            },
                        };
                    } else {
                        // 普通类型,不包含数组类型
                        this.formJson.triggers[index].id = sceneScripts[i].id;
                        this.formJson.triggers[index].name = sceneScripts[i].name;
                        this.formJson.triggers[index].model = sceneScripts[i];
                    }
                    break;
                }
            }
            //能源触发的点击逻辑
            if (this.formJson.triggers[index].source === 6) {
                console.log('11111111');
                const data = {
                    identifier: identifier,
                    deviceNum: this.formJson.triggers[index].deviceNums[index],
                };
                getEnergyType(data).then((rp) => {
                    if (rp.Type != null) {
                        console.log(rp.Type);
                        this.formJson.triggers[index].energtype = rp.Type;
                    }
                    this.tpyeopen = true;
                });
            }
        },
        // 触发器-物模数组索引选择
        handleTriggerIndexChange(id, index) {
            this.formJson.triggers[index].arrayIndexName = this.formJson.triggers[index].parentModel.datatype.arrayModel.find((x) => x.id == id).name;
            this.formJson.triggers[index].value = '';
            this.formJson.triggers[index].valueA = '';
            this.formJson.triggers[index].valueB = '';
            this.formJson.triggers[index].operator = '';
            // 数组类型保留id和name
            if (this.formJson.triggers[index].parentModel.datatype.arrayType === 'object') {
                this.formJson.triggers[index].id = '';
                this.formJson.triggers[index].name = '';
            }
        },
        // 触发器物模选择
        handleTriggerModelChange(id, index) {
            this.formJson.triggers[index].operator = '';
            this.formJson.triggers[index].value = '';
            this.formJson.triggers[index].valueA = '';
            this.formJson.triggers[index].valueB = '';
            let model = null;
            if (this.formJson.triggers[index].parentModel.datatype.type === 'array' || this.formJson.triggers[index].parentModel.datatype.type === 'object') {
                model = this.formJson.triggers[index].parentModel.datatype.params.find((item) => item.id == id);
                this.formJson.triggers[index].name = model.name;
                this.formJson.triggers[index].model = model;
            }
        },
        // 添加触发器
        handleAddTrigger() {
            this.formJson.triggers.push({
                source: 1, //1=设备，2=定时,3=产品
                type: 1, // 类型
                id: '',
                name: '',
                operator: '',
                value: '',
                // between操作符时，值=值A-值B
                valueA: '',
                valueB: '',
                model: null,
                parentModel: null,
                parentId: '', // 物模父级id
                parentName: '',
                arrayIndex: '', // 索引，数组才有
                arrayIndexName: '',
                isAdvance: 0, // 自定义CRON
                cronExpression: '', // cron表达式
                timerTimeValue: '', // 时间
                timerWeekValue: [1, 2, 3, 4, 5, 6, 7], // 星期
                productId: 0,
                productName: '',
                deviceNums: [],
                deviceCount: 0,
                scriptPurpose: 2, // scriptPurpose:脚本用途(1=数据流，2=触发器，3=执行动作)
                sceneRule: [
                    {
                        ruleType: 0,
                        unit: '',
                        ruleValue: '',
                    },
                ],
            });
        },
        // 添加动作
        handleAddAction() {
            console.log('this.formJson', this.formJson);
            if (this.formJson.actions[this.formJson.actions.length - 1].source == 6) {
                if (this.formJson.actions[this.formJson.actions.length - 1].userName.length <= 0) {
                    return Message.error('请输入执行人！');
                }
            }
            this.formJson.actions.push({
                source: 1, //1=设备，3=产品，4=告警
                type: 2, // 类型
                id: '',
                name: '',
                value: '',
                model: null,
                parentId: '', // 物模id
                parentName: '',
                parentModel: null,
                arrayIndex: '', // 索引，数组才有
                arrayIndexName: '',
                productId: 0,
                productName: '',
                deviceNums: [],
                deviceCount: 0,
                scriptPurpose: 3, // scriptPurpose:脚本用途(1=数据流，2=触发器，3=执行动作)
                userName: '',
            });
        },
        // 删除触发器
        handleRemoveTrigger(index) {
            this.formJson.triggers.splice(index, 1);
        },
        // 删除动作
        handleRemoveAction(index) {
            this.formJson.actions.splice(index, 1);
        },
        /** cron表达式按钮操作 */
        handleShowCron(item, index) {
            this.expression = item.cronExpression;
            this.triggerIndex = index;
            this.openCron = true;
        },
        /** 确定后回传值 */
        crontabFill(value) {
            this.formJson.triggers[this.triggerIndex].cronExpression = value;
        },
        /** 星期改变事件 **/
        weekChange(data, index) {
            this.gentCronExpression(index);
        },
        /** 时间改变事件 **/
        timeChange(data, index) {
            this.gentCronExpression(index);
        },
        /**自定义cron表达式选项改变事件 */
        customerCronChange(data, index) { },
        /** 生成cron表达式**/
        gentCronExpression(index) {
            let hour = '00';
            let minute = '00';
            if (this.formJson.triggers[index].timerTimeValue != null && this.formJson.triggers[index].timerTimeValue != '') {
                hour = this.formJson.triggers[index].timerTimeValue.substring(0, 2);
                minute = this.formJson.triggers[index].timerTimeValue.substring(3);
            }
            let week = '*';
            if (this.formJson.triggers[index].timerWeekValue.length > 0) {
                let order = this.formJson.triggers[index].timerWeekValue.slice().sort();
                for (let i = 0; i < order.length; i++) {
                    if (order[i] != 7) {
                        order[i] = order[i] + 1;
                    } else {
                        order[i] = 1;
                    }
                }
                console.log(order);
                week = order;
                //week = this.formJson.triggers[index].timerWeekValue.sort();
                console.log(week);
            }
            this.formJson.triggers[index].cronExpression = '0 ' + minute + ' ' + hour + ' ? * ' + week;
        },
        // 动作类型改变事件
        handleActionTypeChange(data, index) {
            this.formJson.actions[index].id = '';
            this.formJson.actions[index].name = '';
            this.formJson.actions[index].value = '';
            this.formJson.actions[index].model = null;
            this.formJson.actions[index].parentId = '';
            this.formJson.actions[index].parentName = '';
            this.formJson.actions[index].arrayIndex = '';
            this.formJson.actions[index].arrayIndexName = '';
            this.formJson.actions[index].parentModel = null;
            this.formJson.actions[index].userName = null;
            this.formJson.actions[index].userId = null;
        },
        // 动作物模型项改变事件
        handleActionParentModelChange(identifier, index) {
            this.formJson.actions[index].model = null;
            this.formJson.actions[index].value = '';
            this.formJson.actions[index].arrayIndex = '';
            this.formJson.actions[index].arrayIndexName = '';

            let sceneScripts = [];
            if (this.formJson.actions[index].type == 1) {
                //属性
                sceneScripts = this.formJson.actions[index].thingsModel.properties;
            } else if (this.formJson.actions[index].type == 2) {
                //功能
                sceneScripts = this.formJson.actions[index].thingsModel.functions;
            }
            for (let i = 0; i < sceneScripts.length; i++) {
                if (sceneScripts[i].id == identifier) {
                    this.formJson.actions[index].parentName = sceneScripts[i].name;
                    this.formJson.actions[index].parentModel = sceneScripts[i];
                    if (sceneScripts[i].datatype.type === 'object') {
                        // 对象类型
                        this.formJson.actions[index].id = '';
                        this.formJson.actions[index].name = '';
                    } else if (sceneScripts[i].datatype.type === 'array' && sceneScripts[i].datatype.arrayType === 'object') {
                        // 对象数组类型
                        this.formJson.actions[index].id = '';
                        this.formJson.actions[index].name = '';
                    } else if (sceneScripts[i].datatype.type === 'array' && sceneScripts[i].datatype.arrayType !== 'object') {
                        // 普通类型，数组类
                        this.formJson.actions[index].id = sceneScripts[i].id;
                        this.formJson.actions[index].name = sceneScripts[i].name;
                        // 用于减少界面判断
                        this.formJson.actions[index].model = {
                            datatype: {
                                type: this.formJson.actions[index].parentModel.datatype.arrayType,
                                maxLength: -1,
                                min: -1,
                                max: -1,
                                unit: this.$t('scene.index.670805-64'),
                            },
                        };
                    } else {
                        // 普通类型,不包含数组类型
                        this.formJson.actions[index].id = sceneScripts[i].id;
                        this.formJson.actions[index].name = sceneScripts[i].name;
                        this.formJson.actions[index].model = sceneScripts[i];
                    }
                    break;
                }
            }
        },
        // 执行动作物模型数组索引选择
        handleActionIndexChange(id, index) {
            this.formJson.actions[index].arrayIndexName = this.formJson.actions[index].parentModel.datatype.arrayModel.find((x) => x.id == id).name;
            this.formJson.actions[index].value = '';
            this.formJson.actions[index].valueA = '';
            this.formJson.actions[index].valueB = '';
            this.formJson.actions[index].operator = '';
            // 数组类型保留id和name
            if (this.formJson.actions[index].parentModel.datatype.arrayType === 'object') {
                this.formJson.actions[index].id = '';
                this.formJson.actions[index].name = '';
            }
        },
        // 执行动作物模型选择
        handleActionModelChange(id, index) {
            this.formJson.actions[index].operator = '';
            this.formJson.actions[index].value = '';
            let model = null;
            if (this.formJson.actions[index].parentModel.datatype.type === 'array' || this.formJson.actions[index].parentModel.datatype.type === 'object') {
                model = this.formJson.actions[index].parentModel.datatype.params.find((item) => item.id == id);
                this.formJson.actions[index].name = model.name;
                this.formJson.actions[index].model = model;
            }
        },
        // 提交按钮
        handleSubmitForm() {
            if (this.formJson.actions[this.formJson.actions.length - 1].source == 6) {
                if (this.formJson.actions[this.formJson.actions.length - 1].userName.length <= 0) {
                    return Message.error('请输入执行人！');
                }
            }
            let triggers = [];
            let actions = [];
            // 触发器验证和构建
            for (let i = 0; i < this.formJson.triggers.length; i++) {
                // 类型为属性/功能/事件
                if (this.formJson.triggers[i].type == 1 || this.formJson.triggers[i].type == 2 || this.formJson.triggers[i].type == 3) {
                    // 值不能为空
                    if (this.formJson.triggers[i].source == 1) {
                        if (this.formJson.triggers[i].value == '') {
                            this.$modal.alertError(this.$t('scene.index.670805-67'));
                            return;
                        } else if (this.formJson.triggers[i].value.indexOf('-') != -1) {
                            // 区间格式10-50
                            if (this.formJson.triggers[i].valueA == '' || this.formJson.triggers[i].valueB == '') {
                                this.$modal.alertError(this.$t('scene.index.670805-68'));
                                return;
                            }
                        }
                    }
                    // 定时时间不能为空
                    if (this.formJson.triggers[i].source == 2) {
                        if (this.formJson.triggers[i].isAdvance == 0) {
                            if (this.formJson.triggers[i].timerTimeValue == '' || this.formJson.triggers[i].timerTimeValue == null) {
                                this.$modal.alertError(this.$t('scene.index.670805-69'));
                                return;
                            }
                            if (this.formJson.triggers[i].timerWeekValue == null || this.formJson.triggers[i].timerWeekValue == '') {
                                this.$modal.alertError(this.$t('scene.index.670805-70'));
                                return;
                            }
                        } else if (this.formJson.triggers[i].isAdvance == 1) {
                            if (this.formJson.triggers[i].cronExpression == '') {
                                this.$modal.alertError(this.$t('scene.index.670805-71'));
                                return;
                            }
                        }
                    }
                }
                // 数据重组
                let item = this.formJson.triggers[i];
                // id拼接array索引
                if (item.arrayIndex != '') {
                    item.id = 'array_' + item.arrayIndex + '_' + item.id;
                }
                // 只传需要的数据
                triggers[i] = {
                    productId: item.productId,
                    productName: item.productName,
                    deviceNums: item.deviceNums,
                    deviceCount: item.deviceCount,
                    source: item.source,
                    type: item.type,
                    id: item.id,
                    name: item.name,
                    operator: item.operator,
                    value: item.value,
                    isAdvance: item.isAdvance,
                    cronExpression: item.cronExpression,
                    parentId: item.parentId,
                    parentName: item.parentName,
                    arrayIndex: item.arrayIndex,
                    arrayIndexName: item.arrayIndexName,
                    scriptPurpose: 2, // scriptPurpose:脚本用途(1=数据流，2=触发器，3=执行动作)
                    sceneOperation: item.sceneOperation,
                    sceneRule: item.sceneRule,
                    energtype: item.energtype,
                };
                if (item.source === 5) {
                    triggers[i].name = item.sceneOperation[item.sceneOperation.length - 1].name;
                    triggers[i].parentName = item.sceneOperation[item.sceneOperation.length - 1].name;
                    triggers[i].id = item.sceneOperation[item.sceneOperation.length - 1].id;
                    triggers[i].parentId = item.sceneOperation[item.sceneOperation.length - 1].id;
                }
            }
            // 动作验证和构建
            for (let i = 0; i < this.formJson.actions.length; i++) {
                if (this.formJson.actions[i].value === '' && this.formJson.actions[i].source !== 4 && this.formJson.actions[i].source !== 5 && this.formJson.actions[i].source !== 6) {
                    this.$modal.alertError(this.$t('scene.index.670805-72'));
                    return;
                }
                // 数据重组
                let item = this.formJson.actions[i];
                // id拼接array索引
                if (item.arrayIndex != '') {
                    item.id = 'array_' + item.arrayIndex + '_' + item.id;
                }
                // 只传需要的数据
                actions[i] = {
                    productId: item.productId,
                    productName: item.productName,
                    deviceCount: item.deviceCount,
                    source: item.source,
                    deviceNums: item.deviceNums,
                    type: item.type,
                    id: item.id,
                    name: item.name,
                    value: item.value,
                    parentId: item.parentId,
                    parentName: item.parentName,
                    arrayIndex: item.arrayIndex,
                    arrayIndexName: item.arrayIndexName,
                    scriptPurpose: 3, // scriptPurpose:脚本用途(1=数据流，2=触发器，3=执行动作)
                    userId: item.userId,
                };
            }
            // 判断是否包含告警(1=包含，2=不包含)
            if (actions.filter((x) => x.source === 4).length > 0) {
                this.form.hasAlert = 1;
            } else {
                this.form.hasAlert = 2;
            }
            this.form.triggers = triggers;
            this.form.actions = actions;
            this.confirmLoading = true;
            this.form.triggers.forEach((item) => {
                item.sceneEneregy = {
                    productId: item.productId,
                    productName: item.productName,
                    id: item.id,
                    name: item.name,
                    serialNumber: item.deviceNums[0],
                    energtype: item.energtype,
                };
            });
            if (this.form.sceneId != null) {
                updateScene(this.form).then(() => {
                    this.$modal.msgSuccess(this.$t('scene.index.670805-73'));
                    this.open = false;
                    this.confirmLoading = false;
                    this.getList();
                });
            } else {
                addScene(this.form).then(() => {
                    this.$modal.msgSuccess(this.$t('scene.index.670805-74'));
                    this.open = false;
                    this.confirmLoading = false;
                    this.getList();
                });
            }
        },
    },
    mounted() {
        //初始化上下拖动
        this.dragControllerUD();
        //加载作业目录树
        this.getCatalogueTreeList();
        //加载流程引擎
        this.lf = new LogicFlow({
            container: this.$refs['flowContainer'],
            grid: {
                visible: true,
                type: 'mesh',
                size: 10,
                config: {
                    color: '#eeeeee',
                },
            },
            keyboard: {
                enabled: true,
            },
            // 注册组件
            plugins: [Menu, Control, SelectionSelect, DndPanel, Snapshot],
        });
        //注册任务节点

        this.lf.register(TaskModel);
        // register(
        //     {
        //         type: 'UserTask',
        //         component: TaskNode,
        //         properties: {
        //             progress: 60,
        //             width: 240,
        //             height: 150,
        //         },
        //     },
        //     this.lf
        // );

        //注册连线
        this.lf.register(FlowLink);
        this.lf.setDefaultEdgeType('flow-link');
        document.getElementById('snapshotDownloadId').addEventListener('click', () => {
            this.lf.getSnapshot();
        });
        this.lf.extension.control.addItem({
            key: 'clear',
            iconClass: 'lf-control-clear',
            title: '',
            text: '清空',
            onClick: (lf, ev) => {
                lf.clearData();
            },
        });
        let that = this;
        this.lf.extension.control.addItem({
            key: 'save',
            iconClass: 'lf-control-save',
            title: '',
            text: '保存',
            onClick: (lf, ev) => {
                that.saveFrom(lf, ev);
            },
        });
        this.lf.extension.control.addItem({
            key: 'download',
            iconClass: 'lf-control-download',
            title: '',
            text: '导出',
            onClick: (lf, ev) => {
                document.getElementById('snapshotDownloadId').dispatchEvent(new MouseEvent('click'));
            },
        });

        this.lf.setTheme({
            snapline: {
                stroke: '#ace2ff', // 对齐线颜色
                strokeWidth: 1, // 对齐线宽度
            },
        });
        //设置右键菜单
        this.lf.extension.menu.setMenuConfig({
            nodeMenu: [
                {
                    text: '查看',
                    callback(node) {
                        that.nodeEdit(node);
                    },
                },
                {
                    text: '删除',
                    callback(node) {
                        that.lf.deleteNode(node.id);
                    },
                },
            ], // 覆盖默认的节点右键菜单
            //edgeMenu: false, // 删除默认的边右键菜单
            graphMenu: [], // 覆盖默认的边右键菜单，与false表现一样
        });
        //监听新增的拖拽节点
        this.lf.on('node:dnd-add', (data) => {
            console.log('datadatata', data);
            if (data.data.properties.type == 'trigger') {
            } else {
                this.nodeEdit(data.data);
            }
        });

        this.init('', '');
        //渲染
        //this.lf.render(graphData)
    },
};
</script>
<style lang="scss">
#flowContainer {
    height: 100%;
    width: 100%;
    /* height: calc(100vh - 200px); */
}

.dnd-class {
    padding: 7px;
}

/* 主矿体 */
.flowTopBox {
    height: 70%;
    display: flex;
}

/* 左侧布局 */
.leftFlowBox {
    height: 100%;
    flex: 1;
}

/* 右侧布局 */
.rightFlowBox {
    height: 100%;
    flex: 5;
}

/* 拖拽区div样式 */
.flowBottomResize {
    overflow: hidden;
    cursor: s-resize;
    width: 100%;
    height: 10px;
    background-color: #d6d6d6;
    margin: 0 auto;
    border-radius: 5px;
    text-align: center;
    line-height: 3px;
    font-size: 32px;
    color: white;
}

/* 底部box */
.flowBottomBox {
    height: calc(30% - 10px);
}

/* 树节点相关属性 */
.flowdiv .el-tree-node__content {
    height: 35px;
}

.flow-tree-node {
    font-size: 16px;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

.flow-tree-drag—node {
    font-size: 16px;
    cursor: move;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

.flowBottomTabs {
    height: 100%;
}

.flowBottomTabs>.el-tabs__content {
    height: calc(100% - 40px);
    padding: 0;
}

/* 每个tab高度设置为100% */
.flowBottomTabs>.el-tabs__content>.el-tab-pane {
    height: 100%;
}

.flowBottomTabs .flowCustomTabsLabel {
    font-size: 16px;
}

.flowBottomTabs>.el-tabs__header {
    padding: 0;
    position: relative;
    margin: 0 0 0;
}

.el-notification.right {
    height: 100px;
}

.action-form-item {
    .el-form-item__label {
        display: block;
        float: none;
        text-align: center;
        width: 100% !important;
        font-size: 18px;
        margin-bottom: 10px;
    }

    .el-form-item__content {
        margin-left: 0 !important;
    }

    .action-box {
        position: relative;
        /* border: 1px solid; */
        padding: 20px;
        background-color: #fafafa;
        border-radius: 10px;

        .action-row {
            margin-bottom: 10px;
        }

        .el-row {
            position: relative;
        }

        .action-icon {
            position: absolute;
            right: 0;
            top: -35px;
            font-size: 25px;
            color: #409eff;
            cursor: pointer;

            &.delete-icon {
                font-size: 20px;
                top: 9px;
                color: #f56c6c;
            }
        }
    }
}

.scene-config-dialog {

    .condition-wrap,
    .action-wrap {
        position: relative;

        .trigger-type-wrap {
            margin-bottom: 10px;

            ::v-deep .el-input__inner {
                /**border: none;*/
                box-shadow: none;
            }
        }

        .item-wrap {
            margin-bottom: 15px;
            padding: 10px;
            background-color: #d9e5f6;
            border-radius: 5px;

            .delete-wrap {
                position: absolute;
                right: 10px;
                top: 0;
            }
        }
    }
}
</style>
