<!--
 * @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'].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'
  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()
    },
    methods: {
      // 重新加载
      onLoad() {
        this.queryForm.pageNum++
        this.getInstList()
      },
      // 查询列表
      async getInstList() {
        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 电脑控制）
       */
      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') {
          // wifi控制 和 电脑控制
          const that = this
          // 调起条码扫描
          const res = await useUserInfo().scanCode()
          that.handleDeCode(res, row)
        } else if (row.controlMode == '30') {
          // 蓝牙
          // this.$refs.bluetoothRef.initBlue('open', row)
          await useUserInfo().scanCode(0)
        }
      },
      /**
       *  解码
       *  code 二维码内容
       *  row 当前预约信息
       * */
      async handleDeCode(code, row) {
        if (this.loading) return
        this.loading = true
        const params = { content: code }
        const [err, res] = await to(instApi.decode({ ...params }))
        if (err) return (this.loading = false)
        if (res.code == 200) {
          this.handleCodeInfo(res.data.content, row)
        } else {
          this.loading = false
        }
      },
      /**
       * 解码后的信息判断扫码仪器是否是当前预约仪器
       * 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) return
          if (instRes.data.id == appointRow.instId) {
            this.handleGetOnByAppointId(appointRow.id)
          } 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) => {
            console.log(e)
            this.cancelAppoint(row.id)
          })
          .catch(() => {
            console.log('ssss')
          })
      },
      // 取消预约
      async cancelAppoint(id) {
        const params = { id }
        const [err, res] = await to(instAppointApi.userCancelAppoint(params))
        this.modalVisible = false
        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>
