<template>
    <el-card style="margin: 6px; padding-bottom: 100px" class="main-card">
        <el-tabs v-model="activeName" style="padding: 10px; min-height: 400px" tab-position="left"
            @tab-click="tabChange">
            <el-tab-pane name="basic">
                <span slot="label">
                    <span style="color: red">*</span>
                    {{ $t('product.product-edit.473153-0') }}
                </span>
                <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                    <el-row :gutter="100">
                        <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="8">
                            <el-form-item :label="$t('product.product-edit.473153-1')" prop="productName">
                                <el-input v-model="form.productName" :placeholder="$t('product.product-edit.473153-2')"
                                    :readonly="form.status == 2 || form.isOwner == 0" />
                            </el-form-item>
                            <el-form-item :label="$t('product.product-edit.473153-3')" prop="categoryId">
                                <el-select v-model="form.categoryId" :placeholder="$t('product.product-edit.473153-4')"
                                    @change="selectCategory" style="width: 100%"
                                    :disabled="form.status == 2 || form.isOwner == 0">
                                    <el-option v-for="category in categoryShortList" :key="category.id"
                                        :label="category.name" :value="category.id"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item v-if="form.deviceType !== 3" label="通讯协议" prop="protocolCode">
                                <template slot="label">
                                    <span>通讯协议</span>
                                    <el-tooltip effect="light" placement="bottom" style="cursor: pointer">
                                        <div slot="content">
                                            产品建立后，不允许修改通讯协议,修改会导致该产品下设备脏数据问题
                                            <br />
                                        </div>
                                        <i class="el-icon-question" />
                                    </el-tooltip>
                                </template>
                                <el-select v-model="form.protocolCode"
                                    :disabled="form.status == 2 || form.productId != 0 || form.isOwner == 0"
                                    placeholder="请选择协议" style="width: 100%" @change="changeProductCode">
                                    <el-option v-for="p in protocolList" :key="p.protocolCode" :label="p.protocolName"
                                        :value="p.protocolCode" />
                                </el-select>
                            </el-form-item>
                            <el-form-item v-if="form.deviceType !== 3 && tempOpen">
                                <template>
                                    <el-alert description="当前通讯协议为modbus协议,请选择采集点模板,默认添加设备为网关设备"
                                        type="success"></el-alert>
                                </template>
                            </el-form-item>
                            <el-form-item v-if="tempOpen && selectRowData" prop="templateId">
                                <span slot="label">
                                    <span style="color: #f56c6c">*</span>
                                    采集点模板
                                </span>
                                <div style="display: inline-block; padding-right: 5px">
                                    <span
                                        style="font-size: 9px; padding-right: 5px; color: #00bb00; font-size: 12px; font-weight: bold">{{
                                            selectRowData.templateName }}</span>
                                    <el-button :disabled="form.status == 2 || form.productId != 0 || form.isOwner == 0"
                                        plain size="mini" @click="deleteData">删除</el-button>
                                </div>
                                <el-button plain size="mini" type="primary"
                                    :disabled="form.status == 2 || form.productId != 0 || form.isOwner == 0"
                                    @click="selectTemplate">选择模板</el-button>
                            </el-form-item>
                            <el-form-item :label="$t('product.product-edit.473153-78')" prop="deviceType">
                                <el-select v-model="form.deviceType" :disabled="form.productId != 0"
                                    placeholder="请选择设备类型" style="width: 100%">
                                    <el-option v-for="dict in dict.type.iot_device_type" :key="dict.value"
                                        :label="dict.label" :value="parseInt(dict.value)"></el-option>
                                </el-select>
                            </el-form-item>
                            <!-- <el-form-item v-if="form.deviceType !== 3" :label="$t('product.product-edit.473153-81')" prop="protocolCode">
                                <el-select
                                    v-model="form.protocolCode"
                                    :disabled="form.status == 2 || form.productId != 0 || form.isOwner == 0"
                                    :placeholder="$t('product.product-edit.473153-82')"
                                    style="width: 100%"
                                    @change="changeProductCode"
                                >
                                    <el-option v-for="p in protocolList" :key="p.protocolCode" :label="p.protocolName" :value="p.protocolCode" />
                                </el-select>
                            </el-form-item> -->
                            <el-form-item v-if="form.deviceType !== 4" :label="$t('product.product-edit.473153-14')"
                                prop="transport">
                                <el-select v-model="form.transport" :placeholder="$t('product.product-edit.473153-15')"
                                    style="width: 100%" :disabled="form.productId != 0" @change="transportChange">
                                    <el-option v-for="dict in dict.type.iot_transport_type" :key="dict.value"
                                        :value="dict.value" />
                                </el-select>
                            </el-form-item>
                            <el-form-item :label="$t('product.product-edit.473153-16')" prop="networkMethod">
                                <el-select v-model="form.networkMethod"
                                    :placeholder="$t('product.product-edit.473153-17')" style="width: 100%"
                                    :disabled="form.productId != 0">
                                    <el-option v-for="dict in networkOptions" :key="dict.value" :label="dict.label"
                                        :value="parseInt(dict.value)"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item :label="$t('product.product-edit.473153-18')" prop="isSys">
                                <template slot="label">
                                    <span>{{ $t('product.product-edit.473153-18') }}</span>
                                    <el-tooltip style="cursor: pointer" effect="light" placement="bottom">
                                        <div slot="content">
                                            {{ $t('product.product-edit.473153-19') }}
                                            <br />
                                        </div>
                                        <i class="el-icon-question" />
                                    </el-tooltip>
                                </template>
                                <el-switch v-model="form.isSys" :active-value="1" :disabled="form.productId != 0"
                                    :inactive-value="0" />
                            </el-form-item>
                        </el-col>
                        <el-col v-show="dialogVisibleInterface === 'MTG'" :xs="24" :sm="24" :md="24" :lg="12" :xl="8">
                            <el-form-item v-if="form.deviceType != 4" :label="$t('product.product-edit.473153-20')"
                                prop="networkMethod">
                                <el-switch v-model="form.isAuthorize" @change="changeIsAuthorize(form.isAuthorize)"
                                    :active-value="1" :inactive-value="0" :disabled="form.productId != 0" />
                            </el-form-item>
                            <el-form-item v-if="form.deviceType != 4" :label="$t('product.product-edit.473153-21')"
                                prop="vertificateMethod">
                                <el-select v-model="form.vertificateMethod"
                                    :placeholder="$t('product.product-edit.473153-22')" style="width: 100%"
                                    :disabled="form.productId != 0">
                                    <el-option v-for="dict in dict.type.iot_vertificate_method" :key="dict.value"
                                        :label="dict.label" :value="parseInt(dict.value)"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item v-if="form.deviceType != 4" :label="$t('product.product-edit.473153-23')"
                                prop="locationWay">
                                <el-select v-model="form.locationWay"
                                    :placeholder="$t('product.product-edit.473153-24')" clearable size="small"
                                    :disabled="form.productId != 0" style="width: 100%">
                                    <el-option v-for="dict in dict.type.iot_location_way" :key="dict.value"
                                        :label="dict.label" :value="Number(dict.value)" />
                                </el-select>
                            </el-form-item>
                            <el-form-item :label="$t('product.product-edit.473153-25')" prop="productId">
                                <el-input v-model="form.productId" :placeholder="$t('product.product-edit.473153-26')"
                                    :disabled="form.productId != 0" readonly />
                            </el-form-item>
                            <el-form-item v-if="form.deviceType != 4" :label="$t('product.product-edit.473153-27')"
                                prop="mqttAccount">
                                <el-input v-model="form.mqttAccount" :placeholder="$t('product.product-edit.473153-28')"
                                    :disabled="form.deviceType == 3"
                                    :readonly="accountInputType == 'password' || form.isOwner == 0"
                                    :type="accountInputType">
                                    <el-button slot="append" icon="el-icon-view" style="font-size: 18px"
                                        @click="changeInputType('account')"></el-button>
                                </el-input>
                            </el-form-item>
                            <el-form-item v-if="form.deviceType != 4" :label="$t('product.product-edit.473153-29')"
                                prop="mqttPassword">
                                <el-input v-model="form.mqttPassword"
                                    :placeholder="$t('product.product-edit.473153-30')" :disabled="form.deviceType == 3"
                                    :readonly="passwordInputType == 'password' || form.isOwner == 0"
                                    :type="passwordInputType">
                                    <el-button slot="append" icon="el-icon-view" style="font-size: 18px"
                                        @click="changeInputType('password')"></el-button>
                                </el-input>
                            </el-form-item>
                            <el-form-item v-if="form.deviceType != 4" :label="$t('product.product-edit.473153-31')"
                                prop="mqttSecret">
                                <el-input v-model="form.mqttSecret" :placeholder="$t('product.product-edit.473153-26')"
                                    :disabled="form.productId != 0" readonly :type="keyInputType">
                                    <el-button slot="append" icon="el-icon-view" style="font-size: 18px"
                                        @click="changeInputType('key')"></el-button>
                                </el-input>
                            </el-form-item>
                            <el-form-item :label="$t('product.product-edit.473153-32')" prop="remark">
                                <el-input v-model="form.remark" :placeholder="$t('product.product-edit.473153-33')"
                                    rows="3" :readonly="form.status == 2 || form.isOwner == 0" />
                            </el-form-item>
                        </el-col>

                        <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="8" v-show="dialogVisibleInterface === 'HTTP'">
                            <el-form-item label="用户登录">
                                <el-switch v-model="userParmas.isLogin" @change="changeIsLogin" :active-value="true"
                                    :inactive-value="false" />
                            </el-form-item>

                            <el-form-item label="响应数据key">
                                <el-input v-model="form.responseKey" :disabled="form.status == 2 ? true : false" />
                            </el-form-item>
                            <el-form-item label="请求间隔">
                                <el-input v-model="form.cronExpression" placeholder="请输入cron执行表达式"
                                    :disabled="form.status == 2 ? true : false">
                                    <template slot="append">
                                        <el-button type="primary" @click="handleShowCron"
                                            :disabled="form.status == 2 ? true : false">
                                            生成表达式
                                            <i class="el-icon-time el-icon--right"></i>
                                        </el-button>
                                    </template>
                                </el-input>
                            </el-form-item>

                            <el-form-item label="请求方式">
                                <el-select v-model="form.methodType" placeholder="请选择"
                                    :disabled="form.status == 2 ? true : false">
                                    <el-option label="get" value="get"></el-option>
                                    <el-option label="post" value="post"></el-option>
                                    <el-option label="put" value="put"></el-option>
                                </el-select>
                            </el-form-item>

                            <el-form-item label="请求地址">
                                <el-input placeholder="例：http:127.0.0.1/" v-model="form.url"
                                    :disabled="form.status == 2 ? true : false" />
                            </el-form-item>

                            <el-form-item label="请求参数">
                                <div style="margin-top: 20px; overflow-y: auto">
                                    <el-tabs style="height: 350px" v-model="form.requestType">
                                        <el-tab-pane label="Header" :disabled="form.status == 2 ? true : false">
                                            <el-table :data="form.headersList" style="width: 100%">
                                                <el-table-column type="index" width="50" />
                                                <el-table-column label="key" prop="key">
                                                    <template slot-scope="scope">
                                                        <el-input placeholder="请输入" v-model="scope.row.key"
                                                            :disabled="form.status == 2 ? true : false"></el-input>
                                                    </template>
                                                </el-table-column>
                                                <el-table-column label="value" prop="value">
                                                    <template slot-scope="scope">
                                                        <el-input placeholder="请输入" v-model="scope.row.value"
                                                            :disabled="form.status == 2 ? true : false"></el-input>
                                                    </template>
                                                </el-table-column>
                                                <el-table-column label="操作" width="120">
                                                    <template slot-scope="scope">
                                                        <el-button size="mini" @click="handleEdit(form.headersList)"
                                                            :disabled="form.status == 2 ? true : false">+</el-button>
                                                        <el-button size="mini" type="danger"
                                                            @click="handleDelete(scope.$index, form.headersList)"
                                                            :disabled="form.status == 2 ? true : false">-</el-button>
                                                    </template>
                                                </el-table-column>
                                            </el-table>
                                        </el-tab-pane>
                                        <el-tab-pane label="Params" :disabled="form.status == 2 ? true : false">
                                            <el-table :data="form.paramsDataList" style="width: 100%">
                                                <el-table-column type="index" width="50" />
                                                <el-table-column label="key" prop="key">
                                                    <template slot-scope="scope">
                                                        <el-input placeholder="请输入" v-model="scope.row.key"
                                                            :disabled="form.status == 2 ? true : false"></el-input>
                                                    </template>
                                                </el-table-column>
                                                <el-table-column label="value" prop="value">
                                                    <template slot-scope="scope">
                                                        <el-input placeholder="请输入" v-model="scope.row.value"
                                                            :disabled="form.status == 2 ? true : false"></el-input>
                                                    </template>
                                                </el-table-column>
                                                <el-table-column label="操作" width="120">
                                                    <template slot-scope="scope">
                                                        <el-button size="mini" @click="handleEdit(form.paramsDataList)"
                                                            :disabled="form.status == 2 ? true : false">+</el-button>
                                                        <el-button size="mini" type="danger"
                                                            :disabled="form.status == 2 ? true : false"
                                                            @click="handleDelete(scope.$index, form.paramsDataList)">-</el-button>
                                                    </template>
                                                </el-table-column>
                                            </el-table>
                                        </el-tab-pane>
                                        <el-tab-pane label="Body" :disabled="form.status == 2 ? true : false">
                                            <div style="margin-bottom: 10px">
                                                <el-radio-group v-model="form.contentTypeNumber"
                                                    :disabled="form.status == 2 ? true : false">
                                                    <el-radio :label="1">none</el-radio>
                                                    <el-radio :label="2">form-data</el-radio>
                                                    <el-radio :label="3">x-www-form-urlencoded</el-radio>
                                                    <el-radio :label="4">json</el-radio>
                                                    <el-radio :label="5">xml</el-radio>
                                                </el-radio-group>
                                            </div>
                                            <el-empty description="该请求没有body体" v-if="form.contentTypeNumber == 1"
                                                :image-size="100"></el-empty>
                                            <el-table :data="form.bodyDataTable" style="width: 100%"
                                                v-else-if="form.contentTypeNumber == 2 || form.contentTypeNumber == 3">
                                                <el-table-column type="index" width="50" />
                                                <el-table-column label="key" prop="key">
                                                    <template slot-scope="scope">
                                                        <el-input placeholder="请输入" v-model="scope.row.key"
                                                            :disabled="form.status == 2 ? true : false"></el-input>
                                                    </template>
                                                </el-table-column>
                                                <el-table-column label="value" prop="value">
                                                    <template slot-scope="scope">
                                                        <el-input placeholder="请输入" v-model="scope.row.value"
                                                            :disabled="form.status == 2 ? true : false"></el-input>
                                                    </template>
                                                </el-table-column>
                                                <el-table-column label="操作" width="120">
                                                    <template slot-scope="scope">
                                                        <el-button size="mini" @click="handleEdit(form.bodyDataTable)"
                                                            :disabled="form.status == 2 ? true : false">+</el-button>
                                                        <el-button size="mini" type="danger"
                                                            @click="handleDelete(scope.$index, form.bodyDataTable)"
                                                            :disabled="form.status == 2 ? true : false">-</el-button>
                                                    </template>
                                                </el-table-column>
                                            </el-table>
                                            <el-input type="textarea" :rows="8" placeholder="请输入内容"
                                                v-model="form.bodyDataArea"
                                                v-else-if="form.contentTypeNumber == 4 || form.contentTypeNumber == 5"
                                                :disabled="form.status == 2 ? true : false"></el-input>
                                        </el-tab-pane>
                                    </el-tabs>
                                </div>
                            </el-form-item>
                        </el-col>

                        <el-col v-show="dialogVisibleInterface === 'SNMP'" :xs="24" :sm="24" :md="24" :lg="12" :xl="8">
                            <el-form-item label="请求间隔">
                                <el-input v-model="form.cronExpression" placeholder="请输入cron执行表达式"
                                    :disabled="form.status == 2 ? true : false">
                                    <template slot="append">
                                        <el-button type="primary" @click="handleShowCron"
                                            :disabled="form.status == 2 ? true : false">
                                            生成表达式
                                            <i class="el-icon-time el-icon--right"></i>
                                        </el-button>
                                    </template>
                                </el-input>
                            </el-form-item>
                            <el-form-item label="设备地址" prop="ipAddress">
                                <el-input v-model="form.ipAddress" :disabled="form.status == 2 ? true : false" />
                            </el-form-item>
                            <el-form-item label="团体名" prop="community">
                                <el-input v-model="form.community" :disabled="form.status == 2 ? true : false" />
                            </el-form-item>
                            <div>
                                <el-form-item label="OID信息" label-width="57%" align="center"
                                    style="text-align: center; background-color: #f5f7fa"
                                    prop="vertificateMethod"></el-form-item>
                                <div class="flex-center mb20" v-for="(item, index) in this.form.oidList" :key="index"
                                    style="border-bottom: 1px solid #dfe6ec; position: relative">
                                    <el-form-item label="名称" label-width="60px" prop="oidName">
                                        <el-input style="width: " v-model="item.oidName"
                                            :disabled="form.status == 2 ? true : false" />
                                    </el-form-item>
                                    <el-form-item label="oid" label-width="50px" prop="oid">
                                        <el-input v-model="item.oid" :disabled="form.status == 2 ? true : false" />
                                    </el-form-item>
                                    <el-form-item>
                                        <el-button v-if="form.oidList.length > 1" size="mini" type="danger"
                                            @click="deleteOid(item, index)" icon="el-icon-minus"></el-button>
                                        <!-- <div v-if="form.oidList.length > 1">
                                            <i class="el-icon el-icon-delete" style="color: #ff4949" @click="deleteOid(item, index)"></i>
                                        </div>-->
                                    </el-form-item>
                                </div>
                                <div class="flex-center">
                                    <el-button size="mini" type="primary" @click="addOid"
                                        icon="el-icon-plus"></el-button>
                                </div>
                            </div>
                        </el-col>

                        <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="8">
                            <el-form-item :label="$t('product.product-edit.473153-34')">
                                <div v-if="form.status == 2 && form.imgUrl == null && form.isOwner != 0">
                                    <el-image style="height: 145px; height: 145px; border-radius: 10px"
                                        :preview-src-list="[require('@/assets/images/gateway.png')]"
                                        :src="require('@/assets/images/gateway.png')" fit="cover"
                                        v-if="form.deviceType == 2"></el-image>
                                    <el-image style="height: 145px; height: 145px; border-radius: 10px"
                                        :preview-src-list="[require('@/assets/images/video.png')]"
                                        :src="require('@/assets/images/video.png')" fit="cover"
                                        v-else-if="form.deviceType == 3"></el-image>
                                    <el-image style="height: 145px; height: 145px; border-radius: 10px"
                                        :preview-src-list="[require('@/assets/images/product.png')]"
                                        :src="require('@/assets/images/product.png')" fit="cover" v-else></el-image>
                                </div>
                                <div v-else>
                                    <imageUpload ref="image-upload" :disabled="true" :value="form.imgUrl"
                                        :limit="form.status == 2 ? 0 : 1" :fileSize="1" @input="getImagePath($event)">
                                    </imageUpload>
                                </div>
                                <div class="el-upload__tip" style="color: #f56c6c"
                                    v-if="form.productId == null || form.productId == 0">
                                    {{ $t('product.product-edit.473153-35') }}
                                </div>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-col :span="20">
                        <el-form-item style="text-align: center; margin: 40px 0px">
                            <el-button type="primary" @click="submitForm" v-hasPermi="['iot:product:edit']"
                                v-show="form.productId != 0 && form.status != 2 && form.isOwner != 0">
                                {{ $t('product.product-edit.473153-36') }}
                            </el-button>
                            <el-button type="primary" @click="submitForm" v-hasPermi="['iot:product:add']"
                                v-show="form.productId == 0 && form.status != 2">{{ $t('product.product-edit.473153-37')
                                }}</el-button>
                        </el-form-item>
                    </el-col>
                </el-form>
            </el-tab-pane>
            <el-tab-pane label="" name="things" :disabled="form.productId == 0">
                <span slot="label">
                    <span style="color: red" v-hasPermi="['iot:model:list']">*</span>
                    {{ $t('product.product-edit.473153-38') }}
                </span>
                <product-things-model ref="productThingsModel" :product="form" @updateModel="updateModel" />
            </el-tab-pane>
            <!--            <el-tab-pane label="" name="ProductModbus" :disabled="form.productId == 0" v-if="form.deviceType == 1 || form.deviceType == 4">
                <span slot="label">
                    <span style="color: red" v-hasPermi="['iot:model:list']">*</span>
                    {{ $t('product.product-edit.473153-80') }}
                </span>
                <product-modbus ref="ProductModbus" :product="form" />
            </el-tab-pane>-->
            <el-tab-pane label="" name="productFirmware" :disabled="form.productId == 0" v-if="form.deviceType !== 3">
                <span slot="label" v-hasPermi="['iot:firmware:list']">{{ $t('product.product-edit.473153-39') }}</span>
                <product-firmware ref="productFirmware" :product="form" />
            </el-tab-pane>
            <el-tab-pane label="" name="productAuthorize" :disabled="form.productId == 0" v-if="form.deviceType !== 3">
                <span slot="label" v-hasPermi="['iot:authorize:query']">{{ $t('product.product-edit.473153-40')
                }}</span>
                <product-authorize ref="productAuthorize" :product="form" />
            </el-tab-pane>
            <!-- <el-tab-pane label="" name="productApp" :disabled="form.productId==0">
            <span slot="label">控制界面</span>
            <product-app ref="productApp" :product="form" />
        </el-tab-pane> -->
            <el-tab-pane label="" name="sipConfig" :disabled="form.productId == 0" v-if="form.deviceType === 3">
                <span slot="label">{{ $t('product.product-edit.473153-41') }}</span>
                <config-sip ref="configSip" :product="form" />
            </el-tab-pane>
            <el-tab-pane name="scada" :disabled="form.deviceId == 0" v-if="form.deviceType !== 3 && isShowScada == true"
                lazy>
                <span slot="label">{{ $t('device.device-edit.148398-73') }}</span>
                <product-scada ref="productScada" :product="form" />
            </el-tab-pane>
            <!-- 用于设置间距 -->
            <el-tab-pane>
                <span slot="label">
                    <div style="margin-top: 200px"></div>
                </span>
            </el-tab-pane>
            <el-tab-pane v-if="form.status == 1" name="product04" disabled>
                <span slot="label">
                    <el-button type="success" v-if="form.isOwner != 0" size="mini" @click="changeProductStatus(2)"
                        v-hasPermi="['iot:product:add']">{{ $t('product.product-edit.473153-42') }}</el-button>
                </span>
            </el-tab-pane>
            <el-tab-pane v-if="form.status == 2" name="product05" disabled>
                <span slot="label">
                    <el-button type="danger" v-if="form.isOwner != 0" size="mini" @click="changeProductStatus(1)"
                        v-hasPermi="['iot:product:edit']">{{ $t('product.product-edit.473153-43') }}</el-button>
                </span>
            </el-tab-pane>
            <el-tab-pane name="product06" disabled>
                <span slot="label">
                    <el-button type="info" size="mini" @click="goBack()">{{ $t('product.product-edit.473153-44')
                    }}</el-button>
                </span>
            </el-tab-pane>
        </el-tabs>
        <!--添加从机对话框-->
        <el-dialog :title="title" :visible.sync="open" append-to-body width="1000px">
            <el-row :gutter="30">
                <el-col :span="11">
                    <el-form ref="tempParams" :inline="true" :model="tempParams">
                        <el-form-item size="mini">
                            <el-input v-model="tempParams.templateName" placeholder="模板名称"></el-input>
                        </el-form-item>
                        <el-form-item size="mini">
                            <el-button icon="el-icon-search" size="mini" type="primary" @click="queryTemp">{{
                                $t('search')
                            }}</el-button>
                            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('reset')
                                }}</el-button>
                        </el-form-item>
                    </el-form>
                    <el-table :border="false" ref="multipleTable" v-loading="loading" :data="tempList"
                        highlight-current-row style="width: 100%">
                        <el-table-column align="left" label="选择采集点模板">
                            <template slot-scope="scope">
                                <el-radio v-model="currentRow" :label="scope.row"
                                    @change.native="getCurrentRow(scope.row)">{{ scope.row.templateName }}</el-radio>
                            </template>
                        </el-table-column>
                    </el-table>
                    <pagination v-show="tempTotal > 0" :limit.sync="tempParams.pageSize" :page.sync="tempParams.pageNum"
                        :total="tempTotal" layout="total, prev, pager, next" small @pagination="getTempList" />
                </el-col>
                <el-col :span="13">
                    <el-form :inline="true" :model="pointsParams">
                        <el-form-item size="mini">
                            <span slot="label" style="font-size: 16px; font-weight: 400">物模型列表</span>
                        </el-form-item>
                        <el-form-item size="mini">
                            <span slot="label" style="font-weight: 400; font-size: 12px">从机数量:</span>
                            {{ selectRowData.slaveTotal }}
                        </el-form-item>
                        <el-form-item size="mini">
                            <span slot="label" style="font-weight: 400; font-size: 12px">变量数量:</span>
                            {{ selectRowData.pointTotal }}
                        </el-form-item>
                        <el-form-item size="mini">
                            <span slot="label" style="font-weight: 400; font-size: 12px">采集方式:</span>
                            <dict-tag :options="dict.type.data_collect_type" :value="selectRowData.pollingMethod"
                                size="small" style="display: inline-block" />
                        </el-form-item>
                    </el-form>
                    <el-table :border="false" v-loading="loading" :data="pointList" size="mini">
                        <el-table-column label="物模型名称" prop="templateName"></el-table-column>
                        <el-table-column label="寄存器" prop="regAddr"></el-table-column>
                        <el-table-column label="数值类型" prop="datatype"></el-table-column>
                    </el-table>
                    <pagination v-show="total > 0" :limit.sync="pointsParams.pageSize" :page.sync="pointsParams.pageNum"
                        :total="total" layout="total, prev, pager, next" small @pagination="getList" />
                </el-col>
            </el-row>

            <div slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="submitSelect">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog title="登录信息" :visible.sync="userEdit" append-to-body @close="userClose">
            <el-form :inline="true" ref="userForm" :model="userParmas" label-width="100px">
                <div class="flex-center">
                    <div>
                        <div>
                            <el-form-item label="账号" prop="user">
                                <el-input v-model="userParmas.user" placeholder="请输入账号" clearable size="small" />
                            </el-form-item>
                        </div>
                        <div>
                            <el-form-item label="密码" prop="password">
                                <el-input v-model="userParmas.password" placeholder="请输入密码" clearable size="small" />
                            </el-form-item>
                        </div>
                        <div>
                            <el-form-item label="登录地址" prop="password">
                                <el-input v-model="userParmas.url" placeholder="请输入登录地址，例：http:127.0.0.1/" clearable
                                    size="small" />
                            </el-form-item>
                        </div>
                    </div>
                </div>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancelUser">取 消</el-button>
                <el-button type="primary" @click="confirmUser">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog title="Cron表达式生成器" :visible.sync="openCron" append-to-body destroy-on-close class="scrollbar">
            <crontab @hide="openCron = false" @fill="crontabFill" :expression="expression"></crontab>
        </el-dialog>
    </el-card>
