<template>
  <view class="container">
    <uv-notice-bar :text="dataList[0] || ''"></uv-notice-bar>
    <view style="margin: 10rpx 0;display: flex;align-items: center;justify-content: space-between;">
      <view>当前扫描到，共：{{ dataList.length - 1 }}条</view>
      <view>总条目：{{ scanTotal || "暂无" }}</view>
    </view>
    <uv-list>
      <uv-list-item :title="item" v-for="(item, index) in dataList" :key="index" v-show="index > 0"></uv-list-item>
    </uv-list>
    <uv-button type="primary" text="确定" size="large" class="btn" @tap="startScan" v-show="status == 0">开 始 盘
      点</uv-button>
    <uv-button type="primary" text="确定" size="large" class="btn" @tap="goMatch" v-show="status == 1">匹 配 结 果</uv-button>

  </view>
</template>

<script setup>
import { BASE_URL } from "@/api/request";
import { ref } from "vue";
import { onLoad, onUnload } from "@dcloudio/uni-app";
import { getScan, stopScan, getMatch, getTaskCount } from "@/api/inventory"

const deviceInfo = ref({})
const taskInfo = ref({})


const status = ref(0)
const taskModalRef = ref("")
const scanTotal = ref("")
const getTotal = () => {
  let obj = {
    taskId: taskInfo.value.id
  }
  obj.sceneId = uni.getStorageSync("taskInfo").sceneId
  obj.warehouseCode = uni.getStorageSync("taskInfo").warehouseCode
  getTaskCount(obj).then(res => {
    scanTotal.value = res.data
  })
}


// 开始盘点
const startScan = () => {
  let obj = {
    deviceId: deviceInfo.value.deviceId
  }
  getScan(obj).then(() => {
    console.log("开始盘点")
    status.value = 1
    taskModalRef.value.close()
  })
}
// 开始匹配
const goMatch = () => {
  let list = JSON.parse(JSON.stringify(dataList.value))
  let arr = list.splice(1)
  let obj = {
    ids: arr,
    taskId: taskInfo.value.id,
    deviceId: deviceInfo.value.deviceId,
  }
  getMatch(obj).then(res => {
    console.log("保存数据")
    stopTask(1)
  })
}


const stopTask = (status) => {
  console.log("停止")
  let obj = {
    deviceId: deviceInfo.value.deviceId,
    showLoading: true
  }
  console.log("deviceId", deviceInfo.value.deviceId)
  stopScan(obj).then(res => {
    console.log("停止盘点")
    if (status == 1) {
      uni.hideLoading()
      uni.redirectTo({
        url: '/pagesInventory/matchResult?taskId=' + taskInfo.value.id
      })
      // uni.closeSocket()
    }
    if (status != 2) {
      socketTask.value.close();
      clearInterval(reconnectTimeOut.value)
    }
  })
}

const dataList = ref([])
const reconnectTimeOut = ref(null)
const isOpenSocket = ref(true)
const socketTask = ref(null)
const connectSocketInit = () => {
  socketTask.value = uni.connectSocket({
    url: BASE_URL + '/ws/socket',
    success: () => {
      console.log('WebSocket连接创建成功');
    }
  });

  socketTask.value.onOpen(() => {
    console.log('WebSocket连接已打开');
    send()
  });

  socketTask.value.onError(() => {
    console.log('WebSocket连接打开失败，请检查！', res)
    reconnect()
  })


  socketTask.value.onClose(() => {
    console.log('WebSocket连接已关闭');
  });

  socketTask.value.onMessage((res) => {
    if (status.value == 0) {
      stopTask(2)
    }
    uni.hideLoading()
    if (((status.value == 0 && res.data.includes("连接")) || (status.value == 1 && !res.data.includes("连接"))) && !(dataList.value.some(e => e == res.data))) {
      // if (((status.value == 0 && res.data.includes("连接")) || (status.value == 1 && !res.data.includes("连接"))) && !(dataList.value.some(e => e == res.data))) {
      dataList.value.push(res.data)
      console.log("存储", dataList.value)
    }
  })


}

const send = () => {
  let obj = {
    deviceId: deviceInfo.value.deviceId,
    ip: deviceInfo.value.ipAddress,
    port: deviceInfo.value.port
  }
  console.log("发送参数", obj)
  socketTask.value.send({
    data: JSON.stringify(obj)
  })

}

//重新连接
const reconnect = () => {
  console.log("重连")
  //停止发送心跳
  clearInterval(reconnectTimeOut.value)
  //如果不是人为关闭的话，进行重连
  if (isOpenSocket.value) {
    reconnectTimeOut.value = setInterval(() => {
      connectSocketInit();
    }, 5000)
  }
}


onLoad(() => {
  deviceInfo.value = uni.getStorageSync("deviceInfo")
  taskInfo.value = uni.getStorageSync("taskInfo")
  connectSocketInit()
  getTotal()
})

onUnload(() => {
  console.log("销毁")
  // uni.closeSocket()
  stopTask(0)
})
</script>

<style scoped lang="scss">
.container {
  padding: 32rpx;
  position: relative;

  .tableBox {
    padding-bottom: 120rpx;
  }

  .paginationBox {
    margin-top: 20rpx;
  }

  .btn {
    // height: 100rpx;
    position: fixed;
    width: calc(100vw - 64rpx);
    bottom: 0;
    left: 32rpx;
    z-index: 9999;
  }
}

::v-deep .uni-select {
  border: unset;
  border-bottom: unset;
}

::v-deep .uv-popup .uv-popup__content {
  overflow: unset !important;
}

::v-deep .uv-modal {
  overflow: unset !important;
}

::v-deep .uv-input__content {
  flex-direction: column;
  align-items: flex-start;
}

::v-deep .uni-select__input-placeholder {
  font-size: unset;
  color: #c0c4cc;
}

::v-deep .uni-select {
  padding: 0 !important;
}
</style>
