<template>
  <view>
    <scroll-view
      v-if="deviceInfo"
      scroll-y="true"
      :style="{ height: deviceInfo.screenHeight - deviceInfo.safeArea.top + 'px' }"
      lower-threshold="100"
    >
      <view class="search">
        <up-search
          shape="square"
          searchIconSize="48rpx"
          :inputStyle="{ fontSize: '32rpx' }"
          height="80rpx"
          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="https://oss-lock.xhjcn.ltd/mp/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="https://oss-lock.xhjcn.ltd/mp/icon_select.png"
                ></image>
                <image
                  v-else
                  class="w-40 h-40"
                  src="https://oss-lock.xhjcn.ltd/mp/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 { lockUserListRequest } from '@/api/lock'
  import { keysType } from '@/constant/keyType'

  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)

  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({
      searchStr: searchStr.value
    })
    requestFinished.value = true
    uni.hideLoading()
    if (code !== 0) {
      uni.showToast({
        title: message,
        icon: 'none'
      })
    }
  })

  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 lockUserListRequest({
      ...params,
      lockId: lockId.value
    })
    if (code === 0) {
      const result = []
      for (let i = 0; i < data.length; i++) {
        if (data[i].openLockType === 1) {
          for (let j = 0; j < data[i].keys.length; j++) {
            data[i].keys[j].openLockType = data[i].openLockType
            data[i].keys[j].name = data[i].keys[j].keyName
            if (data[i].keys[j].keyType === 1) {
              data[i].keys[j].timeText =
                `${timeFormat(new Date(data[i].keys[j].created_at), 'yyyy-mm-dd h:M')} 永久`
            } else if (data[i].keys[j].keyType === 2) {
              data[i].keys[j].timeText =
                `${timeFormat(new Date(data[i].keys[j].startDate), 'yyyy-mm-dd h:M')} - ${timeFormat(new Date(data[i].keys[j].endDate), 'yyyy-mm-dd h:M')} 限时`
            } else if (data[i].keys[j].keyType === 3) {
              data[i].keys[j].timeText =
                `${timeFormat(new Date(data[i].keys[j].created_at), 'yyyy-mm-dd h:M')} 单次`
            } else {
              data[i].keys[j].timeText = `循环`
            }
          }
        }
        if (data[i].openLockType === 2) {
          for (let j = 0; j < data[i].keys.length; j++) {
            data[i].keys[j].openLockType = data[i].openLockType
            data[i].keys[j].name = data[i].keys[j].keyboardPwdName
            data[i].keys[j].id = data[i].keys[j].keyboardPwdId
            if (data[i].keys[j].keyboardPwdType === 2) {
              data[i].keys[j].timeText =
                `${timeFormat(new Date(data[i].keys[j].created_at), 'yyyy-mm-dd h:M')} 永久`
            } else if (data[i].keys[j].keyboardPwdType === 3) {
              data[i].keys[j].timeText = `${data[i].keys[j].validTimeStr} 限时`
            } else {
              let text = ''
              if (data[i].keys[j].keyboardPwdType === 5) {
                text = '周末'
              } else if (data[i].keys[j].keyboardPwdType === 6) {
                text = '每日'
              } else if (data[i].keys[j].keyboardPwdType === 7) {
                text = '工作日'
              } else if (data[i].keys[j].keyboardPwdType === 8) {
                text = '周一'
              } else if (data[i].keys[j].keyboardPwdType === 9) {
                text = '周二'
              } else if (data[i].keys[j].keyboardPwdType === 10) {
                text = '周三'
              } else if (data[i].keys[j].keyboardPwdType === 11) {
                text = '周四'
              } else if (data[i].keys[j].keyboardPwdType === 12) {
                text = '周五'
              } else if (data[i].keys[j].keyboardPwdType === 13) {
                text = '周六'
              } else if (data[i].keys[j].keyboardPwdType === 14) {
                text = '周日'
              }
              data[i].keys[j].timeText =
                `${text} ${data[i].keys[j].hoursStart}:00-${data[i].keys[j].hoursEnd}:00 循环`
            }
          }
        }
        if (data[i].openLockType === 3) {
          for (let j = 0; j < data[i].keys.length; j++) {
            data[i].keys[j].openLockType = data[i].openLockType
            data[i].keys[j].name = data[i].keys[j].fingerprintName
            data[i].keys[j].id = data[i].keys[j].fingerprintId
            if (data[i].keys[j].fingerprintType === 1) {
              data[i].keys[j].timeText =
                timeFormat(data[i].keys[j].createDate, 'yyyy-mm-dd hh:MM') + ' 永久'
            } else if (data[i].keys[j].fingerprintType === 2) {
              data[i].keys[j].timeText =
                timeFormat(data[i].keys[j].startDate, 'yyyy-mm-dd hh:MM') +
                ' - ' +
                timeFormat(data[i].keys[j].endDate, 'yyyy-mm-dd hh:MM') +
                ' 限时'
            } else {
              data[i].keys[j].timeText =
                timeFormat(data[i].keys[j].startDate, 'yyyy-mm-dd') +
                ' - ' +
                timeFormat(data[i].keys[j].endDate, 'yyyy-mm-dd') +
                ' 循环'
            }
          }
        }
        if (data[i].openLockType === 4) {
          for (let j = 0; j < data[i].keys.length; j++) {
            data[i].keys[j].openLockType = data[i].openLockType
            data[i].keys[j].name = data[i].keys[j].cardName
            data[i].keys[j].id = data[i].keys[j].cardId
            if (data[i].keys[j].cardType === 1) {
              data[i].keys[j].timeText =
                timeFormat(data[i].keys[j].createDate, 'yyyy-mm-dd hh:MM') + ' 永久'
            } else if (data[i].keys[j].cardType === 2) {
              data[i].keys[j].timeText =
                timeFormat(data[i].keys[j].startDate, 'yyyy-mm-dd hh:MM') +
                ' - ' +
                timeFormat(data[i].keys[j].endDate, 'yyyy-mm-dd hh:MM') +
                ' 限时'
            } else {
              data[i].keys[j].timeText =
                timeFormat(data[i].keys[j].startDate, 'yyyy-mm-dd') +
                ' - ' +
                timeFormat(data[i].keys[j].endDate, 'yyyy-mm-dd') +
                ' 循环'
            }
          }
        }
        if (data[i].openLockType === 5) {
          for (let j = 0; j < data[i].keys.length; j++) {
            data[i].keys[j].openLockType = data[i].openLockType
            data[i].keys[j].name = data[i].keys[j].faceName
            data[i].keys[j].id = data[i].keys[j].faceId
            if (data[i].keys[j].faceType === 1) {
              data[i].keys[j].timeText =
                timeFormat(data[i].keys[j].createDate, 'yyyy-mm-dd hh:MM') + ' 永久'
            } else if (data[i].keys[j].faceType === 2) {
              data[i].keys[j].timeText =
                timeFormat(data[i].keys[j].startDate, 'yyyy-mm-dd hh:MM') +
                ' - ' +
                timeFormat(data[i].keys[j].endDate, 'yyyy-mm-dd hh:MM') +
                ' 限时'
            } else {
              data[i].keys[j].timeText =
                timeFormat(data[i].keys[j].startDate, 'yyyy-mm-dd') +
                ' - ' +
                timeFormat(data[i].keys[j].endDate, 'yyyy-mm-dd') +
                ' 循环'
            }
          }
        }
        result.push(...data[i].keys)
      }
      console.log(result)
      list.value = result
      return { code }
    }
    return { code, message }
  }

  const changeSearch = async data => {
    const { code, message } = await getList({
      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 {
    width: 686rpx !important;
    padding: 32rpx;
  }

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

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

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

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

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

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

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

      .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 {
    font-size: 32rpx;
    color: #999999;
    text-align: center;
  }

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