<script setup>
import { getCurrentInstance, nextTick, onMounted, ref } from 'vue';
import { showConfirmDialog, showFailToast, showSuccessToast } from 'vant';

const base_url = '/sgsafe/SafeClient'
const {
  proxy
} = getCurrentInstance()

/* 通用方法： 重置list数据 */
const basicReset = () => {
  finished.value = false;
  loading.value = true;
  pageNum.value = 1
  list.value = []
}

const pageNum = ref(1)
const pageSize = ref(10)
const fetchData = ref({
  clientId: '',
})

/* 条件查询返回结果 */
const total = ref(0)
const resultData = ref([])
const queryFetch = async () => {
  const url = base_url + '/query'
  const param = {
    page: pageNum.value,
    rows: pageSize.value,
    params: JSON.stringify(fetchData.value)
  }
  const res = await proxy.$axios.post(url, param)
  if (res.data.code === 0) {
    total.value = res.data.data.total
    resultData.value = res.data.data.records
  } else {
    showFailToast('操作失败!' + res.data.msg)
  }
}

const onSearch = () => {
  basicReset()
  onLoad()
}

/* 查询条件重置 */
const resetCondition = () => {

  fetchData.value = {
    clientId: '',
  }
  basicReset()
  onLoad()
}

/* 列表加载与下拉刷新 */
const list = ref([]);
const refreshing = ref(false)
const loading = ref(false)
const finished = ref(false)

const onRefresh = () => {
  basicReset()
  onLoad()
};

const onLoad = async () => {
  if (refreshing.value) {
    list.value = [];
    pageNum.value = 1;
    refreshing.value = false;
  }
  try {
    await  queryFetch();
    if (pageSize.value * pageNum.value < total.value) {
      list.value = [...list.value,...resultData.value ]
      openStates.value = new Array(list.value.length).fill(true);
      pageNum.value++;
    } else {
      list.value = [...list.value,...resultData.value ]
      openStates.value = new Array(list.value.length).fill(true);
      finished.value = true;
    }
  } catch (error) {
    console.log(error);
    finished.value = true;
  } finally {
    loading.value = false;
  }
}

/**
 * 获取所有蓝牙信标
 */
const beaconList = ref([])
const getDangerAreaByCode = async () => {
  const url = '/sgsafe/SafeBeacon/selectAll'
  const param = {}
  const res = await proxy.$axios.post(url,param)
  if (res.data.code === 0) {
    beaconList.value = res.data.data
  } else {
    showFailToast('操作失败' + res.data.msg)
  }
}

/**
 * 根据蓝牙信标返回危险区域名称
 */
const getAreaNameByCode = (beaconCode) => {
  for (let item of beaconList.value) {
    if (item.beaconCode === beaconCode) {
      return item.areaName
    }
  }
  return ''
}

/**
 * 弹出终端前警告
 */
const handleResetClient = (clientId) => {
  showConfirmDialog({
    title:'警告',
    message: '终端异常事件是否已解决？'
  })
  .then(() => {
    resetClientManually(clientId)
  })
  .catch(() => {

  })
}

/**
 * 手动重置终端
 */
const resetClientManually = async (clientId) => {

  const url = '/sgsafe/SafeClient/resetClientManually'
  const param = {
    clientId: clientId
  }
  const res = await proxy.$axios.post(url,param)
  if (res.data.code === 0) {
    showSuccessToast('重置终端成功')
    basicReset()
    onLoad()
  } else {
    showFailToast('操作失败!' + res.data.msg)
  }
}

/**
 * 按钮实现swipe-cell滑动
 */
const openStates  = ref([])
const swipeCellRefs = ref([])
const getSwipeCellRef = (el, index) => {
  if (el) {
    swipeCellRefs.value[index] = el;
  }
}
const openSwipe = (idx) => {
  openStates.value = new Array(list.value.length).fill(true);
  if (idx >= 0 && idx < swipeCellRefs.value.length) {
    openStates.value[idx] = false
    swipeCellRefs.value[idx].open('right')
  }
  document.addEventListener('click',handleDocumentClick)
}

const closeSwipe = (idx) => {
  if (idx >= 0 && idx < swipeCellRefs.value.length) {
    openStates.value[idx] = true
    swipeCellRefs.value[idx].close()
  }
}

/* 当点击滑动单元格时，开始监听点击事件 */
const handleDocumentClick = (event) => {
  openStates.value = new Array(list.value.length).fill(true);
}

/**
 *  人员选择
 */
import OrganizationalWithLeafUserOne from '@/components/OrganizationalWithLeafUserOne.vue';
const popupDeptUserRef = ref()
const selectedClientId = ref('')
const handleDeptUser = (clientId) => {
  selectedClientId.value = clientId
  popupDeptUserRef.value.open()
}

