<template>
  <div>
    <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-change="tabChange"
      >
        <el-tab-pane name="basic">
          <template #label>
            <span style="color: red">*</span>
            {{ t('product.product-edit473153-0') }}
          </template>
          <el-form ref="formRef" :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="所在部门" prop="groupName">
                  <el-tree-select
                    v-model="form.groupName"
                    :data="deptList"
                    :props="defaultProps"
                    check-strictly
                    node-key="id"
                    filterable
                    placeholder="请选择所在部门"
                    @change="handleDeptChange"
                    :disabled="form.status == 2 || form.isOwner == 0"
                   
                  />
                </el-form-item> -->
                <el-form-item :label="t('product.product-edit473153-1')" prop="productName">
                  <el-input
                    v-model="form.productName"
                    :placeholder="t('product.product-edit473153-2')"
                    :readonly="form.status == 2 || form.isOwner == 0"
                  />
                </el-form-item>
                <el-form-item :label="t('product.product-edit473153-3')" prop="categoryId">
                  <el-select
                    v-model="form.categoryId"
                    :placeholder="t('product.product-edit473153-4')"
                    @change="selectCategory"
                    style="width: 100%"
                    :disabled="form.status == 2 || form.isOwner == 0"
                  >
                    <el-option
                      v-for="category in categoryShortList"
                      :key="category.categoryId"
                      :label="category.categoryName"
                      :value="category.categoryId"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item v-if="form.deviceType !== 3" label="通讯协议" prop="protocolCode">
                  <template #label>
                    <span>通讯协议</span>
                    <el-tooltip effect="light" placement="bottom" style="cursor: pointer">
                      <template #content>
                        产品建立后，不允许修改通讯协议,修改会导致该产品下设备脏数据问题
                        <br />
                      </template>
                      <el-icon><QuestionFilled /></el-icon>
                    </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">
                  <el-alert
                    description="当前通讯协议为modbus协议,请选择采集点模板,默认添加设备为网关设备"
                    type="success"
                  />
                </el-form-item>
                <el-form-item v-if="tempOpen && selectRowData" prop="templateId">
                  <template #label>
                    <span style="color: #f56c6c">*</span>
                    采集点模板
                  </template>
                  <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="small"
                      @click="deleteData"
                      >删除</el-button
                    >
                  </div>
                  <el-button
                    plain
                    size="small"
                    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-edit473153-78')" prop="deviceType">
                  <el-select
                    v-model="form.deviceType"
                    :disabled="form.productId != 0"
                    placeholder="请选择设备类型"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="dict in iot_device_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="parseInt(dict.value)"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item
                  v-if="form.deviceType !== 4"
                  :label="t('product.product-edit473153-14')"
                  prop="transport"
                >
                  <el-select
                    v-model="form.transport"
                    :placeholder="t('product.product-edit473153-15')"
                    style="width: 100%"
                    :disabled="form.productId != 0"
                    @change="transportChange"
                  >
                    <el-option
                      v-for="dict in iot_transport_type"
                      :key="dict.value"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item :label="t('product.product-edit473153-16')" prop="networkMethod">
                  <el-select
                    v-model="form.networkMethod"
                    :placeholder="t('product.product-edit473153-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-select>
                </el-form-item>
                <el-form-item :label="t('product.product-edit473153-18')" prop="isSys">
                  <template #label>
                    <span>{{ t('product.product-edit473153-18') }}</span>
                    <el-tooltip style="cursor: pointer" effect="light" placement="bottom">
                      <template #content>
                        {{ t('product.product-edit473153-19') }}
                        <br />
                      </template>
                      <el-icon><QuestionFilled /></el-icon>
                    </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-edit473153-20')"
                  prop="networkMethod"
                >
                  <el-switch
                    v-model="form.isAuthorize"
                    @change="changeIsAuthorize"
                    :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-edit473153-21')"
                  prop="vertificateMethod"
                >
                  <el-select
                    v-model="form.vertificateMethod"
                    :placeholder="t('product.product-edit473153-22')"
                    style="width: 100%"
                    :disabled="form.productId != 0"
                  >
                    <el-option
                      v-for="dict in iot_vertificate_method"
                      :key="dict.value"
                      :label="dict.label"
                      :value="parseInt(dict.value)"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item
                  v-if="form.deviceType != 4"
                  :label="t('product.product-edit473153-23')"
                  prop="locationWay"
                >
                  <el-select
                    v-model="form.locationWay"
                    :placeholder="t('product.product-edit473153-24')"
                    clearable
                    size="small"
                    :disabled="form.productId != 0"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="dict in 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-edit473153-25')" prop="productId">
                  <el-input
                    v-model="form.productId"
                    :placeholder="t('product.product-edit473153-26')"
                    :disabled="form.productId != 0"
                    readonly
                  />
                </el-form-item>
                <el-form-item
                  v-if="form.deviceType != 4"
                  :label="t('product.product-edit473153-27')"
                  prop="mqttAccount"
                >
                  <el-input
                    v-model="form.mqttAccount"
                    :placeholder="t('product.product-edit473153-28')"
                    :disabled="form.deviceType == 3"
                    :readonly="accountInputType == 'password' || form.isOwner == 0"
                    :type="accountInputType"
                  >
                    <template #append>
                      <el-button
                        :icon="View"
                        style="font-size: 18px"
                        @click="changeInputType('account')"
                      />
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item
                  v-if="form.deviceType != 4"
                  :label="t('product.product-edit473153-29')"
                  prop="mqttPassword"
                >
                  <el-input
                    v-model="form.mqttPassword"
                    :placeholder="t('product.product-edit473153-30')"
                    :disabled="form.deviceType == 3"
                    :readonly="passwordInputType == 'password' || form.isOwner == 0"
                    :type="passwordInputType"
                  >
                    <template #append>
                      <el-button
                        :icon="View"
                        style="font-size: 18px"
                        @click="changeInputType('password')"
                      />
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item
                  v-if="form.deviceType != 4"
                  :label="t('product.product-edit473153-31')"
                  prop="mqttSecret"
                >
                  <el-input
                    v-model="form.mqttSecret"
                    :placeholder="t('product.product-edit473153-26')"
                    :disabled="form.productId != 0"
                    readonly
                    :type="keyInputType"
                  >
                    <template #append>
                      <el-button
                        :icon="View"
                        style="font-size: 18px"
                        @click="changeInputType('key')"
                      />
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item :label="t('product.product-edit473153-32')" prop="remark">
                  <el-input
                    v-model="form.remark"
                    :placeholder="t('product.product-edit473153-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 #append>
                      <el-button
                        type="primary"
                        @click="handleShowCron"
                        :disabled="form.status == 2 ? true : false"
                      >
                        生成表达式
                        <el-icon class="el-icon--right"><Timer /></el-icon>
                      </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 label="post" value="post" />
                    <el-option label="put" value="put" />
                  </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 #default="scope">
                              <el-input
                                placeholder="请输入"
                                v-model="scope.row.key"
                                :disabled="form.status == 2 ? true : false"
                              />
                            </template>
                          </el-table-column>
                          <el-table-column label="value" prop="value">
                            <template #default="scope">
                              <el-input
                                placeholder="请输入"
                                v-model="scope.row.value"
                                :disabled="form.status == 2 ? true : false"
                              />
                            </template>
                          </el-table-column>
                          <el-table-column label="操作" width="120">
                            <template #default="scope">
                              <el-button
                                size="small"
                                @click="handleEdit(form.headersList)"
                                :disabled="form.status == 2 ? true : false"
                                >+</el-button
                              >
                              <el-button
                                size="small"
                                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 #default="scope">
                              <el-input
                                placeholder="请输入"
                                v-model="scope.row.key"
                                :disabled="form.status == 2 ? true : false"
                              />
                            </template>
                          </el-table-column>
                          <el-table-column label="value" prop="value">
                            <template #default="scope">
                              <el-input
                                placeholder="请输入"
                                v-model="scope.row.value"
                                :disabled="form.status == 2 ? true : false"
                              />
                            </template>
                          </el-table-column>
                          <el-table-column label="操作" width="120">
                            <template #default="scope">
                              <el-button
                                size="small"
                                @click="handleEdit(form.paramsDataList)"
                                :disabled="form.status == 2 ? true : false"
                                >+</el-button
                              >
                              <el-button
                                size="small"
                                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-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 #default="scope">
                              <el-input
                                placeholder="请输入"
                                v-model="scope.row.key"
                                :disabled="form.status == 2 ? true : false"
                              />
                            </template>
                          </el-table-column>
                          <el-table-column label="value" prop="value">
                            <template #default="scope">
                              <el-input
                                placeholder="请输入"
                                v-model="scope.row.value"
                                :disabled="form.status == 2 ? true : false"
                              />
                            </template>
                          </el-table-column>
                          <el-table-column label="操作" width="120">
                            <template #default="scope">
                              <el-button
                                size="small"
                                @click="handleEdit(form.bodyDataTable)"
                                :disabled="form.status == 2 ? true : false"
                                >+</el-button
                              >
                              <el-button
                                size="small"
                                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-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 #append>
                      <el-button
                        type="primary"
                        @click="handleShowCron"
                        :disabled="form.status == 2 ? true : false"
                      >
                        生成表达式
                        <el-icon class="el-icon--right"><Timer /></el-icon>
                      </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"
                  />
                  <div
                    class="flex-center mb20"
                    v-for="(item, index) in 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="small"
                        type="danger"
                        @click="deleteOid(item, index)"
                        :icon="Minus"
                      />
                    </el-form-item>
                  </div>
                  <div class="flex-center">
                    <el-button size="small" type="primary" @click="addOid" :icon="Plus" />
                  </div>
                </div>
              </el-col>

              <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="8">
                <el-form-item :label="t('product.product-edit473153-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/imgs/gateway.png')]"
                      :src="require('@/assets/imgs/gateway.png')"
                      fit="cover"
                      v-if="form.deviceType == 2"
                    />
                    <el-image
                      style="height: 145px; height: 145px; border-radius: 10px"
                      :preview-src-list="[require('@/assets/imgs/video.png')]"
                      :src="require('@/assets/imgs/video.png')"
                      fit="cover"
                      v-else-if="form.deviceType == 3"
                    />
                    <el-image
                      style="height: 145px; height: 145px; border-radius: 10px"
                      :preview-src-list="[require('@/assets/imgs/product.png')]"
                      :src="require('@/assets/imgs/product.png')"
                      fit="cover"
                      v-else
                    />
                  </div>
                  <div v-else>
                    <image-upload
                      ref="imageUploadRef"
                      :disabled="true"
                      :value="form.imgUrl"
                      :limit="form.status == 2 ? 0 : 1"
                      :file-size="1"
                      @input="getImagePath"
                    />
                  </div>
                  <div
                    class="el-upload__tip"
                    style="color: #f56c6c"
                    v-if="form.productId == null || form.productId == 0"
                  >
                    {{ t('product.product-edit473153-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-show="form.productId != 0 && form.status != 2 && form.isOwner != 0"
                >
                  {{ t('product.product-edit473153-36') }}
                </el-button>

                <el-button
                  type="primary"
                  @click="submitForm"
                  v-show="form.productId == 0 && form.status != 2"
                  >{{ t('product.product-edit473153-37') }}</el-button
                >
              </el-form-item>
            </el-col>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="" name="things" :disabled="form.productId == 0">
          <template #label>
            <span style="color: red">*</span>
            {{ t('product.product-edit473153-38') }}
          </template>
          <product-things-model
            ref="productThingsModelRef"
            :product="form"
            @updateModel="updateModel"
          />
        </el-tab-pane>

        <el-tab-pane
          label=""
          name="sipConfig"
          :disabled="form.productId == 0"
          v-if="form.deviceType === 3"
        >
          <template #label>{{ t('product.product-edit473153-41') }}</template>
          <config-sip ref="configSipRef" :product="form" />
        </el-tab-pane>
        <el-tab-pane
          name="scada"
          :disabled="form.deviceId == 0"
          v-if="form.deviceType !== 3 && isShowScada == true"
          lazy
        >
          <template #label>{{ t('device.device-edit.148398-73') }}</template>
          <product-scada ref="productScadaRef" :product="form" />
        </el-tab-pane>
        <!-- 用于设置间距 -->
        <el-tab-pane>
          <template #label>
            <div style="margin-top: 200px"></div>
          </template>
        </el-tab-pane>
        <el-tab-pane v-if="form.status == 1" name="product04" disabled>
          <template #label>
            <el-button
              type="success"
              v-if="form.isOwner != 0"
              size="small"
              @click="changeProductStatusAsync(2)"
              >{{ t('product.product-edit473153-42') }}</el-button
            >
          </template>
        </el-tab-pane>
        <el-tab-pane v-if="form.status == 2" name="product05" disabled>
          <template #label>
            <el-button
              type="danger"
              v-if="form.isOwner != 0"
              size="small"
              @click="changeProductStatusAsync(1)"
              >{{ t('product.product-edit473153-43') }}</el-button
            >
          </template>
        </el-tab-pane>
        <el-tab-pane name="product06" disabled>
          <template #label>
            <el-button type="info" size="small" @click="goBack()">{{
              t('product.product-edit473153-44')
            }}</el-button>
          </template>
        </el-tab-pane>
      </el-tabs>
      <!--添加从机对话框-->
      <el-dialog v-model="open" :title="title" append-to-body width="1000px">
        <el-row :gutter="30">
          <el-col :span="11">
            <el-form ref="tempParamsRef" :inline="true" :model="tempParams">
              <el-form-item size="small">
                <el-input v-model="tempParams.templateName" placeholder="模板名称" />
              </el-form-item>
              <el-form-item size="small">
                <el-button :icon="Search" size="small" type="primary" @click="queryTemp"
                  >搜索</el-button
                >
                <el-button :icon="Refresh" size="small" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
            <el-table
              :border="false"
              ref="multipleTableRef"
              v-loading="loading"
              :data="tempList"
              highlight-current-row
              style="width: 100%"
            >
              <el-table-column align="left" label="选择采集点模板">
                <template #default="scope">
                  <el-radio
                    v-model="currentRow"
                    :label="scope.row"
                    @change="getCurrentRow(scope.row)"
                    >{{ scope.row.templateName }}</el-radio
                  >
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              v-show="tempTotal > 0"
              v-model:page-size="tempParams.pageSize"
              v-model:current-page="tempParams.pageNo"
              :total="tempTotal"
              layout="total, prev, pager, next"
              small
              @current-change="getTempList"
            />
          </el-col>
          <el-col :span="13">
            <el-form :inline="true" :model="pointsParams">
              <el-form-item size="small">
                <template #label>
                  <span style="font-size: 16px; font-weight: 400">物模型列表</span>
                </template>
              </el-form-item>
              <el-form-item size="small">
                <template #label>
                  <span style="font-weight: 400; font-size: 12px">从机数量:</span>
                </template>
                {{ selectRowData.slaveTotal }}
              </el-form-item>
              <el-form-item size="small">
                <template #label>
                  <span style="font-weight: 400; font-size: 12px">变量数量:</span>
                </template>
                {{ selectRowData.pointTotal }}
              </el-form-item>
              <el-form-item size="small">
                <template #label>
                  <span style="font-weight: 400; font-size: 12px">采集方式:</span>
                </template>
                <dict-tag
                  :options="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="small">
              <el-table-column label="物模型名称" prop="templateName" />
              <el-table-column label="寄存器" prop="regAddr" />
              <el-table-column label="数值类型" prop="datatype" />
            </el-table>
            <el-pagination
              v-show="total > 0"
              v-model:page-size="pointsParams.pageSize"
              v-model:current-page="pointsParams.pageNo"
              :total="total"
              layout="total, prev, pager, next"
              small
              @current-change="getList"
            />
          </el-col>
        </el-row>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submitSelect">确 定</el-button>
          </div>
        </template>
      </el-dialog>
      <el-dialog v-model="userEdit" title="登录信息" append-to-body @close="userClose">
        <el-form :inline="true" ref="userFormRef" :model="userParmas">
          <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>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="cancelUser">取 消</el-button>
            <el-button type="primary" @click="confirmUser">确 定</el-button>
          </div>
        </template>
      </el-dialog>
      <el-dialog
        v-model="openCron"
        title="Cron表达式生成器"
        append-to-body
        destroy-on-close
        class="scrollbar"
      >
        <crontab @hide="openCron = false" @fill="crontabFill" :expression="expression" />
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, getCurrentInstance } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import productThingsModel from './product-things-model.vue'
import imageUpload from './components/ImageUpload/index.vue'
import configSip from '../sip/sipconfig.vue'
import productScada from './product-scada.vue'
import { listProtocol } from '@/api/pms/video/protocol'

import { listShortCategory, listCategory } from '@/api/pms/video/category'
import { getDicts } from '@/api/pms/video/dicts'
import {
  addProduct,
  changeProductStatus,
  deviceCount,
  getProduct,
  updateProduct
} from '@/api/pms/video/product'
import { getTempByPId, listTemp } from '@/api/pms/video/temp'
import { getAllPoints } from '@/api/pms/video/template'

import Crontab from './components/Crontab/index.vue'
import { getAccessToken } from '@/utils/auth'
import { View, QuestionFilled, Timer, Minus, Plus, Search, Refresh } from '@element-plus/icons-vue'
import { useTagsViewStore } from '@/store/modules/tagsView'
import DeptTree from '@/views/system/user/DeptTree.vue'
import { defaultProps, handleTree } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import { IotDeviceApi } from '@/api/pms/device'

// 定义组件名称和属性
defineOptions({
  name: 'VideoCenterProductEdit'
})

// 获取实例、路由和路由器
const route = useRoute()
const router = useRouter()
const { t } = useI18n() // 国际化

// 字典定义
const iot_device_type = ref([])
const iot_network_method = ref([])
const iot_vertificate_method = ref([])
const iot_transport_type = ref([])
const data_collect_type = ref([])
const iot_location_way = ref([])
const sub_gateway_type = ref([])

// Refs
const formRef = ref(null)
const tempParamsRef = ref(null)
const multipleTableRef = ref(null)
const userFormRef = ref(null)
const imageUploadRef = ref(null)
const productThingsModelRef = ref(null)
const productFirmwareRef = ref(null)
const productAuthorizeRef = ref(null)
const configSipRef = ref(null)
const productScadaRef = ref(null)

// Reactive 数据
const dialogVisibleInterface = ref('MTG')
const expression = ref('')
const openCron = ref(false)

// 输入框类型
const keyInputType = ref('password')
const accountInputType = ref('password')
const passwordInputType = ref('password')

// 选中选项卡
const activeName = ref('basic')

// 分类短列表
const categoryShortList = ref([])

// 协议列表
const protocolList = ref([])

// 组态相关按钮是否显示，true显示，false不显示
const isShowScada = ref(false)

// 表单参数
const userParmas = reactive({
  isLogin: false
})

const userStatus = ref(false)
const userEdit = ref(false)

const userRule = {
  user: [
    {
      required: true,
      message: '用户id不能为空',
      trigger: 'blur'
    }
  ],
  password: [
    {
      required: true,
      message: '密码不能为空',
      trigger: 'blur'
    }
  ],
  url: [
    {
      required: true,
      message: '登录地址不能为空',
      trigger: 'blur'
    }
  ]
}

const deptList = ref([]) // 树形结构
let selectedDeptId = ref(null)
// 新增时部门改变时获取设备列表
const handleDeptChange = async (deptId) => {
  if (deptId) {
    selectedDeptId.value = deptId
    getDeviceList(deptId)
  }
}
// 获取设备列表
const deviceOptions = ref([])
const getDeviceList = async (deptId) => {
  try {
    const res = await IotDeviceApi.getIotDeviceSetOptions(deptId)
    deviceOptions.value = res.map((item) => ({
      key: item.id, // 始终使用id作为key
      label: `${item.deviceName} (${item.deviceCode})`,
      ...item
    }))
  } catch (err) {
    console.error(err)
  }
}

const form = reactive({
  networkMethod: 1,
  deviceType: 1,
  groupName: '',
  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 ' + getAccessToken()
    }
  ],
  // --------http协议---------

  //SNMP
  oidListStr: '',
  ipAddress: null,
  community: null,
  oidList: [
    {
      oidName: null,
      oid: null
    }
  ]
})

