<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'

import { useUserStore } from '@/store'
import { storeToRefs } from 'pinia'
import hud from '@/utils/hud'
import router from '@/router/router'
import { useBadgeStore } from '@/store/badge'
import { manualBindApi } from '@/api'
import { useDeviceStore } from '@/store/device'

const { getUserInfo } = useUserStore()
const deviceStore = useDeviceStore()
const { getDevices } = deviceStore
const { devices } = storeToRefs(deviceStore)
const { refreshBadge } = useBadgeStore()
const OSS_URL = import.meta.env.VITE_OSS_HOST
const scanQr = `${OSS_URL}/iconfont/scan_qr.png`
const arrow = `${OSS_URL}/iconfont/down_arrow.png`
const checked = `${OSS_URL}/iconfont/checked.png`
const unchecked = `${OSS_URL}/iconfont/unchecked.png`
const showAllDevice = ref(false)
const defaultAvatar = `${OSS_URL}/urm/default_avatar.png`

// 手动绑定弹框相关
const showHandBindPopup = ref(false)
const childAccount = ref('')

const functionList = reactive([
  {
    name: '一键锁屏',
    bg: `${OSS_URL}/urm/home_lock_screen.png`,
    developingBg: '',
    developing: false,
    type: 0,
  },
  {
    name: '桌面预览',
    bg: `${OSS_URL}/urm/home_desktop_preview.png`,
    developingBg: '',
    developing: false,
    type: 1,
  },
  // {
  //   name: '时间管控',
  //   bg: `${OSS_URL}/urm/home_time_control.png`,
  //   developingBg: '',
  //   developing: false,
  //   type: 2,
  // },
  // {
  //   name: '视频通话',
  //   bg: `${OSS_URL}/urm/home_video_call.png`,
  //   developingBg: `${OSS_URL}/urm/home_video_developing.png`,
  //   developing: true,
  //   type: 3,
  // },
])
const showDevice = ref()

// 选择设备
function chooseEquipment(i: any) {
  showDevice.value = i
}

// 扫码绑定
function scanBind() {
  router.navigateTo('/pages/home/bindDevice/index')
}

// 手动绑定
function handBind() {
  showHandBindPopup.value = true
  childAccount.value = ''
}

// 确认手动绑定
function confirmHandBind() {
  if (!childAccount.value.trim()) {
    hud.error('请输入孩子账号')
    return
  }

  hud.load({
    task: async () => {
      const res = Number(await manualBindApi(childAccount.value))
      if (res === 1) {
        hud.success('绑定成功')
      } else if (res === 0) {
        hud.error('绑定失败')
      } else if (res === 2) {
        hud.success('已向管理员发送绑定请求')
      }
      showHandBindPopup.value = false
    },
    option: '绑定',
  })
}

// 底部点击
function change(i: any) {
  if (devices.value.length === 0) {
    router.navigateTo('/pages/home/bindDevice/index')
    return
  }
  if (i.developing) return
  switch (i.type) {
    case 0:
      // 一键锁屏
      router.navigateTo({
        path: '/pages/home/LockScreen/index',
        query: {
          simSerialNumber: showDevice.value.simSerialNumber,
        },
      })
      break
    case 1:
      // 桌面预览
      router.navigateTo({
        path: '/pages/home/DesktopPreview/index',
        query: {
          simSerialNumber: showDevice.value.simSerialNumber,
        },
      })
      break
    case 2:
      // 时间管控
      router.navigateTo({
        path: '/pages/home/TimeManagement/index',
        query: {
          simSerialNumber: showDevice.value.simSerialNumber,
        },
      })
      break
    case 3:
      // 视频通话
      console.log('视频通话')
      break
  }
}

onShow(() => {
  Promise.all([getDevices(), refreshBadge()])
    .then(() => {
      if (!devices.value?.length) return
      showDevice.value = devices.value[0]
    })
    .finally(() => {
      hud.hide()
    })
})

onLoad(async () => {
  await getUserInfo()
})

onMounted(() => {
  hud.loading()
})
</script>

