<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="openTaskModal" v-show="status == 0">开 始 盘 点</uv-button>
    <uv-button type="primary" text="确定" size="large" class="btn" @tap="goMatch" v-show="status == 1">匹 配 结 果</uv-button>

    <uv-modal ref="taskModalRef" title="任务名称" @confirm="startScan" asyncClose>
      <view class="slot-content" style="width: 100%;">
				<uv-form labelPosition="left" :model="taskForm" labelWidth="80" :rules="rules" ref="formRef">
          <uv-form-item label="任务名称" prop="taskName" borderBottom>
            <uv-input v-model="taskForm.taskName" border="none" placeholder="请输入任务名称" />
          </uv-form-item>
          <uv-form-item label="盘点场景" prop="beLong" borderBottom>
            <uni-data-select
              v-model="taskForm.beLong"
              :localdata="beLongList"
               placeholder="请选择盘点场景"
            ></uni-data-select>
          </uv-form-item>
        </uv-form>
			</view>
    </uv-modal>
  </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, listScene, getScene } from "@/api/inventory"

const deviceInfo = ref({})


const status = ref(0)
const taskModalRef = ref("")
const scanTotal = ref("")
const formRef = ref(null)
const beLongList = ref([])
const openTaskModal = () => {
  taskModalRef.value.open();
} 
const taskForm = ref({
  taskName: '',
  beLong: ""
})
const rules = ref({
  'taskName': {
    type: 'string',
    required: true,
    message: '请填写任务名称',
    trigger: ['blur', 'change']
  },
  'beLong': {
    type: 'string',
    required: true,
    message: '请选择盘点场景',
    trigger: ['blur', 'change']
  },
})


// 开始盘点
const startScan = () => {
  formRef.value.validate().then(res => {
    let obj = {
      beLong: taskForm.value.beLong
    }
    getScene(obj).then(res => {
      scanTotal.value = res.data
      let obj = {
        deviceId: deviceInfo.value.deviceId
      }
      getScan(obj).then(() => {
        console.log("开始盘点")
        status.value = 1
        taskModalRef.value.close()
      })
    })
  }).catch(errors => {
    taskModalRef.value.closeLoading()
  })
  
}
// 开始匹配
const goMatch = () => {
  let list = JSON.parse(JSON.stringify(dataList.value))
  let arr = list.splice(1)
  let obj = {
    pageNum: 1,
    pageSize: 10,
    ids: arr,
    status: 0,
    taskName: taskForm.value.taskName,
    deviceId: deviceInfo.value.deviceId,
    showLoading: true,
    beLong: taskForm.value.beLong,
  }
  uni.showLoading({
    title: '加载中',
    mask: true
  })
  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-old?taskName=' + taskForm.value.taskName
      })
      // 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)
    }
  })
  // uni.connectSocket({
  //   url: BASE_URL + '/ws/socket',
  //   success: () => {
  //     uni.showLoading({
  //       title:'正在连接设备...',
  //       mask: true
  //     })
  //     console.log("正准备建立websocket中...");
  //     // 返回实例
  //   },
  // });


  //   uni.onSocketOpen(function (res) {
  //     console.log('WebSocket连接已打开！', res)
  //     send()
  //   })
    
  //   uni.onSocketError(function (res) {
  //     console.log('WebSocket连接打开失败，请检查！', res)
  //     reconnect()
  //   })
    
  //   uni.onSocketMessage(function (res) {
  //     console.log('收到服务器内容：', res)
  //     if (status.value == 0) {
  //       stopTask()
  //     }
  //     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)
  // uni.sendSocketMessage({
  //   data: JSON.stringify(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")
  console.log(BASE_URL)
  connectSocketInit()
  let obj = {
    pageNum: 1,
    pageSize: 100
  }
  listScene(obj).then(res => {
    res.rows.forEach(item => {
      item.value = item.sceneCode
      item.text = item.sceneName
    });
    beLongList.value = res.rows
  })
})

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>
