<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备编号" prop="deviceCode">
        <el-input
          v-model="queryParams.deviceCode"
          placeholder="请输入设备编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备名称" prop="deviceName">
        <el-input
          v-model="queryParams.deviceName"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备类型" prop="networkingMode">
        <el-select v-model="queryParams.deviceType" placeholder="请选择设备类型" clearable>
          <el-option
            v-for="dict in dict.type.hw_device_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属场景" prop="sceneId">
        <el-select v-model="queryParams.sceneId" placeholder="请选择"  @input="sceneChange">
          <el-option
            v-for="(scene, index) in scenes"
            :key="index"
            :label="scene.sceneName"
            :value="scene.sceneId"
          ></el-option>
        </el-select>

      </el-form-item>
      <el-form-item label="监控单元" prop="monitorUnitId">
        <treeselect v-model="queryParams.monitorUnitId" :options="editedMonitorUnits" :show-count="true"
                    placeholder="请选择所属监控单元" :normalizer="normalizer" :flat="true" clearable style="width: 200px;"/>

      </el-form-item>

      <el-form-item label="设备模型" prop="deviceModeId">
        <el-select v-model="queryParams.deviceModeId" placeholder="请选择" clearable>
          <el-option
            v-for="(editedDeviceMode, index) in editedDeviceModes"
            :key="index"
            :label="editedDeviceMode.deviceModeName"
            :value="editedDeviceMode.deviceModeId"
          ></el-option>
        </el-select>

      </el-form-item>


      <el-form-item label="激活状态" prop="activeStatus">
        <el-select v-model="queryParams.activeStatus" placeholder="请选择" clearable>
          <el-option
            v-for="dict in dict.type.hw_device_active_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="设备状态" prop="deviceStatus">
        <el-select v-model="queryParams.deviceStatus" placeholder="请选择" clearable>
          <el-option
            v-for="dict in dict.type.hw_device_device_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <!--el-form-item label="在线状态" prop="onlineStatus">
        <el-select v-model="queryParams.onlineStatus" placeholder="请选择" clearable>
          <el-option
            v-for="dict in dict.type.hw_device_online_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item-->



      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:device:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:device:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="设备编号" align="center" prop="deviceCode"/>
      <el-table-column label="设备名称" align="center" prop="deviceName"/>
      <el-table-column label="设备类型" align="center" prop="deviceType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.hw_device_type" :value="scope.row.deviceType"/>
        </template>
      </el-table-column>

      <el-table-column label="所属租户" align="center" prop="tenantName"/>
      <el-table-column label="所属场景" align="center" prop="sceneName"/>
      <el-table-column label="监控单元" align="center" prop="monitorUnitName"/>
      <el-table-column label="设备模型" align="center" prop="deviceModeName"/>
      <!--el-table-column label="激活状态" align="center" prop="activeStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.hw_device_active_status" :value="scope.row.activeStatus"/>
        </template>
      </el-table-column-->
      <!--el-table-column label="设备激活时间" align="center" prop="activeTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.activeTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column-->
      <el-table-column label="设备状态" align="center" prop="deviceStatus">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.deviceStatus"
            active-value="1"
            inactive-value="0"
            @change="handleDeviceStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>

      <!--el-table-column label="在线状态" align="center" prop="onlineStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.hw_device_online_status" :value="scope.row.onlineStatus"/>
        </template>
      </el-table-column-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:device:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:device:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.slimitnc="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备编号" prop="deviceCode">
          <el-input v-model="form.deviceCode" placeholder="请输入设备编号" maxlength="20"/>
        </el-form-item>
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="form.deviceName" placeholder="请输入设备名称"/>
        </el-form-item>
        <el-form-item label="设备类型" prop="networkingMode">
          <el-select v-model="form.deviceType" placeholder="请选择设备类型" @input="deviceTypeChange" :disabled="deviceTypeDisabled">
            <el-option
              v-for="dict in dict.type.hw_device_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="所属场景" prop="sceneId">
          <el-select v-model="form.sceneId" placeholder="请选择" @input="sceneChange" :disabled="sceneDisabled">
            <el-option
              v-for="(scene, index) in editedScenes"
              :key="index"
              :label="scene.sceneName"
              :value="scene.sceneId"
              :disabled="scene.selectedDisable && scene.selectedDisable == 1"
            ></el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="监控单元" prop="monitorUnitId">
          <treeselect v-model="form.monitorUnitId" :options="editedMonitorUnits" :show-count="true"
                      placeholder="请选择所属监控单元" :normalizer="normalizer" :flat="true"/>
        </el-form-item>


        <el-form-item label="联网方式" prop="networkingMode" v-if="deviceVisible">
          <el-select v-model="form.networkingMode" placeholder="请选择数据类型">
            <el-option
              v-for="dict in dict.type.hw_device_networking_mode"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="接入协议" prop="accessProtocol" v-if="deviceVisible">
          <el-select v-model="form.accessProtocol" placeholder="请选择接入协议">
            <el-option
              v-for="dict in dict.type.hw_device_access_protocol"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="数据格式" prop="dataFormat" v-if="deviceVisible">
          <el-select v-model="form.accessProtocol" placeholder="请选择数据格式">
            <el-option
              v-for="dict in dict.type.hw_device_data_format"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="关联网关" prop="releatedDeviceId" v-if="subDeviceVisible">
          <el-select v-model="form.releatedDeviceId" placeholder="请选择">
            <el-option
              v-for="(editedGatewayDevice, index) in editedGatewayDevices"
              :key="index"
              :label="editedGatewayDevice.deviceName"
              :value="editedGatewayDevice.deviceId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备模型" prop="deviceModeId" v-if="subDeviceVisible">
          <el-select v-model="form.deviceModeId" placeholder="请选择">
            <el-option
              v-for="(editedDeviceMode, index) in editedDeviceModes"
              :key="index"
              :label="editedDeviceMode.deviceModeName"
              :value="editedDeviceMode.deviceModeId"
            ></el-option>
          </el-select>

        </el-form-item>

        <el-form-item label="描述" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>

        <el-form-item label="设备图片" prop="devicePic">
          <el-upload
            single
            :action="uploadImgUrl"
            list-type="picture-card"
            :limit="limit"
            :on-success="handleUploadSuccess"
            :before-upload="handleBeforeUpload"
            :on-error="handleUploadError"
            :on-exceed="handleExceed"
            ref="imageUpload"
            :on-remove="handleDeletePicture"
            :show-file-list="true"
            :headers="headers"
            :file-list="fileList"
            :on-preview="handlePictureCardPreview"
            :class="{hide: this.fileList.length >= 1}"
          >
            <i class="el-icon-plus"></i>
          </el-upload>

          <!-- 上传提示 -->
          <div class="el-upload__tip" slot="tip" v-if="showTip">
            请上传
            <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b></template>
            <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b></template>
            的文件
          </div>

          <el-dialog
            :visible.sync="dialogVisible"
            title="预览"
            width="800"
            append-to-body
          >
            <img
              :src="dialogImageUrl"
              style="display: block; max-width: 100%; margin: 0 auto"
            />
          </el-dialog>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="confirmBtnVisible">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listDevice,
  getDevice,
  delDevice,
  addDevice,
  updateDevice,
  getScenes,
  getEditedScenes,
  getMonitorTree,
  getDeviceModes,
  getGatewayDevices,
  changeDeviceStatus
} from "@/api/business/device";
import {getToken} from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  components: {Treeselect},
  dicts: ['hw_device_type', 'hw_device_networking_mode', 'hw_device_access_protocol', 'hw_device_data_format', 'hw_device_active_status', 'hw_device_device_status', 'hw_device_online_status'],
  name: "Device",
  props: {
    value: [String, Object, Array],
    // 图片数量限制
    limit: {
      type: Number,
      default: 1,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["png", "jpg", "jpeg"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    }
  },

  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备信息表格数据
      deviceList: [],
      //场景列表
      scenes: [],
      //编辑页面场景列表
      editedScenes:[],
      //编辑页面监控单元树
      editedMonitorUnits: undefined,
      //编辑页面设备模型列表
      editedDeviceModes: [],
      //编辑页面网关设备列表
      editedGatewayDevices: [],
      deviceTypeDisabled:true,
      sceneDisabled:true,
      subDeviceVisible: false,//子设备字段是否显示
      deviceVisible: false,//网关设备或直连设备字段是否显示

      DEVICE_TYPE_GATEWAY_DEVICE: "1",//网关设备
      DEVICE_TYPE_GATEWAY_SUB_EQUIPMENT: "2",//网关子设备
      DEVICE_TYPE_DIRECT_CONNECT_DEVICE: "3",//直连设备

      DEVICE_ACCESS_PROTOCOL_MQTT: 1,//网关接入协议,MQTT

      DEVICE_NETWORKING_MODE_WIFI: "1",// 网关接入协议：WIFI

      DEVICE_DATA_FORMAT_JSON: 1,// 数据格式：JSON

      DEVICE_STATUS_PUBLISHED: "1",//设备状态:已发布
      ACTIVE_STATUS_INACTIVE: "0",//激活状态：未激活

      confirmBtnVisible : true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceCode: null,
        deviceName: null,
        sceneId: null,
        monitorUnitId: null,
        deviceType: null,
        networkingMode: null,
        accessProtocol: null,
        dataFormat: null,
        releatedDeviceId: null,
        deviceModeId: null,
        accessGwProtocol: null,
        activeStatus: null,
        deviceStatus: null,
        activeTime: null,
        devicePic: null,
        ipAddress: null,
        areaId: null,
        deviceLocation: null,
        tenantId: null,
        onlineStatus: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deviceCode: [
          {required: true, message: "设备编号不能为空", trigger: "blur"},
          {
            pattern: /^[a-z][a-z0-9_]+$/,
            message: "2-20个字符，由小写字母、数字或下划线组成，开头必须为小写字母",
            trigger: "blur"
          }
        ],
        deviceName: [
          {required: true, message: "设备名称不能为空", trigger: "blur"}
        ],
        sceneId: [
          {required: true, message: "所属场景不能为空", trigger: "change"}
        ],
        deviceType: [
          {required: true, message: "设备类型不能为空", trigger: "change"}
        ],
        monitorUnitId: [
          {required: true, message: "监控单元不能为空", trigger: "change"}
        ],
      },
      number: 0,
      uploadList: [],
      dialogImageUrl: "",
      dialogVisible: false,
      hideUpload: false,
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/file/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: [],
    };
  },
  created() {
    this.getList();
    getScenes().then(response => {
      this.scenes = response.data;
    });

    //获取文件最大size
    this.getConfigKey("hw.file.maxsize").then(response => {//获取经度标识符
      this.fileSize = response.msg;
    });
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
    formatRow() {
      return (row) => {
        // let languages = this.languages;
        // for (let i = 0; i < languages.length; i++) {
        //   if (languages[i].languageCode === row.languageCode) {
        //     return languages[i].languageName;
        //   }
        // }
      };
    },
  },
  methods: {
    /** 查询设备信息列表 */
    getList() {
      this.loading = true;
      listDevice(this.queryParams).then(response => {
        this.deviceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.subDeviceVisible = true;
      this.deviceVisible = false;
      this.form = {
        deviceId: null,
        deviceCode: null,
        deviceName: null,
        sceneId: null,
        monitorUnitId: null,
        deviceType: "2",
        networkingMode: null,
        accessProtocol: null,
        dataFormat: null,
        releatedDeviceId: null,
        deviceModeId: null,
        accessGwProtocol: null,
        activeStatus: null,
        deviceStatus: null,
        activeTime: null,
        devicePic: null,
        ipAddress: null,
        areaId: null,
        deviceLocation: null,
        currentModuleVersion: null,
        currentSinglechipVersion: null,
        remark: null,
        tenantId: null,
        onlineStatus: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.deviceId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      getEditedScenes().then(response => {
        this.editedScenes = response.data;
      });
      this.deviceTypeDisabled = false;
      this.sceneDisabled = false;
      this.fileList = [];
      this.reset();
      this.open = true;
      this.title = "添加设备信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      getEditedScenes().then(response => {
        this.editedScenes = response.data;
      });
      this.deviceTypeDisabled = true;
      this.sceneDisabled = true;
      this.reset();
      this.fileList = [];
      const deviceId = row.deviceId || this.ids
      getDevice(deviceId).then(response => {
        if(response.data.deviceStatus===this.DEVICE_STATUS_PUBLISHED){
          this.confirmBtnVisible = false;
        }

        if (response.data.devicePic != null) {
          let previewFile = {};
          previewFile.url = response.data.devicePic
          this.fileList.push(previewFile);
        }

        this.getEditedMonitorTree(response.data.sceneId);
        if (response.data.deviceType === this.DEVICE_TYPE_GATEWAY_DEVICE
          || response.data.deviceType === this.DEVICE_TYPE_DIRECT_CONNECT_DEVICE) {
          this.subDeviceVisible = false;
          this.deviceVisible = true;
        } else {
          this.subDeviceVisible = true;
          this.deviceVisible = false;
          this.getEditedDeviceModes(response.data.sceneId);
          this.getGatewayDevices(response.data.sceneId);
        }
        this.form = response.data;
        this.open = true;
        this.title = "修改设备信息";
      });
    },


    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.deviceType === this.DEVICE_TYPE_GATEWAY_DEVICE || this.form.deviceType === this.DEVICE_TYPE_DIRECT_CONNECT_DEVICE) {
            // if(this.form.net)
            // networkingMode: [
            //   {required: true, message: "联网方式(1:Wi-Fi，2、蜂窝(2G/3G/4G/5G),3、以太网，4、其他)不能为空", trigger: "blur"}
            // ],
            //   accessProtocol: [
            //   {required: true, message: "接入协议不能为空", trigger: "blur"}
            // ],
            //   dataFormat: [
            //   {required: true, message: "数据格式不能为空", trigger: "blur"}
            // ],
          } else {
            if (this.form.releatedDeviceId === null || this.form.releatedDeviceId === undefined
              || this.form.releatedDeviceId === '') {
              this.$modal.msgWarning("请选择关联网关");
              return;
            }
            if (this.form.deviceModeId === null || this.form.deviceModeId === undefined
              || this.form.deviceModeId === '') {
              this.$modal.msgWarning("请选择设备模型");
              return;
            }
          }


          if (this.form.deviceId != null) {
            updateDevice(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDevice(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const deviceIds = row.deviceId || this.ids;
      this.$modal.confirm('是否确认删除设备信息编号为"' + deviceIds + '"的数据项？').then(function () {
        return delDevice(deviceIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/device/export', {
        ...this.queryParams
      }, `device_${new Date().getTime()}.xlsx`)
    },


    /**上传图片处理*/
    // 上传前loading加载
    handleBeforeUpload(file) {
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = this.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }

      if (!isImg) {
        this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`);
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传图片，请稍候...");
      this.number++;
    },

    checkPicture(file) {

    },

    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} !`);
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        this.uploadList.push(res.data.url);
        this.uploadedSuccessfully();
      } else {
        this.number--;
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.imageUpload.handleRemove(file);
        this.uploadedSuccessfully();
      }
    },
    // 上传结束处理
    uploadedSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.fileList = this.fileList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.form.devicePic = this.fileList[0];
        // this.$emit("input", this.listToString(this.fileList));
        this.$modal.closeLoading();
      }
    },

    // 删除图片
    handleDeletePicture(file) {
      const findex = this.fileList.map(f => f.name).indexOf(file.name);
      if (findex > -1) {
        this.fileList.splice(findex, 1);
        // this.$emit("input", this.listToString(this.fileList));
      }
      this.form.devicePic = '';
    },
    // 上传失败
    handleUploadError() {
      this.$modal.msgError("上传图片失败，请重试");
      this.$modal.closeLoading();
    },

    // 预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        if (list[i].url) {
          strs += list[i].url.replace(this.baseUrl, "") + separator;
        }
      }
      return strs != '' ? strs.substr(0, strs.length - 1) : '';
    },

    getEditedMonitorTree(sceneId) {
      getMonitorTree(sceneId).then(response => {
        this.editedMonitorUnits = response.data;
      });
    },

    getEditedDeviceModes(sceneId) {
      getDeviceModes(sceneId).then(response => {
        this.editedDeviceModes = response.data;
      });
    },

    getGatewayDevices(sceneId) {
      getGatewayDevices(sceneId).then(response => {
        this.editedGatewayDevices = response.data;
      });
    },

    sceneChange(sceneId) {
      this.form.monitorUnitId = null;
      this.queryParams.monitorUnitId = null;
      this.form.deivceModeId = null;
      this.queryParams.deviceModeId = null;
      this.getEditedMonitorTree(sceneId);
      this.getEditedDeviceModes(sceneId);
      this.getGatewayDevices(sceneId);
    },

    deviceTypeChange(deviceType) {
      if (deviceType === this.DEVICE_TYPE_GATEWAY_DEVICE || deviceType === this.DEVICE_TYPE_DIRECT_CONNECT_DEVICE) {
        this.form.releatedDeviceId = null;
        this.form.deviceModeId = null;
        this.form.accessProtocol = this.DEVICE_ACCESS_PROTOCOL_MQTT;
        this.form.networkingMode = this.DEVICE_NETWORKING_MODE_WIFI;
        this.form.dataFormat = this.DEVICE_DATA_FORMAT_JSON;
        this.deviceVisible = true;
        this.subDeviceVisible = false;
      } else {
        this.form.networkingMode = null;
        this.form.accessProtocol = null;
        this.form.dataFormat = null;
        this.subDeviceVisible = true;
        this.deviceVisible = false;
      }
    },

    monitorUnitSelect(node) {
      if (node.children !== undefined) {
        this.form.monitorUnitId = null;
        this.$modal.msgWarning("请选择子级监控单元");
      }
    },

    normalizer(node) {
      return {
        id: node.id,
        label: node.label,
        children: node.children,
        isDisabled: node.children !== undefined
      };

      // if (!node.children) {
      //   return {
      //     id: node.monitorUnitId,
      //     label: node.monitorUnitName
      //   };
      // }

    },

    // 设备状态修改
    handleDeviceStatusChange(row) {
      // if(row.deviceStatus==='1' && row.activeStatus === '0'){
      //   this.$modal.msgSuccess("激活后才能修改为发布状态");
      //   row.deviceStatus = row.deviceStatus === "0" ? "1" : "0";
      //   return;
      // }
      let text = row.deviceStatus === "0" ? "测试" : "发布";
      this.$modal.confirm('确认要改为'+text+'状态吗？').then(function () {
        return changeDeviceStatus(row.deviceId, row.deviceStatus);
      }).then(() => {
        this.$modal.msgSuccess("修改状态成功");
      }).catch(function () {
        row.deviceStatus = row.deviceStatus === "0" ? "1" : "0";
      });
    },
  }
};
</script>
