<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="devcieType">
          <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>
        
        <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="设备id" align="center" prop="deviceId" v-if="false" />
        <el-table-column label="设备类型" align="center" prop="deviceType" />
        <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="handleQuertPage(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;">{{ stateList[Number(scope.row.deviceStatus)] }}</div>
                <div v-if="scope.row.deviceStatus==1" style="color: red;">{{ stateList[Number(scope.row.deviceStatus)] }}</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="showGt" width="1000px" height="1000px" append-to-body>
          <el-form :model="queryKeyword" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item  prop="keyword">
          <el-input
            v-model="queryKeyword.keyword"
            placeholder="请输入关键词"
            clearable
            @keyup.enter.native="handleQueryTemp"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryTemp">查询</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="handleAddDevice"
            v-hasPermi="['basic:sideband:add']"
          >绑定设备</el-button>
        </el-col>
        
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getListTemp"></right-toolbar>
      </el-row>

      <el-table v-loading="loadingTwo" :data="bindList" width="600px" height = "600px" >
        <el-table-column label="设备id" align="center" prop="deviceId" v-if="false" />
        <el-table-column label="设备类型" align="center" prop="deviceType" />
        <el-table-column label="设备名称" align="center" prop="deviceName" />
        <el-table-column label="设备编号" align="center" prop="deviceCode" />
        <el-table-column label="设备状态" align="center" prop="deviceStatus" >
        <template slot-scope="scope">
                <div v-if="scope.row.deviceStatus==0" style="color: green;">{{ stateList[Number(scope.row.deviceStatus)] }}</div>
                <div v-if="scope.row.deviceStatus==1" style="color: red;">{{ stateList[Number(scope.row.deviceStatus)] }}</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="handleDelDevice(scope.row)"
              v-hasPermi="['basic:sideband:edit']"
            >解除绑定</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <pagination
        v-show="totalTwo>0"
        :total="totalTwo"
        :page.sync="queryKeyword.pageNum"
        :limit.sync="queryKeyword.pageSize"
        @pagination="getListTemp"
      />

      </el-dialog>

      <!-- 选择设备弹窗 -->
      <el-dialog :title="title" :visible.sync="showDevice" width="800px" height="800px" append-to-body>
          <el-form :model="queryKeywordTemp" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item  prop="keyword">
          <el-input
            v-model="queryKeywordTemp.keyword"
            placeholder="请输入关键词"
            clearable
            @keyup.enter.native="handleQueryDevice"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryDevice">查询</el-button>
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleBindDevice"
            v-hasPermi="['basic:sideband:add']"
          >绑定</el-button>
        </el-form-item>
        </el-form>
