<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>
          <up-swipe-action>
            <up-swipe-action-item
              ref="swipeItem"
              :options="options"
              v-for="item in list"
              :key="item.keyboardPwdId"
              :threshold="50"
              @click="deleteItem(item)"
            >
              <view class="item" @click="toDetail(item)">
                <view class="item-left rounded-50% bg-#2863f6 flex items-center justify-center">
                  <image
                    class="w-80 h-80"
                    src="/static/images/icon_remote_white.png"
                    mode="aspectFill"
                  ></image>
                </view>
                <view class="item-right">
                  <view style="display: flex; align-items: center">
                    <view class="item-right-top">{{ item.remoteName }}</view>
                    <view class="status">
                      {{ item.statusText }}
                    </view>
                  </view>
                  <view class="item-right-bottom">{{ item.timeText }}</view>
                </view>
              </view>
              <view class="line"></view>
            </up-swipe-action-item>
          </up-swipe-action>
        </view>
      </view>
    </scroll-view>
    <view class="button">
      <view class="button-reset" @click="reset">重置遥控</view>
      <view class="button-create" @click="toCreate">添加遥控</view>
    </view>
  </view>
</template>

<script setup>
  import { onMounted, ref } from 'vue'
  import { timeFormat } from 'uview-plus'
  import { useBasicStore } from '@/stores/basic'
  import { useBluetoothStore } from '@/stores/bluetooth'
  import { useUserStore } from '@/stores/user'
  import { clearRemoteRequest, deleteRemoteRequest, getRemoteList } from '@/api/remote'

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

  const swipeItem = ref(null)

  const searchStr = ref('')
  const list = ref([])
  const pageNo = ref(1)
  const pageSize = 50
  const total = ref(0)
  const lockId = ref(null)

  const deviceInfo = ref(null)
  const requestFinished = ref(false)
  const refresherTriggered = ref(false)
  const options = ref([
    {
      text: '删除',
      style: {
        backgroundColor: '#f56c6c'
      }
    }
  ])

  onMounted(async () => {
    uni.showLoading({
      title: '加载中',
      mask: true
    })
    deviceInfo.value = await $basic.getDeviceInfo()
    lockId.value = $bluetooth.currentLockInfo.lockId
    const { code, message } = await getList({
      pageNo: pageNo.value
    })
    requestFinished.value = true
    uni.hideLoading()
    if (code !== 0) {
      uni.showToast({
        title: message,
        icon: 'none'
      })
    }
  })

  const reset = async () => {
    uni.showModal({
      title: '提示',
      content: '重置后，该锁的遥控都将被删除哦，确认要重置吗？',
      async success(res) {
        if (res.confirm) {
          const netWork = await $basic.getNetworkType()
          if (!netWork) {
            return
          }
          await deleteData({
            operate: 3
          })
        }
      }
    })
  }

  const deleteData = async info => {
    uni.showLoading({
      title: `${info.operate === 2 ? '删除' : '重置'}中`
    })

    const { code } = await $bluetooth.registerAuthentication({
      type: 'remote',
      keyId: $bluetooth.keyId.toString(),
      uid: $user.userInfo.uid.toString(),
      no: Number(info.remoteNumber) || 0,
      operate: info.operate,
      isAdmin: 0,
      isForce: 0,
      userCountLimit: 0,
      weekDays: [],
      isRound: 0,
      startDate: 0,
      endDate: 0,
      startTime: '00:00',
      endTime: '00:00'
    })

    $bluetooth.closeBluetoothConnection()
    if (code === 0) {
      let params = {
        lockId: $bluetooth.currentLockInfo.lockId,
        deleteType: 1,
        type: 1
      }
      if (info.operate === 2) {
        params = {
          ...params,
          remoteId: info.remoteId,
          type: 0
        }
      }
      const { code: requestCode, message } =
        info.operate === 3 ? await clearRemoteRequest(params) : await deleteRemoteRequest(params)
      if (requestCode === 0) {
        if (info.back) {
          $basic.backAndToast(`删除成功`)
        }
        uni.hideLoading()
        uni.showToast({
          title: `${info.operate === 2 ? '删除' : '重置'}成功`,
          icon: 'none'
        })
        pageNo.value = 1
        await getList({
          pageNo: pageNo.value
        })
      } else {
        uni.hideLoading()
        uni.showToast({
          title: message,
          icon: 'none'
        })
      }
    } else if (code === -1) {
      uni.hideLoading()
      uni.showToast({
        title: `${info.operate === 2 ? '删除' : '重置'}失败，请保持在锁附近`,
        icon: 'none'
      })
    }
  }

  const deleteItem = async data => {
    const index = list.value.findIndex(item => item.keyboardPwdId === data.keyboardPwdId)
    swipeItem.value[index].closeHandler()
    uni.showModal({
      title: '提示',
      content: '确定要删除吗？',
      async success(res) {
        if (res.confirm) {
          const netWork = await $basic.getNetworkType()
          if (!netWork) {
            return
          }
          await deleteData({
            ...data,
            operate: 2
          })
        }
      }
    })
  }

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

  const nextPage = async () => {
    if (total.value <= pageNo.value * pageSize) {
      return
    }
    const page = pageNo.value + 1
    const params = {
      searchStr: searchStr.value,
      pageNo: page
    }
    const { code, message } = await getList(params)
    if (code === 0) {
      pageNo.value = page
    } else {
      uni.showToast({
        title: message,
        icon: 'none'
      })
    }
  }

  const getList = async params => {
    const {
      data: { timestamp }
    } = await $bluetooth.updateServerTimestamp()
    const { code, data, message } = await getRemoteList({
      ...params,
      lockId: lockId.value,
      pageSize
    })
    if (code === 0) {
      total.value = data.total
      for (let i = 0; i < data.list.length; i++) {
        if (data.list[i].remoteStatus === 1 && data.list[i].startDate > timestamp) {
          data.list[i].statusText = '未生效'
        } else if (data.list[i].remoteStatus === 2) {
          data.list[i].statusText = '已失效'
        }

        if (data.list[i].remoteType === 1) {
          data.list[i].timeText = timeFormat(data.list[i].startDate, 'yyyy-mm-dd hh:MM') + ' 永久'
        } else if (data.list[i].remoteType === 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({
      searchStr: data,
      pageNo: pageNo.value
    })
    if (code !== 0) {
      uni.showToast({
        title: message,
        icon: 'none'
      })
    }
  }

  const toCreate = () => {
    $basic.routeJump({
      name: 'createRemote',
      events: {
        refresherList() {
          pageNo.value = 1
          getList({
            pageNo: pageNo.value
          })
        }
      }
    })
  }

  const toDetail = item => {
    $basic.routeJump({
      name: 'remoteDetail',
      params: {
        info: JSON.stringify(item)
      },
      events: {
        delete() {
          deleteItem({ ...item, back: true })
        },
        refresherList() {
          pageNo.value = 1
          getList({
            pageNo: pageNo.value
          })
        }
      }
    })
  }
</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>
