<!--
 * @Author: liuzhenlin 461480418@qq.ocm
 * @Date: 2023-01-12 11:57:48
 * @LastEditors: liuzhenlin
 * @LastEditTime: 2023-09-26 18:13:20
 * @Description: file content
 * @FilePath: \labsop小程序\pages\appointList\soonGeton\index.vue
-->
<template>
  <div class="panel-wrap">
    <!-- <van-pull-refresh v-model="refreshing" @refresh="onRefresh"> -->
    <van-empty v-if="appointList.length == 0" mode="list" description="暂无即将上机"></van-empty>
    <van-list v-else v-model:loading="listloading" class="data-list" :finished="finished" finished-text="没有更多了"
      @load="onLoad">
      <div class="inst-item mb40" v-for="(v, index) in appointList" :key="index">
        <div class="flex flex-between mb20">
          <div>
            <div class="mr10">
              <span class="primary-color bold fontSize14">{{ v.instName }}</span>
            </div>
          </div>
          <div class="flex">
            <van-button style="width: 80px; height: 30px; margin: 0; font-size: 14px" class="scan-txt" type="primary"
              size="small" :disabled="loading" v-if="['10', '20', '30', '50', '60', '70'].includes(v.controlMode)"
              @click="handleGetOn(v)">
              {{ v.controlMode == '10' ? '上机' : '扫码上机' }}
            </van-button>
            <van-button style="width: 60px; height: 30px; margin: 0 0 0 10px; font-size: 14px" class="scan-txt"
              type="warning" size="small" :disabled="loading" @click="handleCancelAppoint(v)">
              取消
            </van-button>
          </div>
        </div>
        <div class="flex mb20">
          <div class="equ-tit">
            <span class="fontSize14 bold">设备型号：</span>
          </div>
          <div>
            <span class="fontSize14">{{ v.instNameEn }}</span>
          </div>
        </div>
        <div class="flex mb20" v-if="v.projectName">
          <div class="equ-tit">
            <span class="fontSize14 bold">课题组：</span>
          </div>
          <div>
            <span class="fontSize14">{{ v.projectName }}</span>
          </div>
        </div>
        <div class="flex mb20" v-if="v.serviceName">
          <div class="equ-tit">
            <span class="fontSize14 bold">服务：</span>
          </div>
          <div>
            <span class="fontSize14">{{ v.serviceName }}</span>
          </div>
        </div>
        <div class="flex mb20">
          <div class="equ-tit">
            <span class="fontSize14 bold">所在位置：</span>
          </div>
          <div>
            <span class="fontSize14">{{ v.placeAddress + '(' + (v.laboratoryName || '') + ')' }}</span>
          </div>
        </div>
        <div class="flex">
          <div class="equ-tit">
            <span class="fontSize14 bold">开始时间：</span>
          </div>
          <div>
            <span class="fontSize14">
              {{ v.startTime }}
              <!-- {{ v.startTime ? formatDates(new Date(v.startTime), 'YYYY-mm-dd HH:MM') : '' }} -->
            </span>
          </div>
        </div>
      </div>
    </van-list>
    <!-- </van-pull-refresh> -->
    <!-- <blue-tooth ref="bluetoothRef"></blue-tooth> -->
  </div>
</template>

