<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="deviceName">
        <el-input
          v-model="queryParams.deviceName"
          placeholder="请输入设备名称"
          clearable v-no-whitespace
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="负责人姓名" prop="deviceUser" label-width="85px">
        <el-input
          v-model="queryParams.deviceUser"
          placeholder="请输入设备负责人姓名"
          clearable v-no-whitespace
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="绑定人" prop="createUser" label-width="85px">
        <el-input
          v-model="queryParams.createUser"
          placeholder="请输入绑定人姓名"
          clearable v-no-whitespace
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备类型" prop="deviceType">
        <el-select v-model="queryParams.deviceType" placeholder="请选择设备类型" clearable style="width: 240px">
          <el-option v-for="item in deviceOptions" :key="item.deviceType" :label="item.deviceName" :value="item.deviceType"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          :editable="false"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </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="['system:post:add']"
        >绑定设备
        </el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['system:post:edit']"-->
<!--        >新增闸机-->
<!--        </el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-printer"
          size="mini"
          :disabled="multiple"
          v-print="'#printQrCode'"
        >打印二维码
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:post:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deviceInformation" @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="deviceTypeName"/>
      <el-table-column label="设备型号" align="center" prop="deviceModel"/>
      <el-table-column label="设备负责人" align="center" prop="deviceUser"/>
      <el-table-column label="负责人联系方式" width="120" align="center">
        <template slot-scope="scope">
          <!-- 检查是否存在身份证号 -->
          <span v-if="scope.row.devicePhone">{{ hideSensitiveInfo(scope.row.devicePhone) }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="绑定人" align="center" prop="createUser"/>
      <el-table-column label="绑定时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="设备二维码" align="center" prop="proId">
        <template slot-scope="scope">
          <vue-qr
            ref="qrCode"
            :text="scope.row.deviceId"
            :logoSrc="logoSrc"
            :color-dark="randomColor"
            width="50"
            height="50"></vue-qr>
        </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="['system:post:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleUntie(scope.row)"
            v-hasPermi="['system:post:remove']"
          >解绑
          </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"
    />

    <div class="qrCode-container">
      <div id="printQrCode">
        <div
          v-for="item in printQrCode"
          class="qrCode-content"
        >
          <vue-qr
            ref="qrCode"
            :text="item.url"
            size="400"
          ></vue-qr>
        </div>
      </div>
    </div>

    <!-- 添加或修改设备类型对话框 -->
    <el-dialog :title="title" :visible.sync="edit" width="40%" append-to-body>
      <el-form :label-position="labelPosition" ref="editForm" :model="editForm" :rules="rules">
        <el-input v-model="editForm.deviceId" v-show="false" v-no-whitespace/>
        <el-row type="flex" class="row-bg" justify="space-around">
          <el-col :span="11">
            <el-form-item label="设备名称" prop="deviceName">
              <el-input v-model="editForm.deviceName" placeholder="请输入设备名称"  maxlength="30" v-no-whitespace/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="设备类型" prop="deviceType">
              <el-select v-model="editForm.deviceType" placeholder="请选择设备类型" @change="changeTypeName" :placeholder="isEditing ? '请输入设备类型' : ''" :disabled="!isEditing" :style="{width : '100%'}">
                <el-option v-for="item in dict.type.sys_device_type" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" class="row-bg" justify="space-around" v-if="['1', '2', '3', '5', '6'].includes(editForm.deviceType)">
          <el-col :span="11">
            <el-form-item label="设备puid" prop="puid">
              <el-input v-model="editForm.puid" placeholder="请输入设备puid"  :disabled="!isEditing"
                        :placeholder="'请输入设备puid'" v-no-whitespace
              />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="设备ballIndex" prop="ballIndex" label-width="150">
              <el-select v-model="editForm.ballIndex" placeholder="请选择设备ballIndex" :disabled="!isEditing" :style="{width : '100%'}">
                <el-option value="0">0</el-option>
                <el-option value="1">1</el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" class="row-bg" justify="space-around">
          <el-col :span="11">
            <el-form-item label="设备型号" prop="deviceModel">
              <el-input v-model="editForm.deviceModel" placeholder="请输入设备型号" v-no-whitespace :placeholder="isEditing ? '请输入设备型号' : ''" :disabled="!isEditing"/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="设备负责人" prop="deviceUser" label-width="150">
              <el-input v-model="editForm.deviceUser" placeholder="请输入设备负责人" v-no-whitespace maxlength="20" :placeholder="isEditing ? '请输入设备负责人' : ''" :disabled="!isEditing"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" class="row-bg" justify="space-around">
          <el-col :span="11">
            <el-form-item label="负责人联系方式" prop="devicePhone" label-width="170">
              <el-input v-model="editForm.devicePhone" type="number" v-no-whitespace placeholder="请输入负责人联系方式" maxlength="11" :placeholder="isEditing ? '请输入负责人联系方式' : ''" :disabled="!isEditing"/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="新增人" prop="createUser" v-show="showDeviceName">
              <el-input v-model="editForm.createUser" placeholder="" v-no-whitespace :placeholder="isEditing ? '请输入新增人' : ''" :disabled="!isEditing"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" class="row-bg" justify="space-around">
          <el-col :span="11">
            <el-form-item label="新增时间" prop="createTime" v-show="showDeviceName">
              <el-input v-model="editForm.createTime" v-no-whitespace placeholder="" :placeholder="isEditing ? '请输入新增时间' : ''" :disabled="!isEditing"/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="当前绑定工程" prop="proName" v-show="showDeviceName" label-width="150">
              <el-input v-model="editForm.proName" v-no-whitespace placeholder="" :placeholder="isEditing ? '请输入当前绑定工程' : ''" :disabled="!isEditing"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitEditForm" v-preventReClick="5000">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="open" width="45%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备类型">
          <el-select v-model="form.deviceType" placeholder="请选择设备类型" clearable @clear="clearType" @change="changeTypeName">
            <el-option v-for="item in deviceOptions" :key="item.deviceType" :label="item.deviceName" :value="item.deviceType"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="value">
            <el-transfer
              style="text-align: left; display: inline-block"
              v-model="value"
              filterable
              :titles="['为选择设备', '已选择设备']"
              :format="{
              noChecked: '${total}',
              hasChecked: '${checked}/${total}'
            }"
              @change="handleChange"
              :data="data">
            </el-transfer>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-preventReClick="5000">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  selectDeviceInformation,
  selectDeviceType
} from "@/api/tool/select";
import {
  listDeviceInformation, untieInformation, updateBind
} from "@/api/terminalEquipment/engineeringEquipmentBinding";
import VueQr from 'vue-qr'
import print from 'vue-print-nb'
import { hideSensitiveInfo, parseTime } from '@/utils/bonus'
import {updateDeviceInformation} from "@/api/terminalEquipment/deviceInformation";
import dict from '@/utils/dict'