const tempOpen = ref(false)

// 表单校验
const rules = {
  groupName: [{ required: true, message: '请选择部门', trigger: 'change' }],
  productName: [
    {
      required: true,
      message: t('product.product-edit473153-58'),
      trigger: 'blur'
    }
  ],
  categoryId: [
    {
      required: true,
      message: t('product.product-edit473153-59'),
      trigger: 'blur'
    }
  ],
  deviceType: [
    {
      required: true,
      message: t('product.product-edit473153-13'),
      trigger: 'blur'
    }
  ],
  protocolCode: [
    {
      required: true,
      message: t('product.product-edit473153-60'),
      trigger: 'blur'
    }
  ],
  transport: [
    {
      required: true,
      message: t('product.product-edit473153-61'),
      trigger: 'blur'
    }
  ],
  isSys: [
    {
      required: true,
      message: t('product.product-edit473153-61'),
      trigger: 'blur'
    }
  ]
}

// 查询参数
const queryParams = reactive({
  tenantName: null
})

const pointList = ref([])
const open = ref(false)

// 弹出层标题
const title = ref('')

const loading = ref(true)
const tempList = ref([])

// 总条数
const total = ref(0)
const tempTotal = ref(0)

// 查询参数
const pointsParams = reactive({
  pageNo: 1,
  pageSize: 8,
  templateId: 0
})

