<template>
  <!-- 视频设备管理 -->
  <div class="app-container">
    <el-form v-show="showSearch" :model="queryParams" ref="queryForm" size="small" inline>
      <el-form-item label="" prop="keyWord">
        <el-input
          v-model="queryParams.keyWord"
          placeholder="请输入搜索关键词"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="" prop="onLine">
        <el-select v-model="queryParams.onLine" placeholder="设备状态" clearable>
          <el-option v-for="item in deviceStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <!-- 表单按钮 -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
        <el-button icon="el-icon-download" @click="handleExport">导出</el-button>
        <el-button icon="el-icon-menu" @click="">下载二维码</el-button>
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
        <el-button icon="el-icon-download" @click="">导入数据</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableList" fit highlight-current-row style="width: 100%">
      <!-- 多选 -->
      <!-- <el-table-column type="selection" width="55" align="center" @selection-change="selectionChange" /> -->
      <el-table-column
        type="index"
        width="55"
        label="序号"
        align="center"
        :index="indexContinuation(queryParams.pageNum, queryParams.pageSize)"
      />
      <el-table-column
        v-for="(column, index) in tableColumns"
        show-overflow-tooltip
        :key="column.prop"
        :label="column.label"
        :prop="column.prop"
        align="center"
      >
        <!-- 插槽 -->
        <template v-slot="scope" v-if="column.prop == 'qrCode'">
          <span style="color: #409eff; cursor: pointer" @click="checkQrCode(scope.row)">查看</span>
        </template>
        <template v-slot="scope" v-else-if="column.prop == 'isT'">
          <div style="display: flex; align-items: center; justify-content: center">
            <div class="dot" v-if="scope.row.isT == 1"></div>
            <div class="dot-red" v-else></div>
            <div>{{ scope.row.isT == 1 ? '是' : '否' }}</div>
            <div
              v-if="scope.row.isT == 1"
              style="margin-left: 5px; color: #409eff; cursor: pointer"
              @click="handleDetail(scope.row)"
            >
              查看配置
            </div>
          </div>
        </template>
        <template v-slot="scope" v-else-if="column.prop == 'onLine'">
          <div style="display: flex; align-items: center; justify-content: center">
            <div class="dot" v-if="scope.row.onLine == 1"></div>
            <div class="dot-red" v-else></div>
            <div>{{ scope.row.onLine == 1 ? '在用' : '闲置' }}</div>
          </div>
        </template>
      </el-table-column>
      <!-- 操作 -->
      <el-table-column label="操作" align="center" width="255">
        <template slot-scope="scope">
          <el-button type="warning" plain size="mini" icon="el-icon-set-up" @click="handleMonitoringAndDebug(scope.row)"
            >调试</el-button
          >
          <el-button type="primary" plain size="mini" icon="el-icon-edit" @click="handleEdit(scope.row)">
            编辑
          </el-button>
          <el-button type="danger" plain size="mini" icon="el-icon-delete" @click="handleDelete(scope.row)">
            删除
          </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="dialogTitle" :visible.sync="dialogVisible" width="40%">
      <el-form ref="dialogForm" :model="dialogForm" label-width="170px" :rules="dialogRules">
        <el-form-item label="设备类型" prop="devType" v-if="showItem">
          <el-select v-model="dialogForm.devType" placeholder="请选择设备类型" clearable style="width: 100%">
            <el-option v-for="item in deviceTypeOpts" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备名称" prop="devName" v-if="showItem">
          <el-input v-model="dialogForm.devName" placeholder="请输入设备名称" clearable maxlength="64" />
        </el-form-item>
        <el-form-item label="MAC编码" prop="macId" v-if="showItem">
          <el-input v-model="dialogForm.macId" placeholder="请输入MAC编码" clearable maxlength="64" />
        </el-form-item>
        <el-form-item label="国标编码" prop="gbCode" v-if="showItem">
          <el-input v-model="dialogForm.gbCode" placeholder="请输入国标编码" clearable maxlength="64" />
        </el-form-item>
        <el-form-item label="puid" prop="puId" v-if="showItem">
          <el-input v-model="dialogForm.puId" placeholder="请输入puid" clearable maxlength="64" />
        </el-form-item>
        <el-form-item label="视频下标" prop="videoIndex" v-if="showItem">
          <el-input v-model="dialogForm.videoIndex" placeholder="请输入视频下标" clearable maxlength="64" />
        </el-form-item>
        <el-form-item label="是否接入统一视频" prop="isT" v-if="showItem">
          <el-radio-group v-model="dialogForm.isT" @input="changeIsAccess">
            <el-radio-button label="1">是</el-radio-button>
            <el-radio-button label="0">否</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="统一视频名称" prop="tName" v-if="dialogForm.isT == '1'">
          <el-input
            v-model="dialogForm.tName"
            placeholder="请输入统一视频名称"
            clearable
            :disabled="!showItem"
            maxlength="64"
          />
        </el-form-item>
        <el-form-item label="统一视频编码" prop="tCode" v-if="dialogForm.isT == '1'">
          <el-input
            v-model="dialogForm.tCode"
            placeholder="请输入统一视频编码"
            clearable
            :disabled="!showItem"
            maxlength="64"
          />
        </el-form-item>
        <el-form-item label="统一视频前端协议编码" prop="tWbCode" v-if="dialogForm.isT == '1'">
          <el-input
            v-model="dialogForm.tWbCode"
            placeholder="请输入统一视频前端协议编码"
            clearable
            :disabled="!showItem"
            maxlength="64"
          />
        </el-form-item>
        <el-form-item label="统一设备协议编码" prop="tDevCode" v-if="dialogForm.isT == '1'">
          <el-input
            v-model="dialogForm.tDevCode"
            placeholder="请输入统一设备协议编码"
            clearable
            :disabled="!showItem"
            maxlength="64"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark" v-if="showItem">
          <el-input type="textarea" v-model="dialogForm.remark" placeholder="请输入备注" clearable maxlength="100" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">{{ showItem ? '取 消' : '关 闭' }}</el-button>
        <el-button v-if="showItem" type="primary" @click="dialogConfirm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 二维码弹框 -->
    <el-dialog title="二维码查看" :visible.sync="qrVisible" width="36%">
      <div style="text-align: center">
        <vue-qr ref="qrCode" :text="qrData.macId" color-dark="#333" :size="390" :margin="10"></vue-qr>
        <div>设备编号: {{ qrData.gbCode }}</div>
        <div>设备名称: {{ qrData.devName }}</div>
        <!-- 下载 -->
        <el-button type="primary" @click="downloadQrCode" style="margin-top: 20px">下 载</el-button>
      </div>
    </el-dialog>

    <el-dialog title="调试" :visible.sync="videoDebug" width="70%" height="80%">
      <MonitoringAndDebug />
    </el-dialog>
  </div>
