<template>
  <view>
    <view class="bg-white mx-4 rounded-md mt-4 text-base">
      <view class="flex items-center p-3" @click="toSelect">
        <view>{{ mode === 'all' ? '开门方式' : '胁迫指纹' }}</view>
        <view v-if="info?.settingValue?.openDoorType" class="ml-a">
          {{
            mode === 'all'
              ? keysType[info.settingValue.openDoorType].name
              : info?.settingValue?.remark
          }}
        </view>
        <view v-else class="ml-a">请选择</view>
        <view class="ml-2"><up-icon name="arrow-right"></up-icon></view>
      </view>
      <view
        v-if="mode === 'all'"
        class="flex items-center p-3 border-t-1 border-t-solid border-t-gray-200"
        @click="openModal"
      >
        <view>家人</view>
        <view class="ml-a break-all max-w-500">
          <view v-if="type === 'edit'">{{ info?.settingValue?.remark }}</view>
          <view v-else>
            <input
              class="w-450 h-60 text-right font-bold text-base"
              :value="remark"
              :maxlength="50"
              placeholder="请输入"
              placeholder-class="text-base line-height-60rpx font-bold text-right"
              @input="updateName"
          /></view>
        </view>
      </view>
    </view>
    <view class="bg-white mx-4 rounded-md mt-4 text-base" @click="toNoticeWay">
      <view class="flex items-center p-3">
        <view>提醒方式</view>
        <view class="ml-a"><up-icon name="arrow-right"></up-icon></view>
      </view>
      <view class="pb-4">
        <view class="flex items-center bg-#f4f4f4 mx-4 py-1 px-2 rounded-md">
          <view>APP推送</view>
          <view class="text-gray-500 ml-a">管理员</view>
        </view>
        <view
          class="flex items-center bg-#f4f4f4 mx-4 py-1 px-2 rounded-md mt-4"
          v-if="
            info?.settingValue?.noticeWay && info?.settingValue?.noticeWay[0]?.accounts.length > 0
          "
        >
          <view>邮件提醒</view>
          <view class="text-sm ml-a text-right">
            <view
              class="text-gray-500"
              v-for="(item, index) in info.settingValue.noticeWay[0].accounts"
              :key="index"
            >
              {{ item.account }}
            </view></view
          >
        </view>
        <view
          class="flex items-center bg-#f4f4f4 mx-4 py-1 px-2 rounded-md mt-4"
          v-if="
            info?.settingValue?.noticeWay && info?.settingValue?.noticeWay[1]?.accounts.length > 0
          "
        >
          <view>短信提醒</view>
          <view class="ml-a text-sm text-right">
            <view
              class="text-gray-500"
              v-for="(item, index) in info.settingValue.noticeWay[1].accounts"
              :key="index"
            >
              {{ item.account }}</view
            >
          </view></view
        >
      </view>
    </view>
    <view
      v-if="type === 'edit'"
      @click="deleteData"
      class="pos-fixed bottom-[calc(env(safe-area-inset-bottom)+48rpx)] w-686 mx-4 h-88 line-height-88rpx text-center bg-#df2a2c text-white rounded-3xl"
      >删除
    </view>
    <view
      v-else
      @click="create"
      class="pos-fixed bottom-[calc(env(safe-area-inset-bottom)+48rpx)] w-686 mx-4 h-88 line-height-88rpx text-center text-white rounded-3xl"
      :class="[canCreate ? 'bg-#4777ee' : 'bg-#9d9ca1']"
      >保存
    </view>
    <ModalInput
      v-if="info"
      ref="modalInput"
      title="修改名字"
      :autoClose="false"
      placeholder="请输入"
      :value="info?.settingValue?.remark"
      @confirm="changeName"
    />
  </view>
</template>