<script>
// import BlueTooth from '../../../components/BlueTooth'
// import { formatDate } from '/@/utils/formatTime'
import { useUserInfo } from '/@/stores/userInfo'
import { useMyAppointApi } from '/@/api/appoint'
const myAppointApi = useMyAppointApi()
import { useInstrApi } from '/@/api/instr'
const instApi = useInstrApi()
import instAppointApi from '/@/api/instr/instAppoint'
import to from 'await-to-js'
import { showConfirmDialog, showNotify } from 'vant'
import { scanCodeWxUrl } from '/@/constants/pageConstants'
export default {
  // components: { BlueTooth },
  data() {
    return {
      loading: false,
      curAppointInfo: {},
      appointList: [],
      queryForm: {
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      listloading: false,
      finished: false
    }
  },
  mounted() {
    this.queryForm.pageNum = 1
    this.getInstList()
    window.addEventListener('pageshow', this.onPageShow)
  },
  beforeUnmount() {
    window.removeEventListener('pageshow', this.onPageShow)
  },
  methods: {
    onPageShow(e) {
      this.loading = false
    },
    // 重新加载
    onLoad() {
      this.queryForm.pageNum++
      this.getInstList()
    },
    // 查询列表
    async getInstList(isRefresh = false) {
      if (!isRefresh) {
        this.listloading = true
      }
      const [err, res] = await to(myAppointApi.toGetonList(this.queryForm))
      this.listloading = false
      if (err) return
      if (res?.code === 200) {
        this.appointList = this.queryForm.pageNum == 1 ? [...(res?.data?.list || [])] : [...this.appointList, ...(res?.data?.list || [])]
        this.total = res?.data?.total
        if (this.queryForm.pageNum * this.queryForm.pageSize >= res.data.total) {
          this.finished = true
        }
      }
    },
    /**
     * 触发上机之前的订阅
     *
     * */
    handleGetOn(row) {
      this.handleScanCode(row)
    },
    /**
     * 调起二维码扫码
     * controlMode （10 不控制 20 电源控制(wifi) 30 电源控制(蓝牙) 50 电脑控制 60 蓝牙V2）
     */
    async handleScanCode(row) {
      this.curAppointInfo = row
      // 直接上机
      if (row.controlMode == '10') {
        showConfirmDialog({
          title: '提示',
          message: '确认上机？'
        })
          .then(() => {
            if (this.loading) return
            this.loading = true
            this.handleGetOnByAppointId(this.curAppointInfo.id)
          })
          .catch(() => { })
      } else if (row.controlMode == '20' || row.controlMode == '50' || row.controlMode == '70') {
        // wifi控制 和 电脑控制
        const that = this
        // 调起条码扫描
        const res = await useUserInfo().scanCode()
        that.handleDeCode(res, row, that.handleCodeInfo)
      } else if (row.controlMode == '30' || row.controlMode == '60') {
        // 蓝牙
        // this.$refs.bluetoothRef.initBlue('open', row)
        // await useUserInfo().scanCode(0)
        const that = this
        const res = await useUserInfo().scanCode()
        that.handleDeCode(res, row, that.handleBluetoothDeCode)
      }
    },
    /**
     *  解码
     *  code 二维码内容
     *  row 当前预约信息
     * func 解码后的操作函数
     * */
    async handleDeCode(code, row, func) {
      if (this.loading) return
      this.loading = true
      const params = { content: code }
      const [err, res] = await to(instApi.decode({ ...params }))
      if (err) {
        this.loading = false
        showNotify({ type: 'danger', message: '解码失败，请重试' })
        return
      }
      if (res?.code == 200 && res?.data?.content) {
        func(res.data.content, row)
      } else {
        this.loading = false
        showNotify({ type: 'danger', message: res?.message || '解码失败' })
      }
    },
    /**
     * 解码后的信息判断扫码仪器是否是当前预约仪器
     * content 解码后的内容 两种 带id（仪器id）和不带id
     * appointRow 当前预约信息
     */
    async handleCodeInfo(content, appointRow) {
      // if (content.includes('id')) {
      //   if (JSON.parse(content).id == appointRow.instId) {
      //     this.handleGetOnByAppointId(appointRow.id)
      //   } else {
      //     this.loading = false
      //     showNotify({ type: 'warning', message: '扫码机器不是预约机器' })
      //   }
      // } else {
      //   // 拿到解码信息（仪器编码）获取仪器id
      //   const [instErr, instRes] = await to(instApi.getIdByTerminal({ terminal: content }))
      //   if (instErr) {
      //     this.loading = false
      //     return
      //   }
      //   if (instRes.data.id == appointRow.instId) {
      //     this.handleGetOnByAppointId(appointRow.id)
      //   } else {
      //     this.loading = false
      //     showNotify({ type: 'warning', message: '扫码机器不是预约机器' })
      //   }
      // }
      console.log(content)
      // 不管有没有 id 都不要再校验“扫码机器不是预约机器”，直接上机
      this.handleGetOnByAppointId(appointRow.id)
    },

    //蓝牙 重新解码函数，获取解码内容之后 执行跳转操作
    async handleBluetoothDeCode(content) {
      let terminal = ''
      if (content.includes('id')) {
        terminal = JSON.parse(content)?.terminal
      } else {
        terminal = content
      }

      this.loading = true
      const [codeErr, codeRes] = await to(instApi.getBlueToothCode({ terminal }))
      if (codeErr) {
        this.loading = false
        showNotify({ type: 'danger', message: '获取蓝牙码失败，请重试' })
        return
      }
      if (codeRes?.code == 200 && codeRes.data?.code) {
        this.loading = false
        const url = scanCodeWxUrl(terminal, 'StartRun')
        window.location.href = url
      } else {
        this.loading = false
        showNotify({ type: 'warning', message: '未获取到该设备的蓝牙配置，请联系管理员' })
      }
    },

    // 上机
    async handleGetOnByAppointId(id) {
      const params = { appointId: id }
      const [err, res] = await to(instAppointApi.getOn({ ...params }))
      this.loading = false
      if (err) return
      if (res.code == 200) {
        showNotify({ type: 'success', message: '上机成功' })
        setTimeout(() => {
          this.$router.push(`/onlineInfo?appointId=${id}`)
        })
      }
    },
    handleCancelAppoint(row) {
      showConfirmDialog({
        title: '提示',
        message: '确认取消预约？'
      })
        .then((e) => {
          this.cancelAppoint(row.id)
        })
    },
    // 取消预约
    async cancelAppoint(id) {
      const params = { id }
      const [err, res] = await to(instAppointApi.userCancelAppoint(params))
      if (err) return
      if (res?.code === 200) {
        this.queryForm.pageNum = 1
        this.appointList = []
        this.getInstList()
        showNotify({ type: 'success', message: '取消成功' })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
* {
  box-sizing: border-box;
}

.panel-wrap {
  height: 100%;

  .data-list {
    .inst-item {
      border-radius: 10px;
      padding: 15px;
      box-shadow: -2px 0px 9px rgba(0, 0, 0, 0.12);
      margin-bottom: 20px;
      background-color: #fff;

      .equ-tit {
        width: 74px;
      }
    }
  }
}
</style>