<!-- 
        <el-row :gutter="10" class="mb8">
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getListDevice"></right-toolbar>
      </el-row> -->

      <el-table v-loading="loadingThree" :data="bindNoList" width="600px" height = "600px" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="设备id" align="center" prop="deviceId" v-if="false" />
        <el-table-column label="设备类型" align="center" prop="deviceType" />
        <el-table-column label="设备名称" align="center" prop="deviceName" />
        <el-table-column label="设备编号" align="center" prop="deviceCode" />
      </el-table>
  
      <pagination
        v-show="totalThree>0"
        :total="totalThree"
        :page.sync="queryKeywordTemp.pageNum"
        :limit.sync="queryKeywordTemp.pageSize"
        @pagination="getListDevice"
      />

      </el-dialog>

      <!-- 添加或修改设备对话框 -->
      <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="请输入设备编码" />
                    </el-form-item>
                    <el-form-item label="设备名称" prop="deviceName">
                        <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
                    </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>

    </div>
  </template>
  
  <script>
  import { listDevcie, addDevice, editDevice, getDeviceInfo,delDevice,listDeviceNoBind,bindDevice, exportDevice} from "@/api/base/device";

  import { downloadFile } from '@/utils/download'
  import { getToken } from '@/utils/auth'
  import uploadFile from '../../components/uploadFile.vue'
  export default {
    name: "Post",
    dicts: ['sys_normal_disable','sys_user_sex','sys_device_type','sys_device_status'],
    components: {
			uploadFile
		},
    data() {
      return {
        // 遮罩层
        loading: true,
        // 遮罩层2
        loadingTwo:true,
        // 遮罩层3
        loadingThree:true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        //绑定设备总条数
        totalTwo:0,
        //未绑定设备总条数
        totalThree:0,
        // 设备表格数据
        deviceList: [],
        // 绑定设备表格数据
        bindList: [],
        // 绑定设备表格数据
        bindNoList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        //所属工程
        proList: [],
        //状态
        StatusList:[],
        Qrcode:"",
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          deviceType:undefined,
          deviceName:undefined,
          deviceCode: undefined,
          devcieStatus: undefined,
        },
        queryKeyword:{
          pageNum: 1,
          pageSize: 10,
          sidebandId: undefined,
          keyword: undefined,
        },
        queryKeywordTemp:{
          pageNum: 1,
          pageSize: 10,
          sidebandId: undefined,
          keyword: undefined,
        },
        showGt:false,

        showDevice:false,

        stateList:['在用','未用'],
        accept:'.png, .jpg, .jpeg, .pdf, .doc, .docx',
        highImgList: [],
        electricianImgList: [],
        elseImgList: [],
        // 表单参数
        form: {},
        //图片上传
        fileList: [],
        //图片查看弹窗
        dialogImageUrl: '',
        dialogVisible: false,
        // 用户导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/bracelet/person/excelUpload"
        },
        // 表单校验
        rules: {
          deviceType: [
            { required: true, message: "设备类型不能为空", trigger: "change" }
          ],
          deviceCode: [
            { required: true, message: "设备编码不能为空", trigger: "blur" }
          ],
          deviceName: [
            { required: true, message: "设备名称不能为空", trigger: "blur" }
          ]
        }
      };
    },
    computed: {
        //图片上传1张后，隐藏上传框
        uploadDisabled() {
            return this.fileList.length > 0
        },
    },
    created() {
      this.getList();
    },
    methods: {

        /** 查询设备列表 */
        getList() {
            this.loading = true;
            listDevcie(this.queryParams).then(response => {
              this.deviceList = response.rows;
              this.total = response.total;
              this.loading = false;
            });
        },

        // 取消按钮
        cancel() {
            this.open = false;
            this.fileList=[];
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {};
            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
        },

        handleQuertPage(row){
          const qrCodeData = {
        "设备类型": row.deviceType,
        "设备名称": row.deviceName,
        "设备编号": row.deviceCode,
        "设备状态": row.deviceStatus,
    };
        const qrCodeString = JSON.stringify(qrCodeData, null, 2);
        console.log(qrCodeString);
        //清空二维码容器
        // Qrcode = "";
        // // 生成二维码
        //  Qrcode.qrcode(utf16to8(qrCodeString));
        this.open = true;
        },
        /** 新增按钮操作 */
        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' })
          })
        },

        /** 导入按钮操作 */
        handleImport() {
          this.upload.title = "人员导入";
          this.upload.open = true;
        },


        //打开杆塔页面
        openGt(row){
          this.sidebandId = row.sidebandId;
          this.title = "杆塔"
          this.showGt = true;
          this.getListTemp();
        },
        //打开设备页面
        openDevice(row){
          this.sidebandId = row.sidebandId;
          this.title = "选择"
          this.showDevice = true;
          this.getListDevice();
        },
        
        //关闭证书上传
        cancelGt(){
          this.highImgList = []
          this.electricianImgList = []
          this.elseImgList = []
          this.showGt = false;
        },
        //提交证书上传
        submitCertificate(){
          console.log(this.highImgList)
          console.log(this.electricianImgList)
          console.log(this.elseImgList)
          // this.highImgList = []
          // this.electricianImgList = []
          // this.elseImgList = []

          this.showGt = false;
        },
  
    }
  };
  </script>

  <style lang="scss" scoped>
  ::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>