const tempParams = reactive({
  pageNo: 1,
  pageSize: 10,
  templateName: ''
})

const currentRow = ref({})
const selectRowData = ref({})
const isModbus = ref(false)

// Computed properties
const networkOptions = computed(() => {
  return iot_network_method.value
})

// Methods
const userClose = () => {
  if (userParmas.isLogin) {
    for (let key in userParmas) {
      if (!userParmas[key]) {
        userParmas.isLogin = false
      }
    }
  }
}

const changeIsLogin = (status) => {
  if (status) {
    Object.assign(userParmas, {
      isLogin: true,
      user: '',
      password: '',
      url: ''
    })
    userEdit.value = true
  } else {
    Object.assign(userParmas, { isLogin: false })
  }
}

const cancelUser = () => {
  Object.assign(userParmas, { isLogin: false })
  userEdit.value = false
}

const confirmUser = () => {
  userFormRef.value.validate((valid) => {
    if (valid) {
      userEdit.value = false
    }
  })
}

const deleteOid = (item, index) => {
  form.oidList.splice(index, 1)
}

const addOid = (index) => {
  form.oidList.push({
    oidName: '',
    oid: ''
  })
}

/** cron表达式按钮操作 */
const handleShowCron = () => {
  expression.value = form.cronExpression
  openCron.value = true
}

