<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item prop="deviceType">
          <el-select v-model="queryParams.deviceType" placeholder="设备类型" clearable style="width: 100%;">
            <el-option
              v-for="dict in dict.type.sys_device_type"
              v-if = "dict.value != 'shx'"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item  prop="deviceName">
          <el-input
            v-model="queryParams.deviceName"
            placeholder="请输入设备名称"
            clearable
            @keyup.enter.native="handleQuery"
            maxlength="20"
          />
        </el-form-item>
        <el-form-item  prop="deviceCode">
          <el-input
            v-model="queryParams.deviceCode"
            placeholder="请输入设备编码"
            clearable
            @keyup.enter.native="handleQuery"
            maxlength="20"
          />
        </el-form-item>
        <el-form-item prop="deviceStatus">
            <el-select v-model="queryParams.deviceStatus" placeholder="设备状态" clearable style="width: 100%;">
                <el-option
                v-for="dict in dict.type.sys_device_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
                />
                </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="['basic: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="['basic:device:export']"
          >导出数据</el-button>
        </el-col>
        <el-col :span="1.5">
          <!-- 二维码导出组件按钮在内部传选中数组 currentSelection:选中数组 clearCheck:清空选中状态-->
         <qrCodeUpload :checkboxModel.sync="currentSelection" @clearCheck="clearCheck"/>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
  
      <el-table v-loading="loading" :data="tableData" ref="multipleTable" row-key="deviceCode" @selection-change="handleSelectionChange" @select="handlerSelect" @select-all="handlerSelectAll">
        <el-table-column type="selection" width="55" align="center" :reserve-selection="true" />
        <el-table-column label="序号" align="center" width="80" type="index">
        <template slot-scope="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
        <el-table-column label="设备id" align="center" prop="deviceId" v-if="false" />
        <el-table-column label="设备类型" align="center" prop="deviceTypeName" sortable/>
          <!-- <template slot-scope="scope">
              <div>{{ dict.type.sys_device_type[(scope.row.deviceType)].label }}</div>
          </template>
        </el-table-column> -->
        <el-table-column label="设备名称" align="center" prop="deviceName" />
        <el-table-column label="设备编号" align="center" prop="deviceCode"  sortable/>
        <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="labelUploadCode(scope.row)"
              v-hasPermi="['basic:device:query']"
            >查看</el-button>
          </template>
        </el-table-column>
        <el-table-column label="设备状态" align="center" prop="deviceStatus" >
          <template slot-scope="scope">
              <div v-if="scope.row.deviceStatus==0" style="color: green;">{{ dict.type.sys_device_status[Number(scope.row.deviceStatus)].label }}</div>
              <div v-if="scope.row.deviceStatus==1" style="color: red;">{{ dict.type.sys_device_status[Number(scope.row.deviceStatus)].label }}</div>
          </template>
        </el-table-column>
        <el-table-column label="设备使用人" align="center" prop="lyName" />
        <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="['basic:device:edit']"
            >编辑</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-circle-plus-outline"
              @click="openDeviceAttribute(scope.row)"
              v-hasPermi="['basic:bracelet:edit']"
            >设备属性</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['basic:device:del']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加或修改设备对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="600px"   append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="100px" >
                    <el-form-item label="设备类型" prop="devcieType" >
                        <el-select v-if="flag == true" v-model="form.deviceType" placeholder="请选择设备类型" clearable style="width: 100%;" disabled>
                         <el-option
                           v-for="dict in dict.type.sys_device_type"
                           v-if = "dict.value != 'shx'"
                           :key="dict.value"
                           :label="dict.label"
                           :value="dict.value"
                             />
                         </el-select>
                         <el-select v-else v-model="form.deviceType" placeholder="请选择设备类型" clearable style="width: 100%;">
                          <el-option
                            v-for="dict in dict.type.sys_device_type"
                            v-if = "dict.value != 'shx'"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                              />
                          </el-select>
                    </el-form-item>
                    <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="请输入设备名称" maxlength="20"/>
                    </el-form-item>
                    <el-form-item label="设备下标" prop="deviceIndex">
                        <el-input v-model="form.deviceIndex" placeholder="请输入设备下标" maxlength="5"/>
                    </el-form-item>               
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>

        <!-- 查看设备属性弹窗 -->
        <el-dialog :title="title" :visible.sync="showDeviceAttribute" width="1200px" height="1000px" append-to-body>
          <el-form :model="queryDeviceAttribute" ref="queryFormDeviceAttribute" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item  prop="dataCode">
          <el-input
            v-model="queryDeviceAttribute.dataCode"
            placeholder="请输入级联编码"
            clearable
            @keyup.enter.native="handleQueryDeviceAttribute"
            maxlength="20"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryDeviceAttribute">查询</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="handleAddAttribute"
            v-hasPermi="['basic:person:add']"
          >新增设备属性</el-button>
        </el-col>
      </el-row>

      <el-table v-loading="loadingTwo" :data="deviceAttributeList " width="600px" height = "600px" >
        <el-table-column label="序号" align="center" width="80" type="index">
        <template slot-scope="scope">
          <span>{{ (queryDeviceAttribute.pageNum - 1) * queryDeviceAttribute.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
        <el-table-column label="设备id" align="center" prop="id" v-if="false" />
        <el-table-column label="设备属性名称" align="center" prop="dataName" sortable/>
        <el-table-column label="设备采集值" align="center" prop="dataVal" sortable/>
        <el-table-column label="设备值单位" align="center" prop="dataUnit" sortable/>
        <el-table-column label="级联编码" align="center" prop="dataCode" sortable/>
        <el-table-column label="数据类型" align="center" prop="dataType" sortable/>
        <el-table-column label="数据采集时间" align="center" prop="dataTime" width="160px"sortable/>
        <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="openImg(scope.row.base64Url)"
              v-hasPermi="['basic:constructionRecord:edit']"
            >查看</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="140px" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdateAttribute(scope.row)"
              v-hasPermi="['basic:device:edit']"
            >编辑</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDeleteDeviceAttribute(scope.row)"
              v-hasPermi="['basic:device:del']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <pagination
        v-show="totalTwo>0"
        :total="totalTwo"
        :page.sync="queryDeviceAttribute.pageNum"
        :limit.sync="queryDeviceAttribute.pageSize"
        @pagination="getListDeviceAttribute"
      />
      </el-dialog>


        <!-- 新增或修改设备属性弹窗 -->
        <el-dialog :title="title" :visible.sync="showAttribute" width="600px"   append-to-body>
        <el-form ref="formThree" :model="formThree" :rules="rulesShAttribute" label-width="120px" >
          <el-row :gutter="24">
            <el-col :span="20">
                    <el-form-item label="设备属性名称" prop="dataName">
                      <el-input v-model="formThree.dataName" placeholder="请输入设备属性名称" maxlength="20"/>
                      </el-form-item>
            </el-col>
        </el-row>
        <!-- <el-row :gutter="24">  
            <el-col :span="20">
                      <el-form-item label="设备采集值" prop="dataVal">
                        <el-input v-model="formThree.dataVal" placeholder="请输入设备采集值" maxlength="20"/>
                      </el-form-item>
             </el-col>
        </el-row> -->
     
          <el-row :gutter="24">
             <el-col :span="20">
                    <el-form-item label="设备值单位" prop="dataUnit">
                        <el-input v-model.number="formThree.dataUnit" placeholder="请输入设备值单位" maxlength="20">
                      </el-input>
                    </el-form-item>      
             </el-col>   
          </el-row>    
          <el-row :gutter="24">  
             <el-col :span="20">
                    <el-form-item label="级联编码" prop="dataCode">
             <el-input v-model.number="formThree.dataCode" placeholder="请输入级联编码" maxlength="20">
                      </el-input>
                    </el-form-item>      
             </el-col> 
           </el-row>  
           <el-row :gutter="24">  
             <el-col :span="20">
                    <el-form-item label="数据类型" prop="dataType">
             <el-input v-model.number="formThree.dataType" placeholder="请输入数据类型" maxlength="20">
                      </el-input>
                    </el-form-item>      
             </el-col> 
           </el-row> 
           <!-- <el-row :gutter="24">  
             <el-col :span="20">
                    <el-form-item label="数据采集时间" prop="dataTime">
              <el-date-picker
                  placeholder="请选择数据采集日期"
                  v-model="formThree.dataTime"
                  style="width: 345px"
                  value-format="yyyy-MM-dd"
                  type="date">
              </el-date-picker>
                    </el-form-item>      
             </el-col> 
           </el-row>  -->
           <el-row :gutter="24">  
             <el-col :span="20">
              <el-form-item label="图标 " label-width="120px">
          <el-upload
                action="#"
                :limit="1"
                :file-list="fileList"
                :show-file-list="true"
                :auto-upload="false"
                list-type="picture-card"
                accept=".png, .jpg, .jpeg"
                :on-change="handleChange"
                :class="{ disabled: uploadDisabled }"
                :on-preview="picturePreview"
                :on-remove="handleRemove"
            >
                <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
        </el-form-item>
             </el-col> 
           </el-row> 
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFormAttribute">确 定</el-button>
          <el-button @click="cancelAttribute">取 消</el-button>
        </div>
      </el-dialog>

        <!-- 标签下载对话框 -->
        <el-dialog
            :title="title"
            :visible.sync="uploadOpen"
            width="450px"
            append-to-body
            :close-on-click-modal="false"
        >
            <div style="text-align: center" ref="codeBox">
                <div class="uploadImg">
                    <div id="qrcode" class="qrcode" ref="codeItem"></div>
                    <!--        <img src="" alt="">-->
                </div>
                <div class="deviceCode">设备编号：{{ rowObj.deviceCode }}</div>
            </div>
            <div slot="footer" class="dialog-footer" style="text-align: center">
                <el-button type="primary" @click="downloadCode"
                    >下 载</el-button
                >
            </div>
        </el-dialog>

      <!-- 图片查看弹窗 -->
      <el-dialog :visible.sync="dialogVisible">
        <img width="100%" height="650px" :src="dialogImageUrl" alt />
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { listDevcie, addDevice, editDevice, getDeviceInfo,delDevice, exportDevice,exportDeviceSome,addAttribute,listDeviceAttribute,getAttributeInfo,editAttribute,delDeviceAttribute} from "@/api/base/device";
  import { downloadFile } from '@/utils/download'
  import { getToken } from '@/utils/auth'
  import uploadFile from '../../components/uploadFile.vue'
  import qrCodeUpload from '../../components/qrCodeUpload.vue'
  import html2canvas from 'html2canvas'
  import QRCode from 'qrcodejs2'
  import JSZip from 'jszip'
  import FileSaver from 'file-saver'
  import C from "highlight.js/lib/languages/1c";
  export default {
    name: "Post",
    dicts: ['sys_normal_disable','sys_device_type','sys_device_status'],
    components: {
			uploadFile,qrCodeUpload
		},
    data() {
      return {
        showAttribute:false,
        showDeviceAttribute:false,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        //绑定设备总条数
        totalTwo:0,
        //未绑定设备总条数
        totalThree:0,
        // 设备表格数据
        tableData: [],
        queckName: "",
        // 弹出层标题
        title: "",
        delFileId: undefined,
        // 是否显示弹出层
        open: false,
        flag: false,
        //所属工程
        proList: [],
        deviceAttributeList : [],
        //状态
        StatusList:[],
        Qrcode:"",
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          deviceType:undefined,
          deviceName:undefined,
          deviceCode: undefined,
          devcieStatus: undefined,
        },
        queryDeviceAttribute: {
          pageNum: 1,
          pageSize: 10,
          deviceId:undefined,
          dataCode:undefined,
        },
        maxLength:100,//已选列表上限，防止数据过多请求报错
        currentSelection:[],//已选列表
        // 表单参数
        form: {},
        formThree: {},
        //图片上传
        fileList: [],
        //图片查看弹窗
        dialogImageUrl: '',
        dialogVisible: false,
        // 表单校验
        rules: {
          deviceType: [
            { required: true, message: "设备类型不能为空", trigger: "change" }
          ],
          deviceCode: [
            { required: true, message: "设备编码不能为空", trigger: "blur" }
          ],
          deviceName: [
            { required: true, message: "设备名称不能为空", trigger: "blur" }
          ],
          deviceIndex: [
            { required: true, message: "设备下标不能为空", trigger: "blur" },
            {
            validator: (rule, value, callback) => {
              if (value === '' || value === null) {
                return callback(new Error('请必须输入0~10内的整数'));
              }
              const numValue = Number(value);
              if (!Number.isInteger(numValue) || numValue < 0 || numValue > 10) {
                callback(new Error('请必须输入0~10内的整数'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
          ]
        },
        rulesShAttribute: {
          dataName: [
            { required: true, message: "设备属性名称不能为空", trigger: "blur" }
          ],
          // dataVal: [
          //   { required: true, message: "设备采集值不能为空", trigger: "blur" }
          // ],
          dataUnit: [
            { required: true, message: "设备值单位不能为空", trigger: "blur" }
          ],
          dataCode: [
            { required: true, message: "级联编码不能为空", trigger: "blur" }
          ],
          dataType: [
            { required: true, message: "数据类型不能为空", trigger: "blur" }
          ],
          // dataTime: [
          //   { required: true, message: "数据采集日期不能为空", trigger: "blur" }
          // ],
        },
        //二维码
        rowObj:{},
        uploadOpen:false,
        deviceCode:'',
      };
    },
    computed: {
        //图片上传1张后，隐藏上传框
        uploadDisabled() {
            return this.fileList.length > 0
        },
    },
    created() {
      this.getList();
      
    },
    mounted(){
      console.log(this.dict.type.sys_device_type)
    },
    methods: {

        //列表-图片查看
        openImg(url) {
        this.dialogImageUrl = url
        this.dialogVisible = true
        },
        //上传组件-图片查看
        picturePreview(file) {
            this.dialogImageUrl = file.url
            this.dialogVisible = true
        },
        // 图片上传
        handleChange(file, fileList) {
                // this.$refs["form"].clearValidate()
            this.formThree.fileName = file.name;
            this.fileList = fileList;
        },
        handleRemove(file, fileList) {
                let sum = 0
                this.fileList.forEach((item, index) => {
                  if(!item?.hasOwnProperty('raw')) {
                    this.delFileId = this.formThree.filePath;
                  }
                  sum = index;
                })
                // this.delFileId = this.fileList[sum].fileId;
                this.fileList.splice(sum, 1)
        },
        //提交时循环fileList 获取raw文件
        getFileData() {
              const file = []
              this.fileList.forEach(item => {
                if (item?.hasOwnProperty('raw')) {
                  file.push(item.raw)
                }
              })
              return { file }
        },

        /** 查询设备列表 */
        getList() {
            this.loading = true;
            listDevcie(this.queryParams).then(response => {
              this.tableData = response.rows;
              this.total = response.total;
              this.loading = false;
              if (this.currentSelection.length) {
                this.$nextTick(() => {
                  this.currentSelection.forEach(row => {
                    this.tableData.forEach(item => {
                      if (item.deviceCode === row) {
                        this.$refs.multipleTable?.toggleRowSelection(item, true)
                      }
                    })
                  })
                })
              } else {
                this.$refs.multipleTable?.clearSelection()
              }
            });
        },

        resetAttribute() {
            this.formThree = {};
            this.resetForm("formThree");
        },

        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {};
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.currentSelection = []//重置清除已选列表
            this.handleQuery();
        },

        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.deviceCode)
            this.single = selection.length!=1
            this.multiple = !selection.length
        },
        //单选操作-跨页
        handlerSelect(val, row) {
          this.currentSelection.indexOf(row.deviceCode) === -1
            ? this.currentSelection.push(row.deviceCode)
            : this.currentSelection.splice(this.currentSelection.indexOf(row.deviceCode), 1)
        },
        //全选操作-跨页
        handlerSelectAll(val) {
          if (val.length) {
            // 进来此处说明:
            // 1 当前页的全选 2 其他页有数据然后当前页的取消全选
            // 比较全选或者取消全选与当前页的数据，得到差集
            // 如果tableData中的数据在val中不存在，则说明是取消全选，需要从currentSelection中移除
            // 如果tableData中所有的数据都在val中存在，则说明是全选，需要将差集添加到currentSelection中
            const isAllSelect = this.tableData.every(item =>
            val.some(valItem => valItem.deviceCode === item.deviceCode)
            )
            if (isAllSelect) {
              // 全选中新增的差集
              const diff = val.filter(
              item => !this.currentSelection.some(deviceCode => deviceCode === item.deviceCode)
            )
            if (this.currentSelection.length + diff.length > this.maxLength) {
                this.currentSelection = this.currentSelection.concat(
                  diff.splice(0, this.maxLength - this.currentSelection.length)
                      .map(item => item.deviceCode))
                diff.forEach(item => this.$refs.multipleTable.toggleRowSelection(item, false))
            } else {
                this.currentSelection = this.currentSelection.concat(diff.map(item => item.deviceCode))
            }
            } else {
                this.currentSelection = this.currentSelection.filter(
                  deviceCode => !this.tableData.some(item => item.deviceCode === deviceCode)
                )
              }
          } else {
            // 进来此处说明:
            // 其他页并无勾选数据，且当前页取消勾选
            this.currentSelection = []
          }
        },
        clearCheck(){
          this.currentSelection = []
          this.getList()
        },
        //二维码查看
        labelUploadCode(row) {
            this.rowObj = row
            this.uploadOpen = true
            this.title = '二维码查看'
            this.deviceCode = row.deviceCode
            let str = row.deviceCode
            this.$nextTick(() => {
                // this.selectionList.forEach((item, index) => {
                this.$refs.codeItem.innerHTML = ''
                var qrcode = new QRCode(this.$refs.codeItem, {
                    text: str, //二维码内容
                    width: 256,
                    height: 256,
                    colorDark: '#000000',
                    colorLight: '#ffffff',
                    correctLevel: QRCode.CorrectLevel.H,
                })

                // });
            }, 500)
        },
        downloadCode(e) {
            if (document.getElementById('qrcode').childNodes[0]) {
                let element = this.$refs.codeBox
                html2canvas(element).then((canvas) => {
                    // 将canvas转换为图片URL
                    const image = canvas.toDataURL('image/png')
                    const alink = document.createElement('a')
                    alink.href = image
                    alink.download = this.deviceCode
                    alink.click()
                })
            }
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.flag = false;
            this.open = true;
            this.title = "添加设备";
        },

        /** 新增设备属性按钮操作 */
        handleAddAttribute() {
          this.fileList = [];
          this.resetAttribute();
          this.formThree.deviceId = this.deviceId;
          this.title = "新增设备属性"
          this.showAttribute = true;
        },

        /** 修改按钮操作 */
        handleUpdateAttribute(row) {
            this.resetAttribute();
            const id = row.id
            this.fileList=[];
            getAttributeInfo({id:id}).then(response => {
              this.formThree = response.data;
              // this.$set(this.form,'sex',response.data.sex+'')
              if(response.data.fileId && response.data.base64Url){
                this.fileList.push({
                  name: response.data.fileId,
                  url: response.data.base64Url,
                })
              }
              //触发校验
              // this.formThree.fileName = response.data.fileId;
              setTimeout(()=>{
                this.showAttribute = true;
                this.title = "修改设备属性";
              },100)
             
            });
        },

        /** 删除按钮操作 */
        handleDeleteDeviceAttribute(row) {
          const id = row.id;
          this.$modal.confirm('是否确认删除级联编码为"' + row.dataCode + '"的数据项？').then(function() {
            return delDeviceAttribute({id:id});
          }).then(() => {
            this.getListDeviceAttribute();
            this.$modal.msgSuccess("删除成功");
          }).catch(() => {});
        },

        /** 手环管理页面新增设备属性提交按钮 */
        submitFormAttribute() { 
            this.$refs["formThree"].validate(valid => {
            if (valid) {
              if (this.formThree.id != undefined) {
                  //base64地址别传后台，过长
                  this.formThree.base64Url = '';
                  this.formThree.delFileId = this.delFileId;
                  const reqData = new FormData()
                  reqData.append('params', JSON.stringify(this.formThree))
                  const { file } = this.getFileData()
                  file.forEach(item => {
                    reqData.append('file', item)
                  })
                  editAttribute(reqData).then(response => {
                    this.$modal.msgSuccess("修改成功");
                    this.showAttribute = false;
                    this.fileList=[];
                    // this.getList();
                    this.getListDeviceAttribute();
                  });
                }else{
                  console.log(this.formThree)
                  const reqData = new FormData()
                  reqData.append('params', JSON.stringify(this.formThree))
                  const { file } = this.getFileData()
                  file.forEach(item => {
                    reqData.append('file', item)
                  })
                  addAttribute(reqData).then(response => {
                    this.$modal.msgSuccess("新增成功");
                    this.showAttribute = false;
                    this.fileList=[];
                    // this.getList();
                    this.getListDeviceAttribute();
                  });
                }
            }
            });
           
        },

        // 手环管理页面新增设备属性取消按钮
        cancelAttribute() {
            this.showAttribute = false;
            this.fileList=[];
            this.resetAttribute();
        },

        openDeviceAttribute(row){
          this.deviceId = row.deviceId;
          this.title = "查看设备属性"
          this.showDeviceAttribute = true;
          this.getListDeviceAttribute();
        },
        //查看设备属性
        handleQueryDeviceAttribute() {
          this.queryDeviceAttribute.pageNum = 1;
          this.queryDeviceAttribute.deviceId = this.deviceId;
          // this.title = "查看设备属性"
          // this.showDeviceAttribute = true;
          this.getListDeviceAttribute();
        },
   
        
        /** 查询设备属性列表 */
        getListDeviceAttribute() {
          this.loadingTwo = true;
          this.queryDeviceAttribute.deviceId = this.deviceId;
          listDeviceAttribute(this.queryDeviceAttribute).then(response => {
          this.deviceAttributeList = response.rows;
          this.totalTwo = response.total;
          this.loadingTwo = false;
          });
       }, 

        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            this.flag = true;
            this.queckName = row.lyName;
            const deviceId = row.deviceId
            getDeviceInfo(deviceId).then(response => {
              this.form = response.data;
              this.$set(this.form,'deviceType',response.data.deviceType)
              this.$set(this.form,'deviceCode',response.data.deviceCode+'')
              this.$set(this.form,'deviceName',response.data.deviceName+'')
              this.$set(this.form,'deviceIndex',response.data.deviceIndex)
              setTimeout(()=>{
                this.open = true;
                this.title = "修改设备";
              },100)
             
            });
        },

        /** 提交按钮 */
        submitForm() { 
            this.$refs["form"].validate(valid => {
            if (valid) {
                if (this.form.deviceId != undefined) {
                  editDevice(this.form).then(response => {
                    this.$modal.msgSuccess("修改成功");
                    this.open = false;
                    this.getList();
                  });
                } else {
                console.log(this.form)
                  addDevice(this.form).then(response => {
                    this.$modal.msgSuccess("新增成功");
                    this.open = false;
                    this.getList();
                  });
                }
            }
            });
        },

        /** 删除按钮操作 */
        handleDelete(row) {
            const  param = {
              deviceId:row.deviceId
            }
            if (row.lyName!=null && row.lyName!='') {
              this.$alert('存在使用人，无法删除', '提示', {
                type: 'warning',
                confirmButtonText: '确定',
              });
              return;
            }
            this.$modal.confirm('是否确认删除设备名称为"' + row.deviceName + '"的数据项？').then(function() {
              return delDevice(param);
            }).then(() => {
              this.getList();
              this.$modal.msgSuccess("删除成功");
            }).catch(() => {});
        },
        /** 导出按钮操作 */
        handleExport() {
          if(this.ids.length == 0){
            exportDevice(this.queryParams).then(res => {
            downloadFile({ fileName: `设备_${new Date().getTime()}.xlsx`, fileData: res, fileType: 'application/vnd.ms-excel;charset=utf-8' })
          })
          }else{
            const ids = this.ids.join(',')
            exportDeviceSome({ids:ids}).then(res => {
            downloadFile({ fileName: `设备_${new Date().getTime()}.xlsx`, fileData: res, fileType: 'application/vnd.ms-excel;charset=utf-8' })
          })
          }
        },
        //打开设备页面
        openDevice(row){
          this.sidebandId = row.sidebandId;
          this.title = "选择"
          this.showDevice = true;
          this.getListDevice();
        },
 
  
    }
  };
  </script>

  <style lang="scss" scoped>
  .uploadImg {
    padding-top: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .deviceCode {
      margin-top: 10px;
      padding-bottom: 20px;
      font-size: 18px;
  }
  ::v-deep.el-table .fixed-width .el-button--mini {
      width: 60px !important;
      margin-bottom: 10px;
  }
  //隐藏图片上传框的css
  ::v-deep.disabled {
      .el-upload--picture-card {
          display: none;
      }
  }
  </style>