<template>
  <view class="container">
    <up-sticky>
      <navbar-back title="设备查询" />
    </up-sticky>
    <view class="content">
      <up-transition :show="!isFold" mode="slide-left">
        <view class="con-left" v-show="!isFold">
          <uni-card style="height: 100%; overflow: auto" title="分类和产品" padding="0" margin="0" spacing="0">
            <DaTree
              ref="DaTreeRef"
              :data="roomTreeData"
              labelField="name"
              valueField="id"
              appendField="modelNo"
              :indent="10"
              @change="handleTreeChange"
            ></DaTree>
          </uni-card>
        </view>
      </up-transition>
      <view class="con-right">
        <uni-card padding="0" margin="10">
          <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-search
              v-model="keyword"
              shape="square"
              placeholder="请输入设备名称或者扫描设备二维码码查询"
              actionText="重置"
              :clearabled="false"
              :showAction="true"
              @change="handleInputSearch"
              @custom="handleReset"
            ></up-search>
          </view>
          <view style="height: 73vh; width: 100%">
            <zb-table
              ref="zbTableRef"
              isShowLoadMore
              stripe
              :fit="false"
              :columns="column"
              :cellStyle="setCellStyle"
              :cellHeaderStyle="setCellHeaderStyle"
              :data="listData"
              @detail="handleDetail"
              @pullUpLoading="pullUpLoadingAction"
            ></zb-table>
          </view>
        </uni-card>
      </view>
    </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([])

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()
  roomTreeData.value = 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>
.u-sticky {
  top: 0 !important;
}
.container {
  background-color: #f0f2f5;
  height: 100%;
  .content {
    display: flex;
    .con-left {
      height: 83vh;
      overflow: scroll;
      margin-top: 10px;
      margin-left: 10px;
      flex: 2;
    }
    .con-right {
      flex: 8;
      overflow: auto;
    }
  }
}
: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>