/** 确定后回传值 */
const crontabFill = (value) => {
  form.cronExpression = value
}

const handleEdit = (row) => {
  let data = {
    key: '',
    value: ''
  }
  row.push(data)
}

const handleDelete = (xh, row) => {
  if (row.length == 1) {
    return
  }
  row.forEach((element, index) => {
    if (index == xh) {
      row.splice(index, 1)
    }
  })
}

// 获取简短分类列表
const getShortCategory = () => {
  listCategory().then((response) => {
    categoryShortList.value = response.list
  })
}

/** 返回按钮 */
const goBack = () => {
  // 关闭当前tab页签，打开新页签
  const { delView } = useTagsViewStore()
  // 先删除当前页签
  delView(unref(router.currentRoute))
  // 跳转到列表页
  router.push({ name: 'VideoCenterProduct' })
  reset()
}

/** 获取产品信息 */
const getProductInfo = () => {
  getProduct(form.productId).then((response) => {
    Object.assign(form, response)

    if (form.transport === 'HTTP') {
      Object.assign(userParmas, form.userParmas)
      form.bodyDataTable = []
      dialogVisibleInterface.value = 'HTTP'
      form.headersList = JSON.parse(form.headers)
      form.paramsDataList = JSON.parse(form.paramsData)

      if (form.contentTypeNumber === 2 || form.contentTypeNumber === 3) {
        let data1 = JSON.parse(form.data)

        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]
          form.bodyDataTable.push(obj)
          form.data = null
        }
      } else if (form.contentTypeNumber === 4 || form.contentTypeNumber === 5) {
        form.bodyDataArea = JSON.parse(form.data)
        form.bodyDataTable = [
          {
            key: '',
            value: ''
          }
        ]
      } else {
        form.bodyDataTable = [
          {
            key: '',
            value: ''
          }
        ]
      }
    }
    if (form.transport === 'SNMP') {
      dialogVisibleInterface.value = 'SNMP'
      form.oidList = JSON.parse(form.oidListStr)
    }
    changeProductCode(form.protocolCode)
  })
}

