<template>
  <view>
    <scroll-view
      v-if="deviceInfo"
      scroll-y="true"
      :style="{ height: deviceInfo.screenHeight - deviceInfo.safeArea.top + 'px' }"
      lower-threshold="100"
      @refresherrefresh="refresherList"
      :refresher-enabled="true"
      @scrolltolower="nextPage"
      :refresher-triggered="refresherTriggered"
    >
      <view class="search">
        <up-search
          shape="square"
          :searchIconSize="48"
          :inputStyle="{ fontSize: '32rpx' }"
          :height="80"
          placeholder="搜索"
          :clearabled="false"
          @change="changeSearch"
          v-model="searchStr"
          bgColor="#ffffff"
          :showAction="false"
          maxlength="50"
        ></up-search>
      </view>
      <view style="padding: 0 0 calc(env(safe-area-inset-bottom) + 250rpx) 0">
        <view v-if="list.length === 0 && requestFinished">
          <image
            class="empty-list"
            src="/static/images/background_empty_list.png"
            mode="aspectFill"
          ></image>
          <view class="empty-list-text">暂无数据</view>
        </view>
        <view v-else>
          <view v-for="(item, index) in list" :key="index">
            <view class="item" @click="change(item)">
              <image
                class="item-left"
                :src="keysType[item.openLockType].icon"
                mode="aspectFit"
              ></image>
              <view class="item-right">
                <view style="display: flex; align-items: center">
                  <view class="item-right-top">{{ item?.name }}</view>
                </view>
                <view class="item-right-bottom">{{ item?.timeText }}</view>
              </view>
              <view class="ml-a mr-4">
                <image
                  class="w-40 h-40"
                  v-if="info?.id === item.id && info?.openLockType === item.openLockType"
                  src="/static/images/icon_select.png"
                ></image>
                <image v-else class="w-40 h-40" src="/static/images/icon_not_select.png"></image>
              </view>
            </view>
            <view class="line"></view>
          </view>
        </view>
      </view>
    </scroll-view>
    <view
      v-if="list.length > 0"
      @click="confirm"
      class="pos-fixed bottom-[calc(env(safe-area-inset-bottom)+48rpx)] w-686 mx-4 h-88 line-height-88rpx text-center bg-#63b8af text-white rounded-3xl"
      >确定
    </view>
  </view>
</template>