export default {
  components: {VueQr},
  directives: {
    print
  },
  name: "Post",
  dicts: ['sys_normal_disable','sys_device_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      deviceInformation: [],
      // 日期范围
      dateRange: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示设备名称
      edit: false,
      labelPosition: "top",
      // 角色选项
      deviceOptions: [],
      // 默认为新增模式，可编辑
      isEditing: false,
      showDeviceName: false,
      // 地图是否显示弹出层
      innerVisible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceName: undefined,
        createUser: undefined,
        deviceUser: undefined,
        deviceType: undefined,
      },
      proId: undefined,
      // 表单参数
      form: {},
      editForm: {},
      data: [],
      value: [],
      deviceType: undefined,
      // 表单校验
      rules: {
      },
      logoSrc: '',
      randomColor: 'black',
      qrCodeUrl: '',
      printQrCode: [],
    };
  },
  created() {
    this.proId = this.$route.params.proId;
    this.getList();
    this.getDeviceType();
  },
  methods: {
    dict,
    hideSensitiveInfo,
    parseTime,
    handleChange(value, direction, movedKeys) {
      console.log('value:', value);
      this.value = value;
      console.log('direction:', direction);
      console.log('movedKeys:', movedKeys);
    },
    // 改变类型名称
    changeTypeName(e) {
      // this.form.deviceTypeName = this.deviceOptions.find(item => item.deviceType === e).deviceName
      this.deviceType = e
      this.getDeviceInformation()
    },
    //获取设备类型选项
    getDeviceType() {
      const params = {}
      selectDeviceType(params).then(response => {
        console.log('response:', response.data)
        this.deviceOptions = response.data
      })
    },
    clearType() {
      const params = {
        deviceType : undefined
      }
      selectDeviceInformation(params).then(response => {
        console.log('response:', response.data)
        this.data = response.data
      })
    },
    //获取穿梭框设备信息
    getDeviceInformation() {
      const params = {
        deviceType : this.deviceType
      }
      selectDeviceInformation(params).then(response => {
        console.log('response:', response.data)
        this.data = response.data
      })
    },

    /** 查询设备列表 */
    getList() {
      this.queryParams.proId = this.$route.params.proId;
      this.loading = true;
      listDeviceInformation(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.deviceInformation = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.edit = false;
      this.reset();
      this.value = [];
    },
    // 表单重置
    reset() {
      this.form = {
        deviceId: undefined,
        deviceType: undefined,
        deviceName: undefined,
        devicePhone: undefined,
        deviceModel: undefined,
      };
      this.deviceType = undefined
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.deviceId)
      this.printQrCode = selection.map(item => {
        return {
          url: item.deviceId,
          logo: this.logoSrc
        }
      })
      this.single = selection.length !== 1
      this.multiple = !selection.length > 0;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getDeviceType();
      this.getDeviceInformation();
      // this.isEditing = true;
      this.open = true;
      this.title = "添加工程地址";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log('row:', row)
      this.reset();
      this.getDeviceType();
      this.isEditing = false;
      this.showDeviceName = true;
      row.createTime = this.parseTime(row.createTime);
      this.editForm = row;
      this.edit = true;
      this.title = "编辑设备";
    },

    /** 绑定按钮 */
    submitForm: function() {
      if (this.value.length === 0) {
        this.$modal.msgWarning("请选择设备");
        return;
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.proId = this.proId;
          this.form.value = this.value;
          updateBind(this.form).then(response => {
              this.$modal.msgSuccess("绑定成功");
              this.open = false;
              this.getList();
          });
        }
      });
    },

    /** 修改按钮 */
    submitEditForm: function() {
      this.$refs["editForm"].validate(valid => {
        if (valid) {
          this.editForm.createTime = new Date(this.editForm.createTime.replace(" ", "T"));
          updateDeviceInformation(this.editForm).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.edit = false;
            this.getList();
          }).catch(() => {
            this.editForm.createTime = this.parseTime(this.editForm.createTime);
          });
        }
      });
    },

    /** 解绑按钮操作 */
    handleUntie(row) {
      const addressIds = row.deviceId || this.ids;
      const proId = this.$route.params.proId
      this.$modal.confirm('是否确认解绑设备编号为"' + row.deviceCode + '"的数据项？').then(function () {
        console.log('addressIds:', addressIds)
        console.log('proId:', proId)
        return untieInformation(addressIds, proId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("解绑成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.derive('project/deviceInformation/export', {
        ...this.queryParams
      }, `设备信息_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style>
.el-transfer-panel{
  width: 250px; /* 左右两个穿梭框的高度和宽度 */
  height: 450px;
}

.qrCode-container{
  width: 0;
  height: 0;
  overflow: hidden;
}

.qrCode-content{
  margin-top: 200px;
  margin-left: 160px;
  page-break-after:always
}


</style>