// 表单重置
const reset = () => {
  Object.assign(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 ' + getAccessToken()
      }
    ],
    // --------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: ''
  })
  formRef.value?.resetFields()
}

/** 提交按钮 */
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      let data = {}
      let bodyDataTable = form.bodyDataTable

      if (bodyDataTable) {
        for (let itemindex = 0; itemindex < bodyDataTable.length; itemindex++) {
          if (bodyDataTable[itemindex].key) {
            // 在 Vue 3 中可以直接赋值，响应式系统会自动检测变化
            data[bodyDataTable[itemindex].key] = bodyDataTable[itemindex].value
          }
        }
      }
      if (form.contentTypeNumber === 2) {
        form.contentType = 'multipart/form-data'
      } else if (form.contentTypeNumber === 3) {
        form.contentType = 'application/x-www-form-urlencoded;charset=utf-8'
      } else if (form.contentTypeNumber === 4) {
        form.contentType = 'application/json;charset=utf-8'
        data = form.bodyDataArea
      } else if (form.contentTypeNumber === 5) {
        form.contentType = 'text/xml'
        data = form.bodyDataArea
      } else {
        form.contentType = 'application/json;charset=utf-8'
      }

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

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

        updateProduct(form).then((response) => {
          changeProductCode(form.protocolCode)
          ElMessage.success(t('product.product-edit473153-62'))
        })
      } else {
        if (tempOpen.value && !form.templateId) {
          ElMessage('请选择采集点模板')
          return
        }

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

        // console.log(form, 'this.form');
        addProduct(form).then((response) => {
          if (!form.isModbus) {
            ElMessage.success(t('product.product-edit473153-64'))
          } else {
            ElMessage.success('物模型已经从采集点模板同步至产品')
          }
          Object.assign(form, response.data)
          changeProductCode(form.protocolCode)
        })
      }
    }
  })
}