</template>

<script>
import productThingsModel from './product-things-model';
import productFirmware from './product-firmware';
import productApp from './product-app';
import productAuthorize from './product-authorize';
import imageUpload from '../../../components/ImageUpload/index';
import configSip from '../sip/sipconfig.vue';
import productScada from './product-scada';
import ProductModbus from '@/views/iot/product/product-modbus';
import defaultSettings from '@/settings';
import { listProtocol } from '@/api/iot/protocol';

import { listShortCategory } from '@/api/iot/category';
import { addProduct, changeProductStatus, deviceCount, getProduct, updateProduct } from '@/api/iot/product';
import { getTempByPId, listTemp } from '@/api/iot/temp';
import { getAllPoints } from '@/api/iot/template';

import Crontab from '@/components/Crontab';
import { getToken } from '@/utils/auth';

export default {
    name: 'ProductEdit',
    dicts: ['iot_device_type', 'iot_network_method', 'iot_vertificate_method', 'iot_transport_type', 'data_collect_type', 'iot_location_way', 'sub_gateway_type'],
    components: {
        ProductModbus,
        productThingsModel,
        productApp,
        productAuthorize,
        productFirmware,
        imageUpload,
        configSip,
        productScada,
        Crontab,
    },
    data() {
        return {
            dialogVisibleInterface: 'MTG',
            expression: '',
            openCron: false,

            // 输入框类型
            keyInputType: 'password',
            accountInputType: 'password',
            passwordInputType: 'password',
            // 选中选项卡
            activeName: 'basic',
            // 分类短列表
            categoryShortList: [],
            //协议列表
            protocolList: [],
            //组态相关按钮是否显示，true显示，false不显示
            isShowScada: defaultSettings.isShowScada,
            // 表单参数
            userParmas: {
                isLogin: false,
            },
            userStatus: false,
            userEdit: false,
            userRule: {
                user: [
                    {
                        required: true,
                        message: '用户id不能为空',
                        trigger: 'blur',
                    },
                ],
                password: [
                    {
                        required: true,
                        message: '密码不能为空',
                        trigger: 'blur',
                    },
                ],
                url: [
                    {
                        required: true,
                        message: '登录地址不能为空',
                        trigger: 'blur',
                    },
                ],
            },
            form: {
                networkMethod: 1,
                deviceType: 1,
                vertificateMethod: 3,
                transport: 'MQTT',
                imgUrl: '',
                locationWay: 1,
                isSys: 0,

                // --------http协议--------
                responseKey: '',
                methodType: 'get',
                url: '',
                data: {},
                intervalType: '',
                interval: '',
                contentTypeNumber: 1,
                requestType: '0',
                paramsData: '',
                cronExpression: '',
                paramsDataList: [
                    {
                        key: '',
                        value: '',
                    },
                ],
                contentType: 1,
                bodyDataTable: [
                    {
                        key: '',
                        value: '',
                    },
                ],
                bodyDataArea: '',
                headersList: [
                    {
                        key: 'Authorization',
                        value: 'Bearer ' + getToken(),
                    },
                ],
                // --------http协议---------

                //SNMP
                oidListStr: '',
                ipAddress: null,
                community: null,
                oidList: [
                    {
                        oidName: null,
                        oid: null,
                    },
                ],
            },
            tempOpen: false,
            // 表单校验
            rules: {
                productName: [
                    {
                        required: true,
                        message: this.$t('product.product-edit.473153-58'),
                        trigger: 'blur',
                    },
                ],
                categoryId: [
                    {
                        required: true,
                        message: this.$t('product.product-edit.473153-59'),
                        trigger: 'blur',
                    },
                ],
                deviceType: [
                    {
                        required: true,
                        message: this.$t('product.product-edit.473153-13'),
                        trigger: 'blur',
                    },
                ],
                protocolCode: [
                    {
                        required: true,
                        message: this.$t('product.product-edit.473153-60'),
                        trigger: 'blur',
                    },
                ],
                transport: [
                    {
                        required: true,
                        message: this.$t('product.product-edit.473153-61'),
                        trigger: 'blur',
                    },
                ],
                isSys: [
                    {
                        required: true,
                        message: this.$t('product.product-edit.473153-61'),
                        trigger: 'blur',
                    },
                ],
            },
            // 查询参数
            queryParams: {
                tenantName: null,
            },
            pointList: [],
            open: false,
            // 弹出层标题
            title: '',
            loading: true,
            tempList: [],
            // 总条数
            total: 0,
            tempTotal: 0,
            // 查询参数
            pointsParams: {
                pageNum: 1,
                pageSize: 8,
                templateId: 0,
            },
            tempParams: {
                pageNum: 1,
                pageSize: 10,
            },
            currentRow: {},
            selectRowData: {},
            isModbus: false,
        };
    },

    computed: {
        networkOptions() {
            return this.form.deviceType == 4 ? this.dict.type.sub_gateway_type : this.dict.type.iot_network_method;
        },
    },

    created() {
        // 获取产品信息
        const productId = this.$route.query && this.$route.query.productId;
        this.form.productId = productId;
        if (this.form.productId != 0 && this.form.productId != null) {
            this.getProduct();
        }
        // 切换选项卡
        const tabPanelName = this.$route.query && this.$route.query.tabPanelName;
        if (tabPanelName != null && tabPanelName != '') {
            this.activeName = tabPanelName;
        }
        // 获取分类信息
        this.getShortCategory();
        // 设置账号密码输入框类型,新增时为text，查看时为password
        if (!this.form.productId || this.form.productId == 0) {
            this.accountInputType = 'text';
            this.passwordInputType = 'text';
        }
        this.getProtocol();
    },
    activated() {
        const time = this.$route.query.t;
        if (time != null && time != this.uniqueId) {
            this.uniqueId = time;
        }
        // 获取产品信息
        let productId = this.$route.query.productId;
        if (productId != null && productId != 0) {
            this.form.productId = Number(productId);
            this.getProduct();
            this.getShortCategory();
        }
        // 切换选项卡
        const tabPanelName = this.$route.query && this.$route.query.tabPanelName;
        if (tabPanelName != null && tabPanelName != '') {
            this.activeName = tabPanelName;
        }
    },
    methods: {
        userClose() {
            if (this.userParmas.isLogin) {
                for (let key in this.userParmas) {
                    if (!this.userParmas[key]) {
                        this.userParmas.isLogin = false;
                    }
                }
            }
        },
        changeIsLogin(status) {
            if (status) {
                this.userParmas = {
                    isLogin: true,
                    user: '',
                    password: '',
                    url: '',
                };
                this.userEdit = true;
            } else {
                this.userParmas = { isLogin: false };
            }
        },
        cancelUser() {
            this.userParmas = { isLogin: false };
            this.userEdit = false;
        },
        confirmUser() {
            this.$refs['userForm'].validate((valid) => {
                if (valid) {
                    this.userEdit = false;
                }
            });
        },
        deleteOid(item, index) {
            this.form.oidList.splice(index, 1);
        },
        addOid(index) {
            this.form.oidList.push({
                oidName: '',
                oid: '',
            });
        },
        /** cron表达式按钮操作 */
        handleShowCron() {
            this.expression = this.form.cronExpression;
            this.openCron = true;
        },
        /** 确定后回传值 */
        crontabFill(value) {
            this.form.cronExpression = value;
        },

        handleEdit(row) {
            let data = {
                key: '',
                value: '',
            };
            row.push(data);
        },
        handleDelete(xh, row) {
            if (row.length == 1) {
                return;
            }
            row.forEach((element, index) => {
                if (index == xh) {
                    row.splice(index, 1);
                }
            });
        },
        submitInterface() {
            console.log(this.form, '111');
        },

        // 获取简短分类列表
        getShortCategory() {
            listShortCategory().then((response) => {
                this.categoryShortList = response.data;
            });
        },
        /** 返回按钮 */
        goBack() {
            const obj = {
                path: '/iotdev/iot/product',
                query: {
                    t: Date.now(),
                    pageNum: this.$route.query.pageNum,
                },
            };
            this.$tab.closeOpenPage(obj);
            this.reset();
        },
        /** 获取产品信息 */
        getProduct() {
            getProduct(this.form.productId).then((response) => {
                this.form = response.data;
                console.log(this.form, 'getProduct');
                if (this.form.transport === 'HTTP') {
                    this.userParmas = this.form.userParmas;
                    this.form.bodyDataTable = [];
                    this.dialogVisibleInterface = 'HTTP';
                    this.form.headersList = JSON.parse(this.form.headers);
                    this.form.paramsDataList = JSON.parse(this.form.paramsData);

                    if (this.form.contentTypeNumber === 2 || this.form.contentTypeNumber === 3) {
                        let data1 = JSON.parse(this.form.data);
                        console.log(Object.prototype.toString.call(data1), 'typeof');
                        var dataJSONObj = data1;
                        if (Object.prototype.toString.call(data1) !== '[object Object]') {
                            dataJSONObj = JSON.parse(data1);
                        }
                        let data = Object.keys(dataJSONObj);
                        for (let i = 0; i < data.length; i++) {
                            let obj = {
                                key: '',
                                value: '',
                            };
                            obj.key = data[i];
                            obj.value = dataJSONObj[obj.key];
                            this.form.bodyDataTable.push(obj);
                            this.form.data = null;
                        }
                    } else if (this.form.contentTypeNumber === 4 || this.form.contentTypeNumber === 5) {
                        this.form.bodyDataArea = JSON.parse(this.form.data);
                        this.form.bodyDataTable = [
                            {
                                key: '',
                                value: '',
                            },
                        ];
                    } else {
                        this.form.bodyDataTable = [
                            {
                                key: '',
                                value: '',
                            },
                        ];
                    }
                }
                if (this.form.transport === 'SNMP') {
                    this.dialogVisibleInterface = 'SNMP';
                    this.form.oidList = JSON.parse(this.form.oidListStr);
                }
                this.changeProductCode(this.form.protocolCode);
            });
        },
        // 表单重置
        reset() {
            this.form = {
                // --------http协议--------
                responseKey: '',
                methodType: '',
                url: '',
                data: {},
                intervalType: '',
                interval: '',
                contentTypeNumber: 1,
                requestType: '0',
                paramsData: '',
                cronExpression: '',
                paramsDataList: [
                    {
                        key: '',
                        value: '',
                    },
                ],
                contentType: 1,
                bodyDataTable: [
                    {
                        key: '',
                        value: '',
                    },
                ],
                bodyDataArea: '',
                headersList: [
                    {
                        key: 'Authorization',
                        value: 'Bearer ' + getToken(),
                    },
                ],
                // --------http协议---------

                productId: 0,
                productName: null,
                categoryId: null,
                categoryName: null,
                status: 0,
                tslJson: null,
                isAuthorize: 0,
                deviceType: 1,
                networkMethod: 1,
                vertificateMethod: 3,
                mqttAccount: null,
                mqttPassword: null,
                mqttSecret: null,
                remark: null,
                imgUrl: '',
                locationWay: 1,
                isSys: 0,

                //SNMP
                ipAddress: null,
                community: null,
                oidList: [
                    {
                        oidName: null,
                        oid: null,
                    },
                ],
                oidListStr: '',
            };
            this.resetForm('form');
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    let data = {};
                    let bodyDataTable = this.form.bodyDataTable;
                    // console.log(bodyDataTable);
                    if (bodyDataTable) {
                        //body 为multipart/form-data 、application/x-www-form-urlencoded;charset=utf-8
                        for (let itemindex = 0; itemindex < bodyDataTable.length; itemindex++) {
                            //$set()方法第一个参数是对象，第二个参数是key值，第三个参数是value值
                            if (bodyDataTable[itemindex].key) {
                                this.$set(data, bodyDataTable[itemindex].key, bodyDataTable[itemindex].value);
                            }
                        }
                    }

                    if (this.form.contentTypeNumber === 2) {
                        this.form.contentType = 'multipart/form-data';
                    } else if (this.form.contentTypeNumber === 3) {
                        this.form.contentType = 'application/x-www-form-urlencoded;charset=utf-8';
                    } else if (this.form.contentTypeNumber === 4) {
                        this.form.contentType = 'application/json;charset=utf-8';
                        data = this.form.bodyDataArea;
                    } else if (this.form.contentTypeNumber === 5) {
                        this.form.contentType = 'text/xml';
                        data = this.form.bodyDataArea;
                    } else {
                        this.form.contentType = 'application/json;charset=utf-8';
                    }

                    this.form.bodyDataTable = bodyDataTable;
                    this.form.data = JSON.stringify(data);

                    if (this.form.transport === 'SNMP') {
                        this.form.oidListStr = JSON.stringify(this.form.oidList);

                    } else if (this.form.transport === 'HTTP') {
                        this.form.userParmas = this.userParmas;
                    }
                    if (this.form.productId != null && this.form.productId != 0) {
                        this.form.headers = JSON.stringify(this.form.headersList);

                        updateProduct(this.form).then((response) => {
                            this.changeProductCode(this.form.protocolCode);
                            this.$modal.alertSuccess(this.$t('product.product-edit.473153-62'));
                        });
                    } else {
                        if (this.tempOpen && !this.form.templateId) {
                            this.$modal.alert('请选择采集点模板');
                            return;
                        }

                        this.form.headers = JSON.stringify(this.form.headersList);

                        // console.log(this.form, 'this.form');
                        addProduct(this.form).then((response) => {
                            if (!this.form.isModbus) {
                                this.$modal.alertSuccess(this.$t('product.product-edit.473153-64'));
                            } else {
                                this.$modal.alertSuccess('物模型已经从采集点模板同步至产品');
                            }
                            this.form = response.data;
                            this.changeProductCode(this.form.protocolCode);
                        });
                    }
                }
            });
        },
        /**同步获取产品下的设备数量**/
        getDeviceCountByProductId(productId) {
            return new Promise((resolve, reject) => {
                deviceCount(productId)
                    .then((res) => {
                        resolve(res);
                    })
                    .catch((error) => {
                        reject(error);
                    });
            });
        },
        /** 更新产品状态 */
        async changeProductStatus(status) {
            let message = this.$t('product.product-edit.473153-66');
            if (status == 2) {
                message = this.$t('product.product-edit.473153-67');
            } else if (status == 1) {
                let result = await this.getDeviceCountByProductId(this.form.productId);
                if (result.data > 0) {
                    message = this.$t('product.product-edit.473153-68', [result.data]);
                }
            }
            this.$confirm(message, this.$t('product.product-edit.473153-69'), {
                confirmButtonText: this.$t('product.product-edit.473153-70'),
                cancelButtonText: this.$t('product.product-edit.473153-71'),
                type: 'warning',
            })
                .then(() => {
                    let data = {};
                    data.productId = this.form.productId;
                    data.status = status;
                    data.deviceType = this.form.deviceType;
                    changeProductStatus(data)
                        .then((response) => {
                            this.$modal.alertSuccess(response.msg);
                            this.activeName = 'basic';
                            this.getProduct();
                        })
                        .catch(() => {
                            if (status == 2) {
                                this.activeName = 'basic';
                            } else {
                                this.goBack();
                            }
                        });
                })
                .catch(() => {
                    this.activeName = 'basic';
                });
        },
        /** 选择分类 */
        selectCategory(val) {
            for (var i = 0; i < this.categoryShortList.length; i++) {
                if (this.categoryShortList[i].id == val) {
                    this.form.categoryName = this.categoryShortList[i].name;
                    return;
                }
            }
        },
        /**获取上传图片的路径 */
        getImagePath(data) {
            this.form.imgUrl = data;
        },
        /**改变输入框类型**/
        changeInputType(name) {
            if (name == 'key') {
                this.keyInputType = this.keyInputType == 'password' ? 'text' : 'password';
            } else if (name == 'account') {
                this.accountInputType = this.accountInputType == 'password' ? 'text' : 'password';
            } else if (name == 'password') {
                this.passwordInputType = this.passwordInputType == 'password' ? 'text' : 'password';
            }
        },
        // 授权码状态修改
        changeIsAuthorize() {
            let text = this.form.isAuthorize == '1' ? this.$t('product.product-edit.473153-72') : this.$t('product.product-edit.473153-74');
            this.$modal
                .confirm(this.$t('product.product-edit.473153-75', [text]))
                .then(() => {
                    if (this.form.productId != null && this.form.productId != 0) {
                        updateProduct(this.form).then((response) => {
                            this.$modal.alertSuccess(this.$t('product.product-edit.473153-77') + text);
                        });
                    }
                })
                .catch(() => {
                    this.form.isAuthorize = 0;
                });
        },
        //获取设备协议
        getProtocol() {
            const data = {
                protocolStatus: 1,
                pageSize: 99,
            };
            listProtocol(data).then((res) => {
                this.protocolList = res.rows;
            });
        },
        /*选择模板*/
        selectTemplate() {
            // this.reset();
            this.open = true;
            this.title = '选择模板';
            this.getTempList();
            // this.getList()
        },
        getTempDetail() {
            const params = {
                productId: this.form.productId,
            };
            getTempByPId(params).then((response) => {
                this.selectRowData = response.data;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            // this.reset();
        },
        /** 查询设备采集变量模板列表 */
        getTempList() {
            this.loading = true;
            listTemp(this.tempParams).then((response) => {
                this.tempList = response.rows;
                this.tempTotal = response.total;
                this.currentRow = this.tempList[0];
                // this.pointsParams.templateId = this.currentRow.templateId;
                this.getCurrentRow(this.tempList[0]);
                this.loading = false;
                this.getList();
            });
        },
        getList() {
            getAllPoints(this.pointsParams).then((response) => {
                this.pointList = response.rows;
                this.total = response.total;
            });
        },

        /*确认选择*/
        submitSelect() {
            this.open = false;
            this.form.templateId = this.selectRowData.templateId;
        },
        getCurrentRow(val) {
            if (val != null) {
                this.selectRowData = val;
            }
            this.pointsParams.templateId = val.templateId;
            this.getList();
        },
        deleteData() {
            this.selectRowData = {};
            this.form.templateId = null;
        },
        transportChange(val) {
            if (val === 'HTTP') {
                this.dialogVisibleInterface = 'HTTP';
            } else if (val === 'SNMP') {
                this.dialogVisibleInterface = 'SNMP';
            } else {
                this.dialogVisibleInterface = 'MTG';
            }
        },
        changeProductCode(val) {
            if (val && val.startsWith('MODBUS')) {
                this.tempOpen = true;
                this.form.deviceType = 2;
                this.form.isModbus = true;
                if (this.form.productId != 0 && this.form.productId != null) {
                    this.getTempDetail();
                }
            } else {
                this.form.isModbus = false;
                this.tempOpen = false;
            }
        },
        /**选项卡切换事件**/
        tabChange(tabItem) {
            // 切换到告警配置，获取物模型
            if (tabItem.paneName == 'alert') {
                this.$refs.productAlert.getCacheThingsModel(this.form.productId);
            } else if (tabItem.paneName == 'productFirmware') {
                this.$refs.productFirmware.getList();
            } else if (tabItem.paneName == 'productAuthorize') {
                this.$refs.productAuthorize.queryParams.productId = this.form.productId;
                this.$refs.productAuthorize.getList();
            }
        },

        /*按照模板名查询*/
        queryTemp() {
            this.getTempList();
        },

        /** 搜索按钮操作 */
        handleQuery() {
            this.tempParams.pageNum = 1;
            this.getTempList();
        },

        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm('tempParams');
            this.handleQuery();
        },

        /**刷新产品模型 */
        updateModel() {
            this.$refs.ProductModbus.getThingsModelList();
        },
    },
};
</script>

<style lang="scss" scoped>
.el-aside {
    margin: 0;
    padding: 0;
    background-color: #fff;
    color: #333;
}

.el-main {
    margin: 0;
    padding: 0 10px;
    background-color: #fff;
    color: #333;
}

.base-table.table-btn {
    position: absolute;
    right: -40px;
    top: 33%;
    transform: translate(0, -50%);
}
</style>
