<template>
  <div style="padding-left: 20px">
    <el-form
      :model="queryParams"
      ref="queryFormRef"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item :label="t('product.product-things-model142341-127')" prop="isAPP">
        <el-select
          v-model="queryParams.isAPP"
          :placeholder="t('product.product-things-model142341-128')"
          clearable
          size="small"
          style="width: 150px"
        >
          <el-option
            v-for="dict in iot_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('product.product-things-model142341-129')" prop="type">
        <el-select
          v-model="queryParams.type"
          :placeholder="t('product.product-things-model142341-130')"
          clearable
          size="small"
          style="width: 150px"
        >
          <el-option
            v-for="dict in iot_things_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('product.product-things-model142341-131')" prop="isHistory">
        <el-select
          v-model="queryParams.isHistory"
          :placeholder="t('product.product-things-model142341-132')"
          clearable
          size="small"
          style="width: 150px"
        >
          <el-option
            v-for="dict in iot_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" size="small" @click="handleQuery">{{
          t('product.product-things-model142341-133')
        }}</el-button>
        <el-button :icon="Refresh" size="small" @click="resetQuery">{{
          t('product.product-things-model142341-134')
        }}</el-button>
      </el-form-item>
      <el-form-item label="设备从机:" v-if="queryParams.isModbus">
        <el-select v-model="slave.id" placeholder="请选择设备从机" @change="selectSlave">
          <el-option
            v-for="slaveItem in slaveList"
            :key="slaveItem.slaveAddr"
            :label="`${slaveItem.slaveName}   (${slaveItem.slaveAddr})`"
            :value="slaveItem.slaveAddr"
          />
        </el-select>
        <el-button style="margin-left: 20px" plain size="small" type="primary" @click="getGateway"
          >网关物模型</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb20">
      <el-col :span="1.5" v-if="productInfo.status == 1 && productInfo.isOwner != 0">
        <el-button
          type="primary"
          plain
          :icon="Plus"
          size="small"
          @click="handleAdd"
          v-hasPermi="['iot:model:add']"
        >
          {{ t('product.product-things-model142341-0') }}
        </el-button>
      </el-col>
      <!-- <el-col :span="1.5" v-if="productInfo.status == 1 && productInfo.isOwner != 0">
        <el-button type="primary" plain :icon="Upload" size="small" @click="handleImport" v-hasPermi="['iot:point:import']">
          {{ t('product.product-things-model142341-126') }}
        </el-button>
      </el-col> -->
      <el-col :span="1.5" v-if="productInfo.status == 1 && productInfo.isOwner != 0">
        <el-button type="primary" plain :icon="Upload2" size="small" @click="handleSelect">
          {{ t('product.product-things-model142341-1') }}
        </el-button>
      </el-col>
      <el-col :span="1.5" class="flex-center">
        <el-button type="primary" plain :icon="Refresh" size="small" @click="getList">{{
          t('product.product-things-model142341-2')
        }}</el-button>
      </el-col>
      <el-col :span="1.5" class="flex-center">
        <el-button type="info" plain :icon="View" size="small" @click="handleOpenThingsModel">
          {{ t('product.product-things-model142341-3') }}
        </el-button>
      </el-col>
      <el-col :span="1.5" class="flex-center">
        <el-link type="danger" style="padding-top: 5px" :underline="false">
          {{ t('product.product-things-model142341-4') }}
        </el-link>
      </el-col>

      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
    </el-row>
    <el-table :border="false" v-loading="loading" :data="modelList" size="small">
      <el-table-column
        :label="t('product.product-things-model142341-8')"
        align="center"
        prop="modelName"
        width="230"
      />
      <el-table-column
        :label="t('product.product-things-model142341-9')"
        align="center"
        prop="identifier"
      />
      <el-table-column
        v-if="queryParams.isModbus"
        align="center"
        label="寄存器地址(10进制)"
        prop="regAddr"
      />
      <el-table-column
        :label="t('product.product-things-model142341-12')"
        align="center"
        prop=""
        width="80"
      >
        <template #default="scope">
          <dict-tag :options="iot_yes_no" :value="scope.row.isChart" />
        </template>
      </el-table-column>
      <el-table-column label="实时监测" align="center" prop="" width="75">
        <template #default="scope">
          <dict-tag :options="iot_yes_no" :value="scope.row.isMonitor" />
        </template>
      </el-table-column>
      <el-table-column label="APP展示" align="center" prop="" width="75">
        <template #default="scope">
          <dict-tag :options="iot_yes_no" :value="scope.row.isApp" />
        </template>
      </el-table-column>
      <el-table-column label="只读" align="center" prop="" width="75">
        <template #default="scope">
          <dict-tag :options="iot_yes_no" :value="scope.row.isReadonly" />
        </template>
      </el-table-column>
      <el-table-column
        :label="t('product.product-things-model142341-15')"
        align="center"
        prop=""
        width="75"
      >
        <template #default="scope">
          <dict-tag :options="iot_yes_no" :value="scope.row.isHistory" />
        </template>
      </el-table-column>
      <el-table-column
        :label="t('product.product-things-model142341-16')"
        align="center"
        prop="type"
        width="100"
      >
        <template #default="scope">
          <dict-tag :options="iot_things_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column
        :label="t('product.product-things-model142341-17')"
        align="center"
        prop="datatype"
        width="80"
      >
        <template #default="scope">
          <dict-tag :options="iot_data_type" :value="scope.row.datatype" />
        </template>
      </el-table-column>
      <el-table-column
        :label="t('product.product-things-model142341-18')"
        align="left"
        header-align="center"
        prop="specs"
        min-width="150"
        class-name="specsColor"
      >
        <template #default="scope">
          <div v-html="formatSpecsDisplay(scope.row.specs)"></div>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('product.product-things-model142341-19')"
        align="center"
        prop="formula"
      />
      <el-table-column
        :label="t('product.product-things-model142341-20')"
        align="center"
        prop="modelOrder"
        width="80"
      />
      <el-table-column
        :label="t('product.product-things-model142341-21')"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            :icon="View"
            @click="handleUpdate(scope.row)"
            v-if="productInfo.status != 2 && productInfo.isOwner != 0"
          >
            {{ t('product.product-things-model142341-22') }}
          </el-button>
          <el-button
            size="small"
            type="danger"
            :icon="Delete"
            @click="handleDelete(scope.row)"
            v-if="productInfo.status != 2 && productInfo.isOwner != 0"
          >
            {{ t('product.product-things-model142341-23') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-show="total > 0"
      v-model:current-page="queryParams.pageNo"
      v-model:page-size="queryParams.pageSize"
      :total="total"
      layout="prev, pager, next"
      small
      @current-change="getList"
    />

    <!-- 添加或修改物模型对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item :label="t('product.product-things-model142341-24')" prop="modelName">
          <el-input
            v-model="form.modelName"
            :placeholder="t('product.product-things-model142341-25')"
            style="width: 385px"
          />
        </el-form-item>
        <el-form-item :label="t('product.product-things-model142341-26')" prop="identifier">
          <el-input
            v-model="form.identifier"
            :placeholder="t('product.product-things-model142341-27')"
            style="width: 385px"
          />
        </el-form-item>
        <el-form-item v-if="queryParams.isModbus" label="寄存器地址" prop="regAddr">
          <el-input v-model="form.regAddr" style="width: 385px" />
        </el-form-item>
        <el-form-item :label="t('product.product-things-model142341-28')" prop="modelOrder">
          <el-input
            v-model="form.modelOrder"
            :placeholder="t('product.product-things-model142341-29')"
            type="number"
            style="width: 385px"
          />
        </el-form-item>
        <el-form-item :label="t('product.product-things-model142341-30')" prop="type">
          <el-radio-group v-model="form.type" @change="typeChange">
            <el-radio-button label="1">{{
              t('product.product-things-model142341-31')
            }}</el-radio-button>
            <el-radio-button label="2">{{
              t('product.product-things-model142341-32')
            }}</el-radio-button>
            <el-radio-button label="3">{{
              t('product.product-things-model142341-33')
            }}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="t('product.product-things-model142341-34')" prop="property">
          <el-checkbox
            name="isChart"
            :label="t('product.product-things-model142341-12')"
            @change="isChartChange"
            v-show="form.type == 1"
            v-model="form.isChart"
            :false-label="0"
            :true-label="1"
          />
          <el-checkbox
            name="isMonitor"
            :label="t('product.product-select-template.318012-9')"
            v-show="form.type == 1"
            v-model="form.isMonitor"
            :false-label="0"
            :true-label="1"
            @change="isMonitorChange"
          />
          <el-checkbox
            name="isReadonly"
            :label="t('product.product-things-model142341-35')"
            v-model="form.isReadonly"
            :disabled="form.type == 3"
            :false-label="0"
            :true-label="1"
            @change="isReadonlyChange"
          />
          <el-checkbox
            name="isHistory"
            :label="t('product.product-things-model142341-15')"
            v-model="form.isHistory"
            :true-label="1"
            :false-label="0"
          />
          <el-checkbox
            name="isSharePerm"
            :label="t('product.product-things-model142341-36')"
            v-model="form.isSharePerm"
            :true-label="1"
            :false-label="0"
          />
        </el-form-item>
        <el-divider />
        <el-form-item :label="t('product.product-app.045891-5')" prop="datatype">
          <el-select
            v-model="form.datatype"
            :placeholder="t('product.product-things-model142341-37')"
            @change="dataTypeChange"
            style="width: 175px"
          >
            <el-option
              key="integer"
              :label="t('product.product-things-model142341-38')"
              value="integer"
            />
            <el-option
              key="decimal"
              :label="t('product.product-things-model142341-39')"
              value="decimal"
            />
            <el-option
              key="bool"
              :label="t('product.product-things-model142341-40')"
              value="bool"
              :disabled="form.isChart == 1"
            />
            <el-option
              key="enum"
              :label="t('product.product-things-model142341-41')"
              value="enum"
              :disabled="form.isChart == 1"
            />
            <el-option
              key="string"
              :label="t('product.product-things-model142341-42')"
              value="string"
              :disabled="form.isChart == 1"
            />
            <el-option
              key="array"
              :label="t('product.product-things-model142341-43')"
              value="array"
              :disabled="form.isChart == 1"
            />
            <el-option
              key="object"
              :label="t('product.product-things-model142341-44')"
              value="object"
              :disabled="form.isChart == 1"
            />
          </el-select>
        </el-form-item>

        <div v-if="form.datatype == 'integer' || form.datatype == 'decimal'">
          <el-form-item :label="t('product.product-things-model142341-45')">
            <el-row>
              <el-col :span="9">
                <el-input
                  v-model="form.specs.min"
                  :placeholder="t('product.product-things-model142341-46')"
                  type="number"
                />
              </el-col>
              <el-col :span="2" align="center">{{
                t('product.product-things-model142341-47')
              }}</el-col>
              <el-col :span="9">
                <el-input
                  v-model="form.specs.max"
                  :placeholder="t('product.product-things-model142341-48')"
                  type="number"
                />
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item :label="t('product.product-things-model142341-49')">
            <el-input
              v-model="form.specs.unit"
              :placeholder="t('product.product-things-model142341-50')"
              style="width: 385px"
            />
          </el-form-item>
          <el-form-item :label="t('product.product-things-model142341-51')">
            <el-input
              v-model="form.specs.step"
              :placeholder="t('product.product-things-model142341-52')"
              type="number"
              style="width: 385px"
            />
          </el-form-item>
          <el-form-item :label="t('product.product-things-model142341-19')" prop="formula">
            <template #label>
              <span>{{ t('product.product-things-model142341-19') }}</span>
              <el-tooltip style="cursor: pointer" effect="light" placement="top">
                <template #content>
                  {{ t('product.product-things-model142341-53') }}
                  <br />
                  {{ t('product.product-things-model142341-54') }}
                  <br />
                  {{ t('product.product-things-model142341-55') }}
                  <br />
                  {{ t('product.product-things-model142341-56') }}
                  <br />
                  {{ t('product.product-things-model142341-57') }}
                  <br />
                  {{ t('product.product-things-model142341-58') }}
                  <br />
                  {{ t('product.product-things-model142341-59') }}
                  <br />
                  {{ t('product.product-things-model142341-60') }}({{
                    t('product.product-things-model142341-61')
                  }})：%s%10.00
                  <br />
                </template>
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </template>
            <el-input v-model="form.formula" style="width: 385px" />
          </el-form-item>
          <el-form-item v-if="queryParams.isModbus" label="控制公式" prop="reverseFormula">
            <el-input v-model="form.reverseFormula" style="width: 385px" />
          </el-form-item>
        </div>

        <div v-if="form.datatype == 'bool'">
          <el-form-item :label="t('product.product-things-model142341-63')" prop="">
            <el-row style="margin-bottom: 10px">
              <el-col :span="9">
                <el-input
                  v-model="form.specs.falseText"
                  :placeholder="t('product.product-things-model142341-64')"
                />
              </el-col>
              <el-col :span="10" :offset="1">{{
                t('product.product-things-model142341-65')
              }}</el-col>
            </el-row>
            <el-row>
              <el-col :span="9">
                <el-input
                  v-model="form.specs.trueText"
                  :placeholder="t('product.product-things-model142341-66')"
                />
              </el-col>
              <el-col :span="10" :offset="1">{{
                t('product.product-things-model142341-67')
              }}</el-col>
            </el-row>
          </el-form-item>
        </div>

        <div v-if="form.datatype == 'enum'">
          <el-form-item :label="t('product.product-things-model142341-68')">
            <el-select
              v-model="form.specs.showWay"
              :placeholder="t('product.product-things-model142341-69')"
              style="width: 175px"
            >
              <el-option
                key="select"
                :label="t('product.product-things-model142341-70')"
                value="select"
              />
              <el-option
                key="button"
                :label="t('product.product-things-model142341-71')"
                value="button"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="t('product.product-things-model142341-72')" prop="">
            <el-row
              v-for="(item, index) in form.specs.enumList"
              :key="'enum' + index"
              style="margin-bottom: 10px"
            >
              <el-col :span="9">
                <el-input
                  v-model="item.value"
                  :placeholder="t('product.product-things-model142341-73')"
                />
              </el-col>
              <el-col :span="11" :offset="1">
                <el-input
                  v-model="item.text"
                  :placeholder="t('product.product-things-model142341-74')"
                />
              </el-col>
              <el-col :span="2" :offset="1" v-if="index != 0">
                <a style="color: #f56c6c" @click="removeEnumItem(index)">{{ t('del') }}</a>
              </el-col>
            </el-row>
            <div>
              +
              <a style="color: #409eff" @click="addEnumItem()">{{
                t('product.product-things-model142341-75')
              }}</a>
            </div>
          </el-form-item>
        </div>

        <div v-if="form.datatype == 'string'">
          <el-form-item :label="t('product.product-things-model142341-76')" prop="">
            <el-row>
              <el-col :span="9">
                <el-input
                  v-model="form.specs.maxLength"
                  :placeholder="t('product.product-things-model142341-77')"
                  type="number"
                />
              </el-col>
              <el-col :span="14" :offset="1">{{
                t('product.product-things-model142341-78')
              }}</el-col>
            </el-row>
          </el-form-item>
        </div>

        <div v-if="form.datatype == 'array'">
          <el-form-item :label="t('product.product-things-model142341-79')" prop="">
            <el-row>
              <el-col :span="9">
                <el-input
                  v-model="form.specs.arrayCount"
                  :placeholder="t('product.product-things-model142341-80')"
                  type="number"
                />
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item :label="t('product.product-things-model142341-81')" prop="">
            <el-radio-group v-model="form.specs.arrayType">
              <el-radio label="integer">{{ t('product.product-things-model142341-38') }}</el-radio>
              <el-radio label="decimal">{{ t('product.product-things-model142341-39') }}</el-radio>
              <el-radio label="string">{{ t('product.product-things-model142341-42') }}</el-radio>
              <el-radio label="object">{{ t('product.product-things-model142341-44') }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            :label="t('product.product-things-model142341-82')"
            v-if="form.specs.arrayType == 'object'"
          >
            <div style="background-color: #f8f8f8; border-radius: 5px">
              <el-row
                style="padding: 0 10px 5px"
                v-for="(item, index) in form.specs.params"
                :key="index"
              >
                <div style="margin-top: 5px" v-if="index == 0"></div>
                <el-col :span="18">
                  <el-input
                    readonly
                    v-model="item.name"
                    size="small"
                    :placeholder="t('product.product-things-model142341-83')"
                    style="margin-top: 3px"
                  >
                    <template #prepend>
                      <el-tag
                        effect="dark"
                        size="small"
                        style="margin-left: -21px; height: 26px; line-height: 26px"
                        >{{ item.order }}</el-tag
                      >
                      {{ form.identifier + '_' + item.id }}
                    </template>
                    <template #append>
                      <el-button @click="editParameter(item, index)" size="small">{{
                        t('edit')
                      }}</el-button>
                    </template>
                  </el-input>
                </el-col>
                <el-col :span="2" :offset="2">
                  <el-button
                    :icon="Delete"
                    plain
                    size="small"
                    style="padding: 5px"
                    type="danger"
                    @click="removeParameter(index)"
                    >{{ t('del') }}</el-button
                  >
                </el-col>
              </el-row>
            </div>
            <div>
              +
              <a style="color: #409eff" @click="addParameter()">{{
                t('product.product-things-model142341-85')
              }}</a>
            </div>
          </el-form-item>
        </div>
        <div v-if="form.datatype == 'object'">
          <el-form-item :label="t('product.product-things-model142341-82')" prop="">
            <div style="background-color: #f8f8f8; border-radius: 5px">
              <el-row
                style="padding: 0 10px 5px"
                v-for="(item, index) in form.specs.params"
                :key="index"
              >
                <div style="margin-top: 5px" v-if="index == 0"></div>
                <el-col :span="18">
                  <el-input
                    readonly
                    v-model="item.name"
                    size="small"
                    :placeholder="t('product.product-things-model142341-83')"
                    style="margin-top: 3px"
                  >
                    <template #prepend>
                      <el-tag
                        effect="dark"
                        size="small"
                        style="margin-left: -21px; height: 26px; line-height: 26px"
                        >{{ item.order }}</el-tag
                      >
                      {{ form.identifier + '_' + item.id }}
                    </template>
                    <template #append>
                      <el-button @click="editParameter(item, index)" size="small">{{
                        t('edit')
                      }}</el-button>
                    </template>
                  </el-input>
                </el-col>
                <el-col :span="2" :offset="2">
                  <el-button
                    :icon="Delete"
                    plain
                    size="small"
                    style="padding: 5px"
                    type="danger"
                    @click="removeParameter(index)"
                    >{{ t('del') }}</el-button
                  >
                </el-col>
              </el-row>
            </div>
            <div>
              +
              <a style="color: #409eff" @click="addParameter()">{{
                t('product.product-things-model142341-85')
              }}</a>
            </div>
          </el-form-item>
        </div>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" v-show="form.modelId"> 更新 </el-button>
          <el-button type="primary" @click="submitForm" v-show="!form.modelId">添加</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!--物模型参数类型-->
    <things-parameter :data="paramData" @dataEvent="getParamData" />

    <!-- 导入通用物模型对话框 -->
    <el-dialog :title="title" v-model="openSelect" width="800px" append-to-body>
      <product-select-template ref="productSelectTemplateRef" @idsToParentEvent="getChildData" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="importSelect">导入</el-button>
          <el-button @click="cancelSelect">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 物模型JSON -->
    <el-dialog :title="title" v-model="openThingsModel" width="600px" append-to-body>
      <div style="border: 1px solid #ccc; margin-top: -15px; height: 600px; overflow: scroll">
        <json-viewer :value="thingsModel" :expand-depth="10" copyable>
          <template #copy>{{ t('product.product-things-model142341-92') }}</template>
        </json-viewer>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="info" @click="handleCloseThingsModel">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 批量导入 -->
    <!--    <import-batch ref="importBatchRef" :productId="productId" />-->
  </div>
</template>

<script setup>
import { ref, reactive, watch, getCurrentInstance, onMounted } from 'vue'
import productSelectTemplate from './product-select-template.vue'
import JsonViewer from 'vue-json-viewer'
import RightToolbar from './components/RightToolbar/index.vue'
import 'vue-json-viewer/style.css'
import thingsParameter from './template/parameter.vue'
import {
  addModel,
  delModel,
  getModel,
  importModel,
  listModel,
  updateModel
} from '@/api/pms/video/model'
import { listByPid } from '@/api/pms/video/salve'
import {
  Search,
  Refresh,
  Plus,
  Upload,
  View,
  Delete,
  QuestionFilled
} from '@element-plus/icons-vue'

// 定义组件名称
defineOptions({
  name: 'product-things-model'
})

const { t } = useI18n()

// 定义props
const props = defineProps({
  product: {
    type: Object,
    default: null
  },
  isEdit: {
    type: Boolean,
    default: true
  }
})

// 定义emits
const emit = defineEmits(['updateModel'])

// 字典定义
const iot_things_type = []
const iot_data_type = []
const iot_yes_no = []

// Refs
const queryFormRef = ref(null)
const formRef = ref(null)
const productSelectTemplateRef = ref(null)

// 数据定义
// 物模型
const thingsModel = ref({})
// 父组件接收的产品信息
const productInfo = ref({})
// 子组件选中的id数组
const templateIds = ref([])
// 遮罩层
const loading = ref(false)
// 选中数组
const ids = ref([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 显示搜索条件
const showSearch = ref(true)
// 总条数
const total = ref(0)
// 产品物模型表格数据
const modelList = ref([])
// 弹出层标题
const title = ref('')
// 是否显示弹出层
const open = ref(false)
const openSelect = ref(false)
const openThingsModel = ref(false)
// 查询参数
const queryParams = reactive({
  productId: 0,
  pageNo: 1,
  pageSize: 20
})
const productId = ref(0)
// 表单参数
const form = reactive({
  templateId: null,
  templateName: null,
  userId: null,
  userName: null,
  tenantId: null,
  tenantName: null,
  identifier: null,
  modelOrder: 0,
  type: 1,
  datatype: 'integer',
  isSys: null,
  isChart: 1,
  isHistory: 1,
  isSharePerm: 1,
  isMonitor: 1,
  isReadonly: 1,
  delFlag: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  remark: null,
  specs: {
    enumList: [
      {
        value: '',
        text: ''
      }
    ],
    arrayType: 'integer',
    arrayCount: 5,
    showWay: 'select', // 显示方式select=下拉选择框，button=按钮
    params: []
  }
})

// 对象类型参数
const paramData = reactive({
  index: -1,
  parameter: {}
})

//是否是modbus
const isModbus = ref(false)
const slaveList = ref([])
const slave = reactive({})

// 表单校验
const rules = {
  modelName: [
    {
      required: true,
      message: t('product.product-things-model142341-94'),
      trigger: 'blur'
    }
  ],
  identifier: [
    {
      required: true,
      message: t('product.product-things-model142341-95'),
      trigger: 'blur'
    }
  ],
  modelOrder: [
    {
      required: true,
      message: t('product.product-things-model142341-96'),
      trigger: 'blur'
    }
  ],
  type: [
    {
      required: true,
      message: t('product.product-things-model142341-97'),
      trigger: 'change'
    }
  ],
  datatype: [
    {
      required: true,
      message: t('product.product-things-model142341-98'),
      trigger: 'change'
    }
  ]
}

// Watchers
watch(
  () => props.product,
  (newVal, oldVal) => {
    productInfo.value = newVal
    if (productInfo.value && productInfo.value.productId != 0) {
      queryParams.productId = productInfo.value.productId
      productId.value = productInfo.value.productId
      queryParams.isModbus = productInfo.value.isModbus
      getList()
      if (queryParams.isModbus) {
        getSlaveList()
      }
    }
  }
)

// 方法定义
/** 查询产品物模型列表 */
const getList = () => {
  loading.value = true
  listModel(queryParams).then((response) => {
    modelList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/**根据产品id获取从机列表*/
const getSlaveList = () => {
  const params = {
    productId: queryParams.productId
  }
  listByPid(params).then((response) => {
    slaveList.value = response.data
    slave.id = slaveList.value[0].slaveAddr
    queryParams.tempSlaveId = slaveList.value[0].slaveAddr
    getList()
  })
}

const selectSlave = () => {
  queryParams.tempSlaveId = slave.id
  getList()
}

const getGateway = () => {
  queryParams.tempSlaveId = undefined
  getList()
}

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

// 表单重置
const reset = () => {
  Object.assign(form, {
    templateId: null,
    templateName: null,
    userId: null,
    userName: null,
    tenantId: null,
    tenantName: null,
    identifier: null,
    modelOrder: 0,
    type: 1,
    datatype: 'integer',
    isSys: null,
    isChart: 1,
    isHistory: 1,
    isSharePerm: 1,
    isMonitor: 1,
    isReadonly: 1,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
    specs: {
      enumList: [
        {
          value: '',
          text: ''
        }
      ],
      arrayType: 'integer',
      arrayCount: 5,
      showWay: 'select', // 显示方式select=下拉选择框，button=按钮
      params: []
    }
  })
  formRef.value?.resetFields()
}

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

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

/** 新增按钮操作 */
const handleAdd = () => {
  reset()
  open.value = true
  title.value = t('product.product-things-model142341-99')
}

/** 修改按钮操作 */
const handleUpdate = (row) => {
  reset()
  const modelId = row.modelId
  getModel(modelId).then((response) => {
    let tempForm = response.data
    open.value = true
    title.value = t('product.product-things-model142341-100')
    // Json转对象
    tempForm.specs = JSON.parse(tempForm.specs)
    if (!tempForm.specs.enumList) {
      tempForm.specs.showWay = 'select'
      tempForm.specs.enumList = [
        {
          value: '',
          text: ''
        }
      ]
    }
    if (!tempForm.specs.arrayType) {
      tempForm.specs.arrayType = 'integer'
    }
    if (!tempForm.specs.arrayCount) {
      tempForm.specs.arrayCount = 5
    }
    if (!tempForm.specs.params) {
      tempForm.specs.params = []
    }
    // 对象和数组中参数删除前缀
    if (
      (tempForm.specs.type == 'array' && tempForm.specs.arrayType == 'object') ||
      tempForm.specs.type == 'object'
    ) {
      for (let i = 0; i < tempForm.specs.params.length; i++) {
        tempForm.specs.params[i].id = String(tempForm.specs.params[i].id).substring(
          String(tempForm.identifier).length + 1
        )
      }
    }
    Object.assign(form, tempForm)
  })
}

/**查看物模型 */
const handleOpenThingsModel = () => {
  title.value = t('product.product-things-model142341-101')
  // 生成物模型
  thingsModel.value = {
    properties: [],
    functions: [],
    events: []
  }
  for (var i = 0; i < modelList.value.length; i++) {
    let thingsItem = {}
    thingsItem.id = modelList.value[i].identifier
    thingsItem.name = modelList.value[i].modelName
    if (modelList.value[i].type == 1) {
      //属性
      thingsItem.isChart = modelList.value[i].isChart
      thingsItem.isMonitor = modelList.value[i].isMonitor
      thingsItem.isHistory = modelList.value[i].isHistory
      thingsItem.isSharePerm = modelList.value[i].isSharePerm
      thingsItem.isReadonly = modelList.value[i].isReadonly
      thingsItem.datatype = JSON.parse(modelList.value[i].specs)
      thingsModel.value.properties.push(thingsItem)
    } else if (modelList.value[i].type == 2) {
      // 功能
      thingsItem.isHistory = modelList.value[i].isHistory
      thingsItem.isSharePerm = modelList.value[i].isSharePerm
      thingsItem.isReadonly = modelList.value[i].isReadonly
      thingsItem.datatype = JSON.parse(modelList.value[i].specs)
      thingsModel.value.functions.push(thingsItem)
    } else if (modelList.value[i].type == 3) {
      // 事件
      thingsItem.isHistory = modelList.value[i].isHistory
      thingsItem.isSharePerm = modelList.value[i].isSharePerm
      thingsItem.isReadonly = modelList.value[i].isReadonly
      thingsItem.datatype = JSON.parse(modelList.value[i].specs)
      thingsModel.value.events.push(thingsItem)
    }
  }

  openThingsModel.value = true
}

/**关闭物模型 */
const handleCloseThingsModel = () => {
  openThingsModel.value = false
}

/** 选择物模型 */
const handleSelect = () => {
  openSelect.value = true
  title.value = t('product.product-things-model142341-1')
  form.type = 1
  form.datatype = 'integer'
  form.specs = {
    enumList: []
  }
}

// 取消导入通用物模型按钮
const cancelSelect = () => {
  openSelect.value = false
  productSelectTemplateRef.value?.selectTemplateTable.clearSelection()
}

// 获取子组件的值
const getChildData = (data) => {
  templateIds.value = data
}

// 导入通用物模型按钮
const importSelect = () => {
  if (templateIds.value != null && templateIds.value.length > 0) {
    var importData = {
      productId: productInfo.value.productId,
      productName: productInfo.value.productName,
      templateIds: templateIds.value
    }
    importModel(importData).then((response) => {
      ElMessage.success(response.msg)
      openSelect.value = false
      productSelectTemplateRef.value?.selectTemplateTable.clearSelection()
      getList()
      emit('updateModel')
    })
  }
}

const containsUnderscore = (value) => {
  // 使用正则表达式检查值中是否包含下划线
  return /_/.test(value)
}

/** 提交按钮 */
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      // 验证对象或对象数组中的参数不能为空
      if (
        form.datatype == 'object' ||
        (form.datatype == 'array' && form.specs.arrayType == 'object')
      ) {
        if (!form.specs.params || form.specs.params == 0) {
          ElMessage.error(t('product.product-things-model142341-102'))
          return
        }
        if (containsUnderscore(form.identifier)) {
          ElMessage.error(t('product.product-things-model142341-103'))
          return
        }
      }
      // 验证对象参数标识符不能相同
      if (form.specs.params && form.specs.params.length > 0) {
        let arr = form.specs.params.map((item) => item.id).sort()
        for (let i = 0; i < arr.length; i++) {
          if (arr[i] == arr[i + 1]) {
            ElMessage.error('参数标识 ' + arr[i] + ' 重复')
            return
          }
        }
      }
      //验证模型特性为图表展示时，数据类型是否为整数或者小数
      if (
        form.isChart == 1 &&
        form.datatype != 'integer' &&
        form.isChart == 1 &&
        form.datatype != 'decimal'
      ) {
        ElMessage.error(t('product.product-things-model142341-106'))
      } else if (form.modelId != null) {
        // 格式化specs
        let tempForm = JSON.parse(JSON.stringify(form))
        tempForm.specs = formatThingsSpecs()
        if (form.type == 2) {
          tempForm.isMonitor = 0
          tempForm.isChart = 0
        } else if (form.type == 3) {
          tempForm.isMonitor = 0
          tempForm.isChart = 0
        }
        updateModel(tempForm).then((response) => {
          ElMessage.success(t('product.product-things-model142341-107'))
          open.value = false
          getList()
          emit('updateModel')
        })
      } else {
        // 格式化specs
        let tempForm = JSON.parse(JSON.stringify(form))
        tempForm.specs = formatThingsSpecs()
        tempForm.productId = productInfo.value.productId
        tempForm.productName = productInfo.value.productName
        if (form.type == 2) {
          tempForm.isMonitor = 0
        } else if (form.type == 3) {
          tempForm.isMonitor = 0
          tempForm.isChart = 0
        }
        addModel(tempForm).then((response) => {
          ElMessage.success(t('product.product-things-model142341-108'))
          open.value = false
          getList()
          emit('updateModel')
        })
      }
    }
  })
}

/** 删除按钮操作 */
const handleDelete = (row) => {
  const modelIds = row.modelId
  if (!queryParams.isModbus) {
    ElMessageBox.confirm(t('product.product-things-model142341-109', modelIds))
      .then(function () {
        delModel(modelIds).then(() => {
          emit('updateModel')
        })
      })
      .then(() => {
        getList()
        ElMessage.success(t('product.product-things-model142341-111'))
      })
      .catch(() => {})
  } else {
    ElMessage.alert('采集点删除请在采集点模板修改')
  }
}

/** 导出按钮操作 */
const handleExport = () => {
  download(
    'iot/model/export',
    {
      ...queryParams
    },
    `model_${new Date().getTime()}.xlsx`
  )
}

// 类型改变
const typeChange = (type) => {
  if (type == 1) {
    form.isChart = 1
    form.isHistory = 1
    form.isSharePerm = 1
    form.isMonitor = 1
    form.isReadonly = 1
    form.datatype = 'integer'
  } else if (type == 2) {
    form.isChart = 0
    form.isHistory = 1
    form.isSharePerm = 1
    form.isMonitor = 0
    form.isReadonly = 0
  } else if (type == 3) {
    form.isChart = 0
    form.isHistory = 1
    form.isSharePerm = 0
    form.isMonitor = 0
    form.isReadonly = 1
  }
}

// 是否图表展示改变
const isChartChange = () => {
  if (form.isChart == 1) {
    form.isReadonly = 1
  } else {
    form.isMonitor = 0
  }
}

// 是否实时监测改变
const isMonitorChange = () => {
  if (form.isMonitor == 1) {
    form.isReadonly = 1
    form.isChart = 1
  }
}

// 是否只读数据改变
const isReadonlyChange = () => {
  if (form.isReadonly == 0) {
    form.isMonitor = 0
    form.isChart = 0
  }
}

// 格式化物模型
const formatThingsSpecs = () => {
  var data = {}
  data.type = form.datatype
  if (form.datatype == 'integer' || form.datatype == 'decimal') {
    data.min = Number(form.specs.min ? form.specs.min : 0)
    data.max = Number(form.specs.max ? form.specs.max : 100)
    data.unit = form.specs.unit ? form.specs.unit : ''
    data.step = Number(form.specs.step ? form.specs.step : 1)
  } else if (form.datatype == 'string') {
    data.maxLength = Number(form.specs.maxLength ? form.specs.maxLength : 1024)
  } else if (form.datatype == 'bool') {
    data.falseText = form.specs.falseText ? form.specs.falseText : t('close')
    data.trueText = form.specs.trueText ? form.specs.trueText : t('open')
  } else if (form.datatype == 'enum') {
    data.showWay = form.specs.showWay
    if (form.specs.enumList && form.specs.enumList[0].text != '') {
      data.enumList = form.specs.enumList
    } else {
      data.showWay = 'select'
      data.enumList = [
        {
          value: '0',
          text: t('product.product-things-model142341-115')
        },
        {
          value: '1',
          text: t('product.product-things-model142341-116')
        }
      ]
    }
  } else if (form.datatype == 'array') {
    data.arrayType = form.specs.arrayType
    data.arrayCount = form.specs.arrayCount ? form.specs.arrayCount : 5
    if (data.arrayType == 'object') {
      data.params = form.specs.params
      // 物模型名称作为参数的标识符前缀
      for (let i = 0; i < data.params.length; i++) {
        data.params[i].id = form.identifier + '_' + data.params[i].id
      }
    }
  } else if (form.datatype == 'object') {
    data.params = form.specs.params
    // 物模型名称作为参数的标识符前缀
    for (let i = 0; i < data.params.length; i++) {
      data.params[i].id = form.identifier + '_' + data.params[i].id
    }
  }
  return JSON.stringify(data)
}

/** 数据类型改变 */
const dataTypeChange = (val) => {}

/** 添加枚举项 */
const addEnumItem = () => {
  form.specs.enumList.push({
    value: '',
    text: ''
  })
}

/** 删除枚举项 */
const removeEnumItem = (index) => {
  form.specs.enumList.splice(index, 1)
}

/** 格式化显示数据定义 */
const formatSpecsDisplay = (json) => {
  let specs = JSON.parse(json)
  if (
    specs.type === 'integer' ||
    specs.type === 'decimal' ||
    specs.type === 'INT16' ||
    specs.type === 'INT'
  ) {
    return (
      `<span style=\'width:50%;display:inline-block;\'>${t('product.product-things-model142341-117')}<span style="color:#F56C6C">` +
      specs.max +
      `</span></span>${t('product.product-things-model142341-118')}<span style="color:#F56C6C">` +
      specs.min +
      `</span><br /><span style=\'width:50%;display:inline-block;\'>${t('product.product-things-model142341-119')}<span style="color:#F56C6C">` +
      specs.step +
      `</span></span>${t('product.product-things-model142341-120')}<span style="color:#F56C6C">` +
      specs.unit
    )
  } else if (specs.type === 'string') {
    return (
      `${t('product.product-things-model142341-121')}<span style="color:#F56C6C">` +
      specs.maxLength +
      '</span>'
    )
  } else if (specs.type === 'array') {
    return (
      `<span style=\'width:50%;display:inline-block;\'>${t('product.product-things-model142341-122')}<span style="color:#F56C6C">` +
      specs.arrayType +
      `</span></span>${t('product.product-things-model142341-123')}<span style="color:#F56C6C">` +
      specs.arrayCount
    )
  } else if (specs.type === 'enum') {
    let items = ''
    for (let i = 0; i < specs.enumList.length; i++) {
      items =
        items +
        "<span style='width:50%;display:inline-block;'>" +
        specs.enumList[i].value +
        "：<span style='color:#F56C6C'>" +
        specs.enumList[i].text +
        '</span></span>'
      if (i > 0 && i % 2 != 0) {
        items = items + '<br />'
      }
    }
    return items
  } else if (specs.type === 'bool') {
    return (
      '<span style=\'width:50%;display:inline-block;\'>0：<span style="color:#F56C6C">' +
      specs.falseText +
      '</span></span>1：<span style="color:#F56C6C">' +
      specs.trueText
    )
  } else if (specs.type === 'object') {
    let items = ''
    for (let i = 0; i < specs.params.length; i++) {
      items =
        items +
        "<span style='width:50%;display:inline-block;'>" +
        specs.params[i].name +
        "：<span style='color:#F56C6C'>" +
        specs.params[i].datatype.type +
        '</span></span>'
      if (i > 0 && i % 2 != 0) {
        items = items + '<br />'
      }
    }
    return items
  }
}

/** 添加参数 */
const addParameter = () => {
  paramData.index = -1
  paramData.parameter = {}
}

/** 编辑参数*/
const editParameter = (data, index) => {
  paramData.index = index
  paramData.parameter = data
}

/** 删除动作 */
const removeParameter = (index) => {
  form.specs.params.splice(index, 1)
}

/**获取设置的参数对象*/
const getParamData = (data) => {
  if (data.index == -1) {
    form.specs.params.push(data.parameter)
  } else {
    form.specs.params[data.index] = data.parameter
    // Vue 3 中不需要特殊处理，响应式系统会自动检测数组变化
  }
}

const handleImport = () => {
  // this.$refs.importBatchRef.upload.importDeviceDialog = true;
}
</script>

<style lang="scss" scoped>
.specsColor {
  background-color: #fcfcfc;
}

.pagination-container {
  ::v-deep .el-pagination--small .el-pager li:last-child {
    line-height: 28px;
    height: auto;
  }
}
</style>
