<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"
              :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"
          />
        </el-form-item>
        <el-form-item  prop="deviceCode">
          <el-input
            v-model="queryParams.deviceCode"
            placeholder="请输入设备编码"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </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="deviceId" @selection-change="handleSelectionChange" @select="handlerSelect" @select-all="handlerSelectAll">
        <el-table-column type="selection" width="55" align="center" :reserve-selection="true" />
        <el-table-column label="设备id" align="center" prop="deviceId" v-if="false" />
        <el-table-column label="设备类型" align="center" prop="deviceType">
          <template slot-scope="scope">
              <div>{{ dict.type.sys_device_type[Number(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" />
        <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-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-model="form.deviceType" placeholder="请选择设备类型" clearable style="width: 100%;">
                         <el-option
                           v-for="dict in dict.type.sys_device_type"
                           :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>
        <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="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>
    </div>
  </template>
  
  <script>
  import { listDevcie, addDevice, editDevice, getDeviceInfo,delDevice, exportDevice} 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 {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        //绑定设备总条数
        totalTwo:0,
        //未绑定设备总条数
        totalThree:0,
        // 设备表格数据
        tableData: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        //所属工程
        proList: [],
        //状态
        StatusList:[],
        Qrcode:"",
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          deviceType:undefined,
          deviceName:undefined,
          deviceCode: undefined,
          devcieStatus: undefined,
        },
        maxLength:100,//已选列表上限，防止数据过多请求报错
        currentSelection:[],//已选列表
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          deviceType: [
            { required: true, message: "设备类型不能为空", trigger: "change" }
          ],
          deviceCode: [
            { required: true, message: "设备编码不能为空", trigger: "blur" }
          ],
          deviceName: [
            { required: true, message: "设备名称不能为空", trigger: "blur" }
          ]
        },
        //二维码
        rowObj:{},
        uploadOpen:false,
        deviceCode:'',
      };
    },
    computed: {

    },
    created() {
      this.getList();
      
    },
    mounted(){
      console.log(this.dict.type.sys_device_type)
    },
    methods: {

        /** 查询设备列表 */
        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.deviceId === row) {
                        this.$refs.multipleTable?.toggleRowSelection(item, true)
                      }
                    })
                  })
                })
              } else {
                this.$refs.multipleTable?.clearSelection()
              }
            });
        },

        // 取消按钮
        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.deviceId)
            this.single = selection.length!=1
            this.multiple = !selection.length
        },
        //单选操作-跨页
        handlerSelect(val, row) {
          this.currentSelection.indexOf(row.deviceId) === -1
            ? this.currentSelection.push(row.deviceId)
            : this.currentSelection.splice(this.currentSelection.indexOf(row.deviceId), 1)
        },
        //全选操作-跨页
        handlerSelectAll(val) {
          if (val.length) {
            // 进来此处说明:
            // 1 当前页的全选 2 其他页有数据然后当前页的取消全选
            // 比较全选或者取消全选与当前页的数据，得到差集
            // 如果tableData中的数据在val中不存在，则说明是取消全选，需要从currentSelection中移除
            // 如果tableData中所有的数据都在val中存在，则说明是全选，需要将差集添加到currentSelection中
            const isAllSelect = this.tableData.every(item =>
            val.some(valItem => valItem.deviceId === item.deviceId)
            )
            if (isAllSelect) {
              // 全选中新增的差集
              const diff = val.filter(
              item => !this.currentSelection.some(deviceId => deviceId === item.deviceId)
            )
            if (this.currentSelection.length + diff.length > this.maxLength) {
                this.currentSelection = this.currentSelection.concat(
                  diff.splice(0, this.maxLength - this.currentSelection.length)
                      .map(item => item.deviceId))
                diff.forEach(item => this.$refs.multipleTable.toggleRowSelection(item, false))
            } else {
                this.currentSelection = this.currentSelection.concat(diff.map(item => item.deviceId))
            }
            } else {
                this.currentSelection = this.currentSelection.filter(
                  deviceId => !this.tableData.some(item => item.deviceId === deviceId)
                )
              }
          } else {
            // 进来此处说明:
            // 其他页并无勾选数据，且当前页取消勾选
            this.currentSelection = []
          }
        },
        clearCheck(){
          console.log("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.open = true;
            this.title = "添加设备";
        },



        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            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+'')
              setTimeout(()=>{
                this.open = true;
                this.title = "修改设备";
              },100)
             
            });
        },

        /** 提交按钮 */
        submitForm() { 
            this.$refs["form"].validate(valid => {
            if (valid) {
                if (this.form.deviceId != undefined) {
                  console.log(this.form)
                  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) {
            console.log(row)
            const  param = {
              deviceId:row.deviceId
            }
            this.$modal.confirm('是否确认删除设备名称为"' + row.deviceName + '"的数据项？').then(function() {
              return delDevice(param);
            }).then(() => {
              this.getList();
              this.$modal.msgSuccess("删除成功");
            }).catch(() => {});
        },
        /** 导出按钮操作 */
        handleExport() {
          exportDevice(this.queryParams).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>