<script setup>
  import { onLoad, onShow } from '@dcloudio/uni-app'
  import { computed, getCurrentInstance, ref } from 'vue'
  import { useBasicStore } from '@/stores/basic'
  import { keysType } from '@/constant/keyType'
  import { addNoticeRequest, deleteNoticeRequest, updateNoticeRequest } from '@/api/setting'
  import { useBluetoothStore } from '@/stores/bluetooth'
  import { useUserStore } from '@/stores/user'

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

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

  const info = ref(null)

  const remark = ref('')

  const type = ref('add')

  const modalInput = ref(null)

  const pending = ref(false)

  const mode = ref('all')

  const flag = ref(false)

  const canCreate = computed(() => {
    return info.value?.settingValue?.openDoorId
  })

  onLoad(options => {
    if (options.title) {
      uni.setNavigationBarTitle({
        title: options.title
      })
    }
    if (JSON.parse(options.info)) {
      info.value = JSON.parse(options.info)
      type.value = 'edit'
    }

    if (options.mode) {
      mode.value = options.mode
    }
  })

  onShow(() => {
    if (flag.value) {
      $user.getUserInfo()
      flag.value = false
    }
  })

  const create = async () => {
    if (pending.value && canCreate) return
    if ($user.userInfo.isVip === 0) {
      uni.showModal({
        title: '提示',
        content: '该功能是高级功能，请开通后在使用',
        confirmText: '去开通',
        success: async res => {
          if (res.confirm) {
            const { code, data, message } = await $user.getWebUrl()
            if (code === 0) {
              $basic.routeJump({
                name: 'webview',
                params: {
                  url: encodeURIComponent(data.vip_buy_url)
                }
              })
              flag.value = true
            } else {
              uni.showToast({
                title: message,
                icon: 'none'
              })
            }
          }
        }
      })
      return
    }
    pending.value = true
    uni.showLoading({
      title: '保存中'
    })
    const { code, message } = await addNoticeRequest({
      lockId: $bluetooth.currentLockInfo.lockId,
      noticeType: mode.value === 'all' ? 10 : 20,
      settingValue: info.value.settingValue
    })
    uni.hideLoading()
    pending.value = false
    if (code === 0) {
      $basic.backAndToast('保存成功')
      eventChannel.emit('refresherList')
    } else if (code === 434) {
      uni.showModal({
        title: '提示',
        content: message,
        showCancel: false
      })
    } else {
      uni.showToast({
        title: message,
        icon: 'none'
      })
    }
  }

  const openModal = () => {
    if (type.value !== 'edit') return
    modalInput.value.open()
  }

  const updateName = e => {
    remark.value = e.detail.value
    info.value = {
      ...info.value,
      settingValue: {
        ...info.value.settingValue,
        remark: e.detail.value
      }
    }
  }

  const deleteData = async () => {
    uni.showModal({
      title: '是否删除家人？',
      content: '删除家人后，你将不会收到他到家的消息',
      confirmText: '删除',
      success: async res => {
        if (res.confirm) {
          if (pending.value) return
          pending.value = true
          uni.showLoading({
            title: '删除中'
          })
          const { code, message } = await deleteNoticeRequest({
            lockNoticeSettingAccountId: info.value.id
          })
          uni.hideLoading()
          pending.value = false
          if (code === 0) {
            $basic.backAndToast('删除成功')
            eventChannel.emit('refresherList')
          } else {
            uni.showToast({
              title: message,
              icon: 'none'
            })
          }
        }
      }
    })
  }

  const toNoticeWay = () => {
    $basic.routeJump({
      name: 'noticeWay',
      params: {
        info: info.value?.settingValue ? JSON.stringify(info.value.settingValue) : null
      },
      events: {
        async confirm(data) {
          if (type.value === 'add') {
            info.value = {
              settingValue: {
                ...(info.value?.settingValue || {}),
                noticeWay: data.noticeWay
              }
            }
            uni.navigateBack()
            return
          }

          if (pending.value) return
          pending.value = true
          uni.showLoading({
            title: '更新中'
          })
          const params = {
            lockNoticeSettingAccountId: info.value.id,
            settingValue: {
              ...info.value.settingValue,
              noticeWay: data.noticeWay
            }
          }
          const { code, message } = await updateNoticeRequest(params)
          uni.hideLoading()
          pending.value = false
          if (code === 0) {
            info.value = {
              ...info.value,
              settingValue: params.settingValue
            }
            $basic.backAndToast('更新成功')
            eventChannel.emit('refresherList')
          } else {
            uni.showToast({
              title: message,
              icon: 'none'
            })
          }
        }
      }
    })
  }

  const changeName = async name => {
    if (pending.value) return
    pending.value = true
    uni.showLoading({
      title: '更新中'
    })
    const params = {
      lockNoticeSettingAccountId: info.value.id,
      settingValue: {
        ...info.value.settingValue,
        remark: name
      }
    }
    const { code, message } = await updateNoticeRequest(params)
    uni.hideLoading()
    pending.value = false
    if (code === 0) {
      modalInput.value.close()
      info.value = {
        ...info.value,
        settingValue: params.settingValue
      }
      uni.showToast({
        title: '更新成功',
        icon: 'none'
      })
      eventChannel.emit('refresherList')
    } else {
      uni.showToast({
        title: message,
        icon: 'none'
      })
    }
  }

  const toSelect = () => {
    $basic.routeJump({
      name: mode.value === 'all' ? 'lockUser' : 'coercionFingerprint',
      params: {
        info: info.value?.settingValue ? JSON.stringify(info.value.settingValue) : null
      },
      events: {
        async confirm(data) {
          if (type.value === 'add') {
            info.value = {
              settingValue: {
                ...(info.value?.settingValue || {}),
                openDoorId: data.id,
                openDoorType: data.type,
                remark: data.name
              }
            }
            remark.value = data.name
            uni.navigateBack()
            return
          }

          if (pending.value) return
          pending.value = true
          uni.showLoading({
            title: '更新中'
          })
          const params = {
            lockNoticeSettingAccountId: info.value.id,
            settingValue: {
              ...info.value.settingValue,
              openDoorId: data.id,
              openDoorType: data.type,
              remark: data.name
            }
          }
          const { code, message } = await updateNoticeRequest(params)
          uni.hideLoading()
          pending.value = false
          if (code === 0) {
            info.value = {
              ...info.value,
              settingValue: params.settingValue
            }
            $basic.backAndToast('更新成功')
            eventChannel.emit('refresherList')
          } else if (code === 434) {
            uni.showModal({
              title: '提示',
              content: message,
              showCancel: false
            })
          } else {
            uni.showToast({
              title: message,
              icon: 'none'
            })
          }
        }
      }
    })
  }
</script>

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