/**同步获取产品下的设备数量**/
const getDeviceCountByProductId = (productId) => {
  return new Promise((resolve, reject) => {
    deviceCount(productId)
      .then((res) => {
        resolve(res)
      })
      .catch((error) => {
        reject(error)
      })
  })
}

/** 更新产品状态 */
const changeProductStatusAsync = async (status) => {
  let message = t('product.product-edit473153-66')
  if (status == 2) {
    message = t('product.product-edit473153-67')
  } else if (status == 1) {
    let result = await getDeviceCountByProductId(form.productId)
    if (result.data > 0) {
      message = t('product.product-edit473153-68', [result.data])
    }
  }

  ElMessageBox.confirm(message, t('product.product-edit473153-69'), {
    confirmButtonText: t('product.product-edit473153-70'),
    cancelButtonText: t('product.product-edit473153-71'),
    type: 'warning'
  })
    .then(() => {
      let data = {
        productId: form.productId,
        status: status,
        deviceType: form.deviceType
      }

      changeProductStatus(data)
        .then((response) => {
          if (status == 2) {
            ElMessage.success('发布成功')
          }
          activeName.value = 'basic'
          getProductInfo()
        })
        .catch(() => {
          if (status == 2) {
            activeName.value = 'basic'
          } else {
            goBack()
          }
        })
    })
    .catch(() => {
      activeName.value = 'basic'
    })
}