<template>
  <mj-page class="teacher-content">
    <!-- <view v-if="equipmentList.length === 0" class="binding">
      <image class="scan" :src="scanQr" mode=""></image>扫码绑定设备
    </view> -->
    <view class="my_equipment">
      <view class="header">
        <text>我的设备</text>
        <image
          v-if="devices.length > 1"
          :src="arrow"
          mode=""
          :class="{ arrow_icon: true, rotate: showAllDevice }"
          @click="showAllDevice = !showAllDevice"
        ></image>
      </view>
      <view v-if="!showAllDevice && devices.length" class="equipment_item">
        <view class="equipment_item_right">
          <view class="avatar">
            <image :src="showDevice?.lastLoginUser?.avatar || defaultAvatar" mode=""></image>
          </view>
          <view class="right">
            <text class="nickname">{{ showDevice?.lastLoginUser?.name || '未登录账号' }}</text>
            <text class="number">序列号：{{ showDevice?.simSerialNumber }}</text>
          </view>
        </view>
      </view>
      <template v-else>
        <view
          v-for="(i, idx) in devices"
          :key="idx"
          class="equipment_item"
          @click="chooseEquipment(i)"
        >
          <view class="equipment_item_right">
            <view class="avatar">
              <image :src="i.lastLoginUser?.avatar || defaultAvatar" mode=""></image>
            </view>
            <view class="right">
              <text class="nickname">{{ i.lastLoginUser?.name || '未登录账号' }}</text>
              <text class="number">序列号：{{ i.simSerialNumber }}</text>
            </view>
          </view>
          <view class="equipment_item_left">
            <image :src="i.id === showDevice.id ? checked : unchecked" mode=""></image>
          </view>
        </view>
      </template>

      <view class="binding">
        <view class="scan-bind" @click="scanBind">
          <image class="scan" :src="scanQr" mode=""></image>扫码绑定
        </view>
        <view class="hand-bind" @click="handBind"> 手动绑定 </view>
      </view>
    </view>
    <view class="home_function">
      <template v-for="(i, idx) in functionList" :key="idx">
        <view class="item" @click="change(i)">
          <image class="item_bg" :src="i.developing ? i.developingBg : i.bg" mode=""></image>
        </view>
      </template>
    </view>

    <!-- 手动绑定弹框 -->
    <mj-dialog
      v-model="showHandBindPopup"
      title="手动绑定孩子账号"
      okText="绑定"
      :ok="confirmHandBind"
    >
      <input v-model="childAccount" class="single-input" placeholder="请输入孩子账号" type="text" />
    </mj-dialog>
  </mj-page>
</template>

<style scoped lang="scss">
.teacher-content {
  padding: 30rpx 30rpx 120rpx 30rpx;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;

  .binding {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: 120rpx;
    background-color: #fff;
    border-radius: 20rpx;
    border: 2px dashed rgba(97, 93, 255, 1);
    color: rgba(97, 93, 255, 1);
    font-size: 34rpx;
    font-weight: 500;
    line-height: 52rpx;
    .scan-bind {
      .scan {
        width: 40rpx;
        height: 40rpx;
        margin-right: 10rpx;
      }
    }
    .scan-bind,
    .hand-bind {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  .my_equipment {
    background-color: #fff;
    padding: 0 30rpx;
    border-radius: 20rpx;

    .header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 30rpx 0;

      .arrow_icon {
        width: 36rpx;
        height: 36rpx;
      }
      .rotate {
        transform: rotate(180deg);
      }
    }

    .equipment_item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30rpx 0;
      border-top: 1rpx solid rgba(238, 238, 238, 1);

      &_right {
        display: flex;

        .avatar {
          width: 100rpx;
          height: 100rpx;
          margin-right: 20rpx;

          image {
            width: 100%;
            height: 100%;
          }
        }

        .right {
          .nickname {
            display: block;
            margin-bottom: 10rpx;
            font-size: 30rpx;
            line-height: 45rpx;
            font-weight: 500;
            max-width: 210rpx;
            text-overflow: ellipsis;
            overflow: hidden;
            white-space: nowrap;
          }

          .number {
            display: block;
            color: rgba(169, 170, 181, 1);
            font-weight: 400;
            font-size: 28rpx;
            line-height: 42rpx;
          }
        }
      }

      &_left {
        width: 30rpx;
        height: 30rpx;

        image {
          width: 100%;
          height: 100%;
        }
      }
    }

    .binding {
      height: 100rpx !important;
      border-radius: 0;
      border: none;
      border-top: 1rpx solid rgba(238, 238, 238, 1);
      font-size: 30rpx;
      line-height: 36rpx;

      .scan {
        width: 36rpx;
        height: 36rpx;
      }
    }
  }

  .home_function {
    display: flex;
    flex-wrap: wrap;

    margin-top: 40rpx;

    .item {
      height: 220rpx;
      width: 330rpx;
      margin: 0 30rpx 30rpx 0;

      &:nth-child(2n) {
        margin-right: 0;
      }

      &_bg {
        width: 100%;
        height: 100%;
      }
    }
  }
}
</style>