<script setup>
  import { getCurrentInstance, ref } from 'vue'
  import { timeFormat } from 'uview-plus'
  import { onLoad } from '@dcloudio/uni-app'
  import { useBasicStore } from '@/stores/basic'
  import { useBluetoothStore } from '@/stores/bluetooth'
  import { keysType } from '@/constant/keyType'
  import { getCoercedListRequest } from '@/api/fingerprint'

  const instance = getCurrentInstance().proxy
  const eventChannel = instance.getOpenerEventChannel()

  const $basic = useBasicStore()
  const $bluetooth = useBluetoothStore()

  const searchStr = ref('')
  const list = ref([])
  const lockId = ref(null)

  const deviceInfo = ref(null)
  const requestFinished = ref(false)

  const info = ref(null)

  const pageSize = 50
  const pageNo = ref(1)
  const total = ref(0)

  const refresherTriggered = ref(false)

  onLoad(async options => {
    if (JSON.parse(options.info)) {
      info.value = JSON.parse(options.info)
      info.value = {
        ...info.value,
        name: info.value.remark,
        openLockType: info.value.openDoorType,
        id: info.value.openDoorId
      }
    }
    uni.showLoading({
      title: '加载中',
      mask: true
    })
    deviceInfo.value = await $basic.getDeviceInfo()
    lockId.value = $bluetooth.currentLockInfo.lockId
    const { code, message } = await getList({
      pageNo: pageNo.value,
      searchStr: searchStr.value
    })
    requestFinished.value = true
    uni.hideLoading()
    if (code !== 0) {
      uni.showToast({
        title: message,
        icon: 'none'
      })
    }
  })

  const refresherList = async () => {
    refresherTriggered.value = true
    pageNo.value = 1
    const { code } = await getList({
      pageNo: pageNo.value,
      searchStr: searchStr.value
    })
    if (code === 0) {
      uni.showToast({
        title: '刷新成功',
        icon: 'none'
      })
    }
    refresherTriggered.value = false
  }

  const nextPage = async () => {
    if (total.value <= pageNo.value * pageSize) {
      return
    }
    const no = pageNo.value + 1
    const { code } = await getList(no, false)
    if (code === 0) {
      pageNo.value = no
    }
  }

  const confirm = () => {
    if (info.value) {
      eventChannel.emit('confirm', {
        id: info.value.id,
        type: info.value.openLockType,
        name: info.value.name
      })
    }
  }

  const getList = async params => {
    const { code, data, message } = await getCoercedListRequest({
      lockId: lockId.value,
      pageSize,
      ...params
    })
    if (code === 0) {
      total.value = data.total
      for (let i = 0; i < data.list.length; i++) {
        data.list[i].openLockType = 3
        data.list[i].name = data.list[i].fingerprintName
        data.list[i].id = data.list[i].fingerprintId
        if (data.list[i].fingerprintType === 1) {
          data.list[i].timeText = timeFormat(data.list[i].createDate, 'yyyy-mm-dd hh:MM') + ' 永久'
        } else if (data.list[i].fingerprintType === 2) {
          data.list[i].timeText =
            timeFormat(data.list[i].startDate, 'yyyy-mm-dd hh:MM') +
            ' - ' +
            timeFormat(data.list[i].endDate, 'yyyy-mm-dd hh:MM') +
            ' 限时'
        } else {
          data.list[i].timeText =
            timeFormat(data.list[i].startDate, 'yyyy-mm-dd') +
            ' - ' +
            timeFormat(data.list[i].endDate, 'yyyy-mm-dd') +
            ' 循环'
        }
      }
      if (params.pageNo === 1) {
        list.value = data.list
      } else {
        list.value = list.value.concat(data.list)
      }
      return { code }
    }
    return { code, message }
  }

  const changeSearch = async data => {
    pageNo.value = 1
    const { code, message } = await getList({
      pageNo: pageNo.value,
      searchStr: data
    })
    if (code !== 0) {
      uni.showToast({
        title: message,
        icon: 'none'
      })
    }
  }

  const change = item => {
    info.value = item
  }
</script>

<style lang="scss">
  page {
    background-color: $uni-bg-color-grey;
  }
</style>

<style lang="scss" scoped>
  .search {
    padding: 32rpx;
    width: 686rpx !important;
  }

  .button {
    display: flex;
    align-items: center;
    position: fixed;
    bottom: calc(env(safe-area-inset-bottom) + 20rpx);
    font-weight: bold;

    .button-reset {
      margin-left: 50rpx;
      width: 300rpx;
      height: 88rpx;
      background-color: #df282d;
      color: white;
      text-align: center;
      line-height: 88rpx;
      border-radius: 44rpx;
    }

    .button-create {
      margin-left: 50rpx;
      width: 300rpx;
      height: 88rpx;
      background-color: #63b8af;
      color: white;
      text-align: center;
      line-height: 88rpx;
      border-radius: 44rpx;
    }
  }

  .item {
    display: flex;
    align-items: center;
    background-color: #ffffff;
    height: 120rpx;
    width: 750rpx;

    .item-left {
      margin-left: 32rpx;
      width: 80rpx;
      height: 80rpx;
    }

    .item-right {
      margin-right: 32rpx;
      margin-left: 32rpx;
      width: 574rpx;

      .item-right-top {
        max-width: 400rpx;
        font-size: 32rpx;
        font-weight: bold;
        padding-bottom: 6rpx;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .item-right-bottom {
        font-size: 24rpx;
        color: #999999;
      }
    }
  }

  .line {
    width: 100%;
    height: 2rpx;
    background: #ebebeb;
  }

  .empty-list {
    width: 150rpx;
    height: 150rpx;
    margin: 300rpx auto 20rpx 50%;
    transform: translateX(-50%);
  }

  .empty-list-text {
    text-align: center;
    font-size: 32rpx;
    color: #999999;
  }

  .status {
    margin-left: auto;
    font-size: 26rpx;
    color: #df282d;
  }
</style>