/** 选择分类 */
const selectCategory = (val) => {
  for (let i = 0; i < categoryShortList.value.length; i++) {
    if (categoryShortList.value[i].categoryId == val) {
      form.categoryName = categoryShortList.value[i].categoryName
      return
    }
  }
}

/**获取上传图片的路径 */
const getImagePath = (data) => {
  form.imgUrl = data
}

/**改变输入框类型**/
const changeInputType = (name) => {
  if (name == 'key') {
    keyInputType.value = keyInputType.value == 'password' ? 'text' : 'password'
  } else if (name == 'account') {
    accountInputType.value = accountInputType.value == 'password' ? 'text' : 'password'
  } else if (name == 'password') {
    passwordInputType.value = passwordInputType.value == 'password' ? 'text' : 'password'
  }
}

const isInitialized = ref(false)
// 授权码状态修改
const changeIsAuthorize = () => {
  if (!isInitialized.value) return
  let text =
    form.isAuthorize == '1'
      ? t('product.product-edit473153-72')
      : t('product.product-edit473153-74')

  ElMessageBox.confirm(t('product.product-edit473153-75', [text]), '提示', {
    confirmButtonText: t('product.product-edit473153-70'),
    cancelButtonText: t('product.product-edit473153-71'),
    type: 'warning'
  })
    .then(() => {
      if (form.productId != null && form.productId != 0) {
        updateProduct(form).then((response) => {
          ElMessage.success(t('product.product-edit473153-77') + text)
        })
      }
    })
    .catch(() => {
      form.isAuthorize = 0
    })
}

//获取设备协议
const getProtocol = () => {
  const data = {
    protocolStatus: 1,
    pageSize: 99
  }
  listProtocol(data).then((res) => {
    protocolList.value = res.list
  })
}

