<template>
  <navbar-back title="设备查询" />
  <view class="container">
    <up-transition :show="!isFold" mode="slide-left">
      <view class="con-left" v-show="!isFold">
        <view class="border-b p8 pl16 font-bold"> 分类和产品 </view>
        <DaTree
          style="height: 95%"
          ref="DaTreeRef"
          :data="roomTreeData"
          labelField="name"
          valueField="id"
          appendField="modelNo"
          :indent="10"
          @change="handleTreeChange"
        ></DaTree>
      </view>
    </up-transition>
    <view class="con-right">
      <view class="p10 x-f" style="width: 60%">
        <image
          class="mr15"
          style="width: 30px; height: 30px"
          :src="`/static/images/${isFold ? 'zhedie2' : 'zhedie1'}.png`"
          @click="isFold = !isFold"
        ></image>
        <up-input v-model="keyword" placeholder="请输入设备名称或者扫描设备二维码码查询" @change="handleInputSearch"
          ><template #suffix> <up-icon name="scan" size="30" @click="handleScan"></up-icon> </template
        ></up-input>
        <up-button class="ml10" style="width: 50px; height: 35px" type="primary" @click="handleReset">重置</up-button>
      </view>
      <zb-table
        style="height: 90%"
        ref="zbTableRef"
        isShowLoadMore
        stripe
        :fit="false"
        :columns="column"
        :cellStyle="setCellStyle"
        :cellHeaderStyle="setCellHeaderStyle"
        :data="listData"
        @detail="handleDetail"
        @pullUpLoading="pullUpLoadingAction"
      ></zb-table>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, watch, computed, toRefs } from 'vue'
import DaTree from '@/components/da-tree/index.vue'
import { onShow } from '@dcloudio/uni-app'
import { setCellHeaderStyle, setCellStyle } from '@/nx/config/zbTable'
import { useListData } from '@/nx/hooks/usePageListData'
import { throttle } from '@/uview-plus'
import { getColumn } from './deviceBusInfo.data'
import { deviceList, treeData, getDeviceBusInfoById } from '@/nx/api/deviceInfo'
import { useScreenOrientation } from '@/nx/hooks/useScreenOrientation'
import nx from '@/nx'

const column = computed(() => getColumn(isFold.value))
const isFold = ref(false)
const roomTreeData = ref([])

function handleScan() {
  uni.scanCode({
    onlyFromCamera: true,
    success: function (res) {
      const codeObj = JSON.parse(res.result)
      handleDetail({ id: codeObj.id })
    }
  })
}
// const { scanQRInfo } = toRefs(nx.$store('biz'))
// watch(scanQRInfo, newVal => {
//   if (newVal && nx.$router.getCurrentPage().route == 'pages/device/deviceBusInfo/index') {
//     try {
//       const codeObj = JSON.parse(newVal)
//       handleDetail({ id: codeObj.id })
//       scanQRInfo.value = ''
//     } catch (error) {
//       scanQRInfo.value = ''
//       uni.showToast({
//         title: '请扫描设备码',
//         icon: 'none'
//       })
//     }
//   }
// })
// onShow(() => {
//   scanQRInfo.value = ''
// })
async function getTreeData() {
  const res = await treeData()
  console.log(res)

  roomTreeData.value = nx.$helper.handleTree([...res])
}
getTreeData()
const { lockOrientation } = useScreenOrientation()
onMounted(async () => {
  lockOrientation('landscape')
  await getInitData()
  console.log('listData', listData.value)
})
const searchParams = computed(() => {
  const params = {
    deviceName: keyword.value
  }
  if (selectedNode.value) {
    params.productId = selectedNode.value.key
  }
  return params
})
const { listData, loadingData, scrollToLower, loadStatus, getInitData } = useListData({
  searchParams,
  api: deviceList,
  processData: data => {
    return data.map(item => {
      const statuses = [
        item.repairFlag == 1 && '维修',
        item.demoteFlag == 1 && '降级',
        item.scrapFlag == 1 && '报废',
        item.disableFlag == 1 && '停用',
        item.lendFlag == 1 && '外借'
      ].filter(Boolean) // 去掉 false 值

      if (item.acceptFlag != 'finished') {
        item.deviceStatus = '--'
      } else {
        item.deviceStatus = statuses.length > 0 ? statuses.join('、') : '正常'
      }
      if (item.inUseFlag == '1') {
        item.inUseFlag = '是'
      } else {
        item.inUseFlag = '否'
      }
      return item
    })
  }
})

let zbTableRef = ref()
function pullUpLoadingAction() {
  if (loadingData.value) return
  if (loadStatus.value === 'nomore') {
    zbTableRef.value.pullUpCompleteLoading('ok')
  } else {
    scrollToLower()
  }
}
let selectedNode = ref(null)
let DaTreeRef = ref()
function handleTreeChange(allCheckedKeys, currentItem) {
  console.log(allCheckedKeys, currentItem)

  selectedNode.value = currentItem
  getInitData()
}
let keyword = ref('')
function handleInputSearch() {
  if (!keyword.value) return
  throttle(getInitData, 500)
}
function handleReset() {
  keyword.value = ''
  if (selectedNode.value) {
    DaTreeRef.value.setCheckedKeys(selectedNode.value.key, false)
  }
  selectedNode.value = ''
  getInitData()
}
async function handleDetail(row, index) {
  nx.$store('biz').deviceInfo = row
  await getDeviceBusInfoById(row.id)
  nx.$router.go('/pages/device/deviceBusInfo/baseInfo')
}
</script>

<style lang="scss" scoped>
.container {
  background-color: #f0f2f5;
  height: calc(100vh - 77px);
  display: flex;
  padding: 10px;
  box-sizing: border-box;
  .con-left,
  .con-right {
    background-color: #fff;
    box-shadow: rgba(0, 0, 0, 0.08) 0px 0px 3px 1px;
    height: 100%;
    border-radius: 5px;
  }
  .con-left {
    padding-left: 8px;
    margin-right: 10px;
    flex: 2;
  }
  .con-right {
    flex: 8;
  }
}
:deep(.zb-table uni-button[type='primary']) {
  background-color: $uni-color-primary !important;
}
:deep(.u-search__action--active) {
  padding: 5px;
  border-radius: 3px;
  background: #0055a2;
  color: #fff;
}
</style>
