<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="passwordSearch.searchStr" bgColor="#ffffff" :showAction="false" maxlength="20"></up-search>
      </view>
      <view style="padding: 32rpx 0 calc(env(safe-area-inset-bottom) + 250rpx) 0">
        <view v-if="passwordList.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="(password, index) in passwordList"
                                  :key="password.keyboardPwdId" :threshold="50" @click="deletePassword(password)">
              <view class="password" @click="toPasswordDetail(password)">
                <image class="password-left" src="/static/images/icon_lock_transparent.png" mode="aspectFill"></image>
                <view class="password-right">
                  <view style="display: flex; align-items: center">
                    <view class="password-right-top">{{ password.keyboardPwdName }}</view>
                    <view class="key-status">
                      {{ getPasswordStatus(password.keyboardPwdStatus) }}
                    </view>
                  </view>
                  <view class="password-right-bottom">{{ password.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="resetPassword">重置密码</view>
      <view class="button-create" @click="toCreatePassword">获取密码</view>
    </view>
  </view>
</template>

<script>
import { useBasicStore } from '@/stores/basic'
import { mapActions, mapState } from 'pinia'
import { useBluetoothStore } from '@/stores/bluetooth'
import { useLockStore } from '@/stores/lock'
import { useUserStore } from '@/stores/user'
import { deletePsaawordRequest, resetPsaawordListRequest } from '@/api/keyboardPwd'

export default {
  data () {
    return {
      deviceInfo: null,
      refresherTriggered: false,
      requestFinished: false,
      options: [{
        text: '删除',
        style: {
          backgroundColor: '#f56c6c'
        }
      }]
    }
  },
  computed: {
    ...mapState(useUserStore, ['userInfo']),
    ...mapState(useBluetoothStore, ['currentLockInfo', 'keyId']),
    ...mapState(useLockStore, ['passwordTotal', 'passwordList', 'passwordSearch']),
  },
  async onLoad() {
    uni.showLoading({
      title: '加载中',
      mask: true
    })
    this.deviceInfo = await this.getDeviceInfo()
    this.updatePasswordSearch({
      ...this.passwordSearch,
      lockId: this.currentLockInfo.lockId,
      lockStatus: this.currentLockInfo.lockStatus
    })
    const { code, meesage } = await this.getPasswordList(this.passwordSearch)
    this.requestFinished = true
    uni.hideLoading()
  },
  methods: {
    ...mapActions(useBasicStore, ['routeJump', 'getDeviceInfo']),
    ...mapActions(useLockStore, ['getPasswordList', 'updateCurrentPasswordInfo', 'updatePasswordSearch', 'getPasswordStatus']),
    ...mapActions(useBluetoothStore, ['resetLockPassword', 'setLockPassword']),
    toPasswordDetail(password) {
      this.updateCurrentPasswordInfo(password)
      this.routeJump({
        name: 'passwordDetail'
      })
    },
    async deletePassword(data) {
      const password = data
      const that = this
      let index = this.passwordList.findIndex(item => item.keyboardPwdId === password.keyboardPwdId)
      that.$refs.swipeItem[index].closeHandler()
      uni.showModal({
        title: '提示',
        content: '确定要删除该密码',
        async success(res) {
          if(res.confirm) {
            uni.showLoading({
              title: '删除中',
              mask: true
            })
            const timestamp = parseInt(new Date().getTime() / 1000)
            const { code } = await that.setLockPassword({
              keyId: that.keyId.toString(),
              uid: that.userInfo.uid.toString(),
              pwdNo: password.pwdUserNo,
              operate: 3,
              isAdmin: password.pwdRight,
              pwd: password.keyboardPwd,
              userCountLimit: 0xFFFF,
              startTime: timestamp,
              endTime: timestamp
            })
            if(code === 0) {
              const { code: requestCode, message } = await deletePsaawordRequest({
                lockId: that.currentLockInfo.lockId,
                keyboardPwdId: password.keyboardPwdId,
                deleteType: 1
              })
              if(requestCode === 0) {
                uni.hideLoading()
                uni.showToast({
                  title: '删除成功',
                  icon: 'none'
                })
                that.updatePasswordSearch({
                  ...that.passwordSearch,
                  pageNo: 1
                })
                await that.getPasswordList(that.passwordSearch)
              } else {
                uni.hideLoading()
                uni.showToast({
                  title: message,
                  icon: 'none'
                })
              }
            } else {
              uni.hideLoading()
              uni.showToast({
                title: '删除失败，请保持在锁附近',
                icon: 'none'
              })
            }
          }
        }
      })
    },
    async resetPassword() {
      const that = this
      uni.showModal({
        title: '提示',
        content: '确定要重置密码，该锁的所有密码都将被删除',
        async success(res) {
          if(res.confirm) {
            const { code } = await that.resetLockPassword({
              uid: that.userInfo.uid.toString(),
              keyId: that.currentLockInfo.keyId.toString()
            })
            if(code === 0) {
              const { code: requestCode, message } = await resetPsaawordListRequest({
                lockId: that.currentLockInfo.lockId,
                passwordKey: that.currentLockInfo.bluetooth.passwordKey
              })
              console.log('重置密码返回', requestCode, message)
              if(requestCode === 0) {
                uni.showToast({
                  title: '重置密码成功',
                  icon: 'none'
                })
                that.updatePasswordSearch({
                  ...that.passwordSearch,
                  pageNo: 1
                })
                that.getPasswordList(that.passwordSearch)
              } else {
                uni.showToast({
                  title: message,
                  icon: 'none'
                })
              }
            } else {
              uni.showToast({
                title: '重置密码失败，请保持在锁附近',
                icon: 'none'
              })
            }
          }
        }
      })
    },
    toCreatePassword() {
      this.routeJump({
        name: 'createPassword'
      })
    },
    async refresherList() {
      this.refresherTriggered = true
      this.updatePasswordSearch({
        ...this.passwordSearch,
        pageNo: 1
      })
      const { code, meesage } = await this.getPasswordList(this.passwordSearch)
      if(code === 0) {
        uni.showToast({
          title: '刷新成功',
          icon: 'none'
        })
      }
      this.refresherTriggered = false
    },
    async nextPage() {
      if(this.passwordTotal <= this.passwordSearch.pageNo * this.passwordSearch.pageSize) {
        return
      }
      const pageNo = this.passwordSearch.pageNo + 1
      const params = {
        ...this.passwordSearch,
        pageNo
      }
      const { code, meesage } = await this.getPasswordList(params)
      if(code === 0) {
        that.updatePasswordSearch({
          ...that.passwordSearch,
          pageNo
        })
      }
    },
    async changeSearch(data) {
      this.updatePasswordSearch({
        ...this.passwordSearch,
        searchStr: data
      })
      const { code, meesage } = await this.getPasswordList(this.passwordSearch)
    },
  },
}
</script>

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

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

.button {
  display: flex;
  align-items: center;
  position: fixed;
  bottom: calc(env(safe-area-inset-bottom) + 48rpx);
  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;
  }
}

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

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

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

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

    .password-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;
}

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