/*选择模板*/
const selectTemplate = () => {
  // reset();
  open.value = true
  title.value = '选择模板'
  getTempList()
  // getList()
}

const getTempDetail = () => {
  const params = {
    productId: form.productId
  }
  getTempByPId(params).then((response) => {
    selectRowData.value = response.data
  })
}

// 取消按钮
const cancel = () => {
  open.value = false
  // reset();
}

/** 查询设备采集变量模板列表 */
const getTempList = () => {
  loading.value = true
  listTemp(tempParams).then((response) => {
    tempList.value = response.list
    tempTotal.value = response.total
    currentRow.value = tempList.value[0]
    // pointsParams.templateId = currentRow.value.templateId;
    getCurrentRow(tempList.value[0])
    loading.value = false
    getList()
  })
}

const getList = () => {
  getAllPoints(pointsParams).then((response) => {
    pointList.value = response
    total.value = response.length || 0
  })
}

/*确认选择*/
const submitSelect = () => {
  open.value = false
  form.templateId = selectRowData.value.templateId
}

const getCurrentRow = (val) => {
  if (val != null) {
    selectRowData.value = val
  }
  pointsParams.templateId = val.templateId
  getList()
}

const deleteData = () => {
  selectRowData.value = {}
  form.templateId = null
}

const transportChange = (val) => {
  if (val === 'HTTP') {
    dialogVisibleInterface.value = 'HTTP'
  } else if (val === 'SNMP') {
    dialogVisibleInterface.value = 'SNMP'
  } else {
    dialogVisibleInterface.value = 'MTG'
  }
}

const changeProductCode = (val) => {
  if (val && val.startsWith('MODBUS')) {
    tempOpen.value = true
    form.deviceType = 2
    form.isModbus = true
    if (form.productId != 0 && form.productId != null) {
      getTempDetail()
    }
  } else {
    form.isModbus = false
    tempOpen.value = false
  }
}

/**选项卡切换事件**/
const tabChange = (tabItem) => {
  // 切换到告警配置，获取物模型
  if (tabItem === 'alert') {
    productThingsModelRef.value.getCacheThingsModel(form.productId)
  } else if (tabItem === 'productFirmware') {
    productFirmwareRef.value.getList()
  } else if (tabItem === 'productAuthorize') {
    productAuthorizeRef.value.queryParams.productId = form.productId
    productAuthorizeRef.value.getList()
  }
}

/*按照模板名查询*/
const queryTemp = () => {
  getTempList()
}

/** 搜索按钮操作 */
const handleQuery = () => {
  tempParams.pageNo = 1
  getTempList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  tempParamsRef.value?.resetFields()
  handleQuery()
}

/**刷新产品模型 */
const updateModel = () => {
  productModbusRef.value.getThingsModelList()
}

// Lifecycle hooks
onMounted(async () => {
  // 获取产品信息
  const productId = route.query && route.query.productId
  form.productId = productId
  if (form.productId != 0 && form.productId != null) {
    getProductInfo()
  }
  // 切换选项卡
  const tabPanelName = route.query && route.query.tabPanelName
  if (tabPanelName != null && tabPanelName != '') {
    activeName.value = tabPanelName
  }
  // 获取分类信息
  getShortCategory()
  // 设置账号密码输入框类型,新增时为text，查看时为password
  if (!form.productId || form.productId == 0) {
    accountInputType.value = 'text'
    passwordInputType.value = 'text'
  }
  getProtocol()

  getDicts('iot_device_type').then((response) => {
    iot_device_type.value = response
  })

  getDicts('iot_transport_type').then((response) => {
    iot_transport_type.value = response
  })

  // iot_network_method
  getDicts('iot_network_method').then((response) => {
    iot_network_method.value = response
  })

  getDicts('iot_vertificate_method').then((response) => {
    iot_vertificate_method.value = response
  })
  getDicts('data_collect_type').then((response) => {
    data_collect_type.value = response
  })
  getDicts('iot_location_way').then((response) => {
    iot_location_way.value = response
  })
  getDicts('sub_gateway_type').then((response) => {
    sub_gateway_type.value = response
  })
  deptList.value = handleTree(await DeptApi.getSimpleDeptList())

  setTimeout(() => {
    isInitialized.value = true
  }, 0)
})
</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%);
}
::v-deep .el-alert__description {
  font-size: 12px;
}
</style>