</template>

<script>
import VueQr from 'vue-qr'
import MonitoringAndDebug from '@/views/deviceManagement/videoDeviceMgmt/monitoringAndDebug.vue'
import {
  getList,
  getTypeList,
  addVideoDevice,
  editVideoDevice,
  delVideoDevice,
  getVideoDeviceDetail,
} from '@/api/deviceManagement'

export default {
  components: {
    VueQr,
    MonitoringAndDebug,
  },
  data() {
    return {
      showSearch: true,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyWord: '', // 关键词
        onLine: '', // 设备状态
      },
      deviceStatusOptions: [
        { label: '在用', value: '1' },
        { label: '闲置', value: '0' },
      ], // 设备状态
      total: 0, // 总条数
      // 表头
      tableColumns: [
        { label: '设备类型', prop: 'devTypeName' },
        { label: '设备名称', prop: 'devName' },
        { label: 'MACID', prop: 'macId' },
        { label: 'puid', prop: 'puId' },
        { label: '二维码', prop: 'qrCode' },
        { label: '是否接入统一视频', prop: 'isT' },
        { label: '备注', prop: 'remark' },
        { label: '更新人', prop: 'updater' },
        { label: '更新时间', prop: 'updateTime' },
        { label: '设备状态', prop: 'onLine' },
      ],
      // 表格数据
      tableList: [],
      qrVisible: false,
      videoDebug: false,
      qrData: {
        devName: '',
      },
      dialogTitle: '新增',
      isAdd: true,
      dialogVisible: false,
      showItem: true,
      dialogForm: {
        devType: '', // 设备类型
        devTypeName: '', // 设备类型名称
        devName: '', // 设备名称
        macId: '', // MACID
        gbCode: '', // 国标编码
        puId: '', // puid
        videoIndex: '0', // 视频下标
        isT: '0', // 是否接入统一视频
        tName: '', // 统一视频名称
        tCode: '', // 统一视频编码
        tWbCode: '', // 统一视频前端协议编码
        tDevCode: '', // 统一设备协议编码
        remark: '', // 备注
      },
      deviceTypeOpts: [
        { label: '设备类型1', value: '1' },
        { label: '设备类型2', value: '2' },
      ],
      dialogRules: {
        devType: [{ required: true, message: '请选择设备类型', trigger: 'change' }],
        devName: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
        gbCode: [{ required: true, message: '请输入国标编码', trigger: 'blur' }],
        macId: [{ required: true, message: '请输入MACID', trigger: 'blur' }],
        puId: [{ required: true, message: '请输入puid', trigger: 'blur' }],
        // videoIndex 只能输入 number 和 ,
        videoIndex: [
          { required: true, message: '请输入视频下标', trigger: 'blur' },
          {
            pattern: /^[0-9,]*$/,
            message: '只能输入数字和逗号',
            trigger: 'blur',
          },
        ],
        isT: [{ required: true, message: '请选择是否接入统一视频', trigger: 'blur' }],
        tName: [{ required: true, message: '请输入统一视频名称', trigger: 'blur' }],
        tCode: [{ required: true, message: '请输入统一视频编码', trigger: 'blur' }],
        tWbCode: [{ required: true, message: '请输入统一视频前端协议编码', trigger: 'blur' }],
        tDevCode: [{ required: true, message: '请输入统一设备协议编码', trigger: 'blur' }],
      },
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 查询
    handleQuery() {
      this.getList()
    },
    // 重置
    handleReset() {
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10
      this.$refs.queryForm.resetFields()
      this.getList()
    },
    // 获取列表
    async getList() {
      console.log('列表-查询', this.queryParams)
      try {
        this.tableList = []
        const params = { ...this.queryParams }
        const res = await getList(params)
        console.log('🚀 ~ 获取列表 ~ res:', res)
        this.tableList = res.rows
        this.total = res.total
      } catch (error) {
        console.log('🚀 ~ 获取列表 ~ error:', error)
        this.tableList = []
        this.total = 0
      }
    },
    // 设备类型
    async getTypeList() {
      try {
        const params = { dictType: 'smart_device_type' }
        const res = await getTypeList(params)
        console.log('🚀 ~ 获取设备类型 ~ res:', res)
        this.deviceTypeOpts = res.data
      } catch (error) {
        console.log('🚀 ~ 获取设备类型 ~ error:', error)
        this.deviceTypeOpts = []
      }
    },
    // 多选
    selectionChange(val) {
      console.log('selectionChange', val)
    },
    // 切换是否接入统一视频
    changeIsAccess(val) {
      console.log('changeIsAccess', val)
      //清除表单校验
      this.$nextTick(() => {
        this.$refs.dialogForm.clearValidate()
      })
    },
    // 查看二维码
    checkQrCode(row) {
      console.log('查看二维码', row)
      this.qrData = row
      this.qrVisible = true
    },
    // 下载二维码
    downloadQrCode() {
      console.log('下载二维码')
      const a = document.createElement('a') // 创建a标签
      a.download = this.qrData.devName // 下载的文件名
      a.href = this.$refs.qrCode.$el.src // 下载的路径
      a.click()
    },
    // 获取详情
    async getDetail(id) {
      try {
        const res = await getVideoDeviceDetail(id)
        console.log('🚀 ~ 获取详情 ~ res:', res)
        this.dialogForm = res.data
      } catch (error) {
        console.log('🚀 ~ 获取详情 ~ error:', error)
      }
    },
    // 新增
    handleAdd() {
      this.getTypeList()
      console.log('新增')
      this.dialogTitle = '新增'
      this.dialogVisible = true
      this.dialogForm.isT = '0'
      this.isAdd = true
      this.showItem = true
      this.$nextTick(() => {
        this.$refs.dialogForm.resetFields()
      })
    },
    // 编辑
    handleEdit(row) {
      this.getTypeList()
      console.log('编辑', row)
      this.dialogTitle = '编辑'
      this.isAdd = false
      this.dialogVisible = true
      this.dialogForm.isT = row.isT
      this.showItem = true
      this.$nextTick(() => {
        this.$refs.dialogForm.clearValidate()
        this.getDetail(row.id)
      })
    },
    // 监控调试
    handleMonitoringAndDebug(row) {
      console.log('监控调试', row)
      this.videoDebug = true
    },
    // 查看配置
    handleDetail(row) {
      console.log('查看配置', row)
      this.dialogTitle = '统一平台配置'
      this.dialogVisible = true
      this.dialogForm = row
      this.showItem = false
      this.$nextTick(() => {
        this.$refs.dialogForm.clearValidate()
      })
    },
    // 删除
    handleDelete(row) {
      console.log('删除', row)
      this.$confirm('是否删除该数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        const res = await delVideoDevice(row.id)
        console.log('🚀 ~ 删除 ~ res:', res)
        this.getList()
        this.$message({
          type: 'success',
          message: '删除成功!',
        })
      })
    },
    // 导出数据
    handleExport() {
      try {
        let fileName = `数据_${new Date().getTime()}.xLsx`
        let url = '/smart-site/video_equipment/export'
        const params = { ...this.queryParams }
        console.log('🚀 ~ 导出 ~ params:', params)
        this.derive(url, params, fileName)
      } catch (error) {
        console.log('导出数据失败', error)
      }
    },
    // 弹框确认
    dialogConfirm() {
      console.log('dialogConfirm')
      this.$refs.dialogForm.validate(async (valid) => {
        if (valid) {
          if (this.dialogForm.isT == '0') {
            this.dialogForm.tName = ''
            this.dialogForm.tCode = ''
            this.dialogForm.tWbCode = ''
            this.dialogForm.tDevCode = ''
          }
          const params = { ...this.dialogForm }
          console.log('🚀 ~ this.$refs.dialogForm.validate ~ params:', params)
          let res = {}
          if (this.isAdd) {
            // 新增
            res = await addVideoDevice(params)
          } else {
            // 编辑
            res = await editVideoDevice(params)
          }
          console.log('🚀 ~ 弹框确认 ~ res:', res)
          this.$message({
            type: 'success',
            message: '操作成功!',
          })
          this.getList()
          this.dialogVisible = false
        } else {
          return false
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.dot {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: #67c23a;
  display: inline-block;
  margin-right: 5px;
}
.dot-red {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: #f56c6c;
  display: inline-block;
  margin-right: 5px;
}
</style>