const returnUserInfo = (data) => {
  addOwner(data.user.userCode,data.user.userDesc)
}

const addOwner = (ownerCode,ownerName) => {
  const url = base_url + '/saveOwner'
  const param = {
    clientId: selectedClientId.value,
    ownerCode: ownerCode,
    ownerName: ownerName
  }
  proxy.$axios.post(url,param).then(res => {
    if (res.data.code === 0) {
      showSuccessToast('操作成功')
      basicReset()
      onLoad()
    } else {
      showFailToast('操作失败！' + res.data.msg)
    }
  })
}

onMounted(() => {
  getDangerAreaByCode()
  basicReset()
  onLoad()
})

</script>

<template>
  <div class="page-container">
    <van-sticky>
      <van-nav-bar title="终端管理" />

      <van-search
        v-model="fetchData.clientId"
        @search="onSearch"
        @clear="resetCondition"
        placeholder="请输入终端编号"
      />
    </van-sticky>

    <div class="scroll-container">
      <van-pull-refresh
        v-model="refreshing"
        success-text="刷新成功"
        @refresh="onRefresh"
      >
        <van-list
          class="listDiv"
          :immediate-check="false"
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >

          <div v-for="(item,idx) in list" :key="item.id">
            <van-swipe-cell
              title-style="color: #007aff"
              class="goods-card"
              :ref="el => getSwipeCellRef(el, idx)"
            >
              <template #default>
                <div class="swipe-cell-default">
                  <van-cell>
                    <template #title>
                      <van-icon name="idcard" />
                      <span class="bold-title"  style="margin-left: 4px;margin-right: 10px">{{ item.clientId }}</span>
                      <van-tag style="margin-right: 10px;" :type="item.isInDanger === 1 ? 'danger' : 'success'">{{ item.isInDanger === 1 ? (getAreaNameByCode(item.uwbBaseId1) ? getAreaNameByCode(item.uwbBaseId1) : '暂无区域') : '安全区域' }}</van-tag>
                      <van-tag style="margin-right: 10px;" v-if="item.isInDanger === 1" :type="item.isSos === 0 ? 'success': 'danger'">{{ item.isSos === 0 ? '正常' : 'SOS' }}</van-tag>
                      <van-tag style="margin-right: 10px;" v-if="item.isInDanger === 1" :type="item.isSingle === 0 ? 'success': 'danger'">{{ item.isSingle === 0 ? '多人' : '单人' }}</van-tag>
                      <van-tag style="margin-right: 10px;" v-if="item.isInDanger === 1" :type="item.isLongtime === 0 ? 'success': 'danger'">{{ item.isLongtime === 0 ? '<30' : '超时' }}</van-tag>
                    </template>
                    <template #label>
                      <div class="label-content">
                        <span style="margin-right: 10px">拥有者姓名：{{ item.ownerName ? item.ownerName : '暂无拥有者' }}</span>
                      </div>
                    </template>
                  </van-cell>
                  <div class="swipe-cell-default-icon">
                    <van-icon v-if="openStates[idx]" name="arrow-double-left" @click.stop="openSwipe(idx)" />
                    <van-icon v-else name="arrow-double-right" @click.stop="closeSwipe(idx)" />
                  </div>
                </div>
              </template>
              <template #right>
                <van-button @click="handleDeptUser(item.clientId)" size="small" type="primary" class="right-button">选择拥有者</van-button>
                <van-button v-if="item.isNormal === 1" @click="handleResetClient(item.clientId)" size="small" type="danger" class="right-button">重置终端状态</van-button>
              </template>
            </van-swipe-cell>
          </div>
        </van-list>
      </van-pull-refresh>
    </div>

  <OrganizationalWithLeafUserOne ref="popupDeptUserRef" @receive-from-child="returnUserInfo" />

  </div>
</template>

<style scoped>

.page-container {
  height: 100vh; /* 关键：外层容器高度设为视口高度 */
  display: flex;
  flex-direction: column;

}
/*  overflow-y: auto; !* 启用垂直滚动 *!*/


.scroll-container {
  flex: 1;
  overflow: auto;
  -webkit-overflow-scrolling: touch; /* iOS 平滑滚动 */
}

/* 可选：隐藏滚动条（视觉优化） */
.scroll-container::-webkit-scrollbar {
  display: none;
}

.card {
  margin: 10px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  background-color: #fff;
}

.label-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.bold-title {
  font-weight: bold;
  color: #333;
}

.swipe-cell-default {
  display: flex;
  background-color: #ffffff;
  justify-content: center;
  align-items: center;
}

.swipe-cell-default-icon {
  width: 60px;
  display: flex;
  justify-content: center;
}


.selected-cell {
  background-color: #f5f7fa;
  border-left: 4px solid #1989fa;
  padding-left: 12px;
}

.right-button {
  height: 100%;
}

</style>
