<script setup lang="ts">
import ChangePassword from './changePassword.vue'
import { userStore } from '@/stores'
import { storeToRefs } from 'pinia'
import { useRouter } from 'vue-router'
import { getSN, isNotStudyMachine } from '@/utils'
import { useTips } from '@/hooks'
import { debounce } from 'lodash-es'
import { loading } from '@/components/mj/mj-loading'
import hud from '@/utils/hud'
import settingApi from '@/api/system/setting'
import userApi from '@/api/system/user'

const emits = defineEmits(['updateAccount'])
const router = useRouter()
const { logout, changeAccount, getUserNow, clearUser } = userStore()
const { userInfo, userRecords } = storeToRefs(userStore())

interface AccountItemType {
  account?: string
  avatarFrameUrl?: string
  avatarUrl?: string
  nickName?: string
  nickNameFrameUrl?: string
  personalImageNum?: number
  token?: string
}

const OSS_URL = import.meta.env.VITE_OSS_URL
const bg = `url(${OSS_URL}/urm/header_bg.svg) 100%/cover no-repeat`
const addAccount = `url(${OSS_URL}/urm/system_setting_account_add.svg) 100%/cover no-repeat`
const showDia = ref(false)
const accountLoading = ref(false)

const activeAccount = ref<AccountItemType>({})
const accountList = ref<AccountItemType[]>([])

// 退出登录
async function handleConfirmLogout() {
  hud.confirmLoad({
    dialog: '确定要退出？',
    task: async () => {
      await logout()
      router.replace('/login')
    },
    option: '退出登录',
  })
}

// 切换账号
async function handleSwitchAccount(i: AccountItemType) {
  if (i.account === userInfo.value.account) return
  try {
    loading.show('正在切换中...')

    if (isNotStudyMachine) {
      const { data } = await userApi.switchUser({
        account: i.account,
        targetAccountOldToken: i.token,
      })
      await changeAccount(data.data)
    } else {
      const { data } = await settingApi.changeLoginAccApi({ account: i.account as string })
      await changeAccount(data.data)
    }
    activeAccount.value = i
    // await getInspectorInfo()
    // location.reload()
  } catch (err: any) {
    if (isNotStudyMachine) {
      clearUser(i.account!)
    }
    router.push({ path: '/login', query: { back: 1, a: i.account } })
    if (err.data.message) {
      useTips({
        tips: err.data.message,
      })
    }
  } finally {
    loading.hide()
  }
}

// 登录过设备的账号
async function getCurrentDeviceRelateAcc() {
  // web环境使用本地账户信息
  if (isNotStudyMachine) {
    accountList.value = userRecords.value
    activeAccount.value = getUserNow()
    return
  }
  accountLoading.value = true
  try {
    const { data } = await settingApi.getCurrentDeviceRelateAccApi()
    accountList.value = data.data
    activeAccount.value = data.data.find(
      (item: AccountItemType) => item.account === userInfo.value.account,
    )
  } catch (err) {
    console.log(err)
  } finally {
    accountLoading.value = false
  }
}
function handleAddAccount() {
  router.push({ path: '/login', query: { back: 1 } })
}
function handleDelete(i: AccountItemType) {
  if (i.account === userInfo.value.account) return

  hud.alert({
    content: `确定要删除账号${hud.highlight(i.nickName)}吗？`,
    ok: async () => {
      if (isNotStudyMachine) {
        clearUser(i.account!)
        accountList.value = userRecords.value
        return
      }
      // 安卓端删除设备关联账号
      settingApi
        .deleteDeviceRelateAccApi({
          simSerialNumber: getSN(),
          account: i.account,
        })
        .then(() => getCurrentDeviceRelateAcc())
    },
  })
}
const _handleDelete = debounce(handleDelete, 500, {
  leading: true,
  trailing: false,
})
onMounted(() => {
  getCurrentDeviceRelateAcc()
})
onActivated(() => {
  getCurrentDeviceRelateAcc()
})
</script>
<template>
  <div class="account_module hidden_scroll">
    <!--账号密码 -->
    <div class="account_pwd">
      <div
        class="header"
        :style="{
          background: bg,
        }"
      >
        账号密码
      </div>
      <div class="user_account">
        <div class="item">
          <div class="label">账号</div>
          {{ userInfo.account }}
          <div class="change_pwd">
            <mj-button type="warn" width="272" tilt @click="() => (showDia = true)">
              修改密码
            </mj-button>
            <mj-button
              type="danger"
              class="logout_btn"
              width="272"
              tilt
              @click="handleConfirmLogout"
              >退出登录</mj-button
            >
          </div>
        </div>
        <!-- <div class="item">
          <div class="label">密码</div>
          <span>***********</span>
          <div class="change_pwd">
            <mj-button type="warn" width="272" tilt @click="() => (showDia = true)">
              修改密码
            </mj-button>
            <mj-button
              type="danger"
              class="logout_btn"
              width="272"
              tilt
              @click="handleConfirmLogout"
              >退出登录</mj-button
            >
          </div>
          <div></div>
        </div> -->
      </div>
    </div>
    <!-- 切换账号 -->
    <div class="switch_account">
      <div
        class="header"
        :style="{
          background: bg,
        }"
      >
        切换账号
      </div>
      <div class="account_list">
        <div v-if="accountLoading" class="loading_account">
          <Icon name="global_loading" loading size="100"></Icon>
        </div>
        <template v-else>
          <div
            v-for="(i, idx) in accountList"
            :key="idx"
            v-longpress="() => _handleDelete(i)"
            :class="{
              account_item: true,
              active: i.account === userInfo.account,
            }"
            @click="handleSwitchAccount(i)"
          >
            <span v-if="i.account === userInfo.account" class="online"></span>
            <UserHead size="100" :head="i.avatarUrl" :border="i.avatarFrameUrl" />
            <div class="name">{{ i.nickName }}</div>
          </div>
          <div
            :class="{ add_account: true, over_line: accountList.length >= 4 }"
            :style="{ background: addAccount }"
            @click="handleAddAccount"
          ></div>
        </template>
      </div>
    </div>
    <ChangePassword v-model="showDia" />
  </div>
</template>
<style lang="scss" scoped>
.account_module {
  position: relative;
  padding: 4.5vh 0 0 14px;
  font-family: $font-special;
  width: 100%;
  height: 100%;
  z-index: 1;

  .header {
    width: 61.17vh;
    height: 12.5vh;
    font-size: 3.33vh;
    padding: 1.83vh 0 0 146px;
    line-height: 6vh;
    color: #ffffff;
  }

  .account_pwd {
    position: relative;
    width: 100%;
    height: 24.75vh;
    // .header {
    //   position: absolute;
    //   top: 0;
    // }
    .user_account {
      position: absolute;
      width: 100%;
      top: 8.5vh;
      left: 0;
      padding: 4vh 0 4.25vh 64px;
      border-radius: 3.33vh;
      background: $white-gradient;
      z-index: 99;

      .item {
        display: flex;
        align-items: center;
        color: $font-color;
        font-size: 2.67vh;
        line-height: 4vh;
        font-family: $font-text;
        .label {
          font-family: $font-special;
          margin-right: 56px;
          color: $font-tag-color;
          font-size: 3.33vh;
          line-height: 5vh;
        }
      }
      .change_pwd {
        margin-left: 80px;
        font-size: 2.67vh;
        line-height: 4vh;

        .logout_btn {
          margin-left: 48px;
        }
      }
    }
  }
  .switch_account {
    margin: $space-6 0;
    width: 100%;

    .account_list {
      margin-top: -3.83vh;
      display: flex;
      flex-wrap: wrap;
      width: 100%;
      min-height: 25.67vh;
      padding: 4vh 74px 4vh 64px;
      border-radius: 3.33vh;
      background: $white-gradient;
      z-index: 99;
      box-sizing: border-box;
      gap: $space-5_h;
      .loading_account {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
      }
      .account_item {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        position: relative;
        // margin: $space-3_h $space-3_h 0 0;
        background-color: rgba(0, 0, 0, 0.65);
        width: 23.17vh;
        height: 17.67vh;
        border-radius: 2.5vh;
        box-sizing: border-box;
        cursor: pointer;

        .online {
          position: absolute;
          top: 2vh;
          left: 2vh;
          display: block;
          width: 2vh;
          height: 2vh;
          border-radius: 50%;
          background-color: #87fa89;
        }
        .name {
          margin-top: $space-2_h;
          font-size: $font-size-7;
          color: #fff;
          line-height: 4vh;
          font-family: $font-cn;
          font-weight: 400;
          text-align: center;
          font-family: $font-text;
        }
        &:nth-child(4n) {
          margin-right: 0;
        }
        &:nth-child(-n + 4) {
          margin-top: 0;
        }
      }
      .active {
        border: 0.67vh solid rgba(255, 240, 31, 1);
        box-shadow: 0 0.33vh 0.67vh 0 rgba(0, 0, 0, 0.15);
      }
      .add_account {
        width: 23.17vh;
        height: 17.67vh;
        cursor: pointer;
      }
      .over_line {
        margin-top: $space-3_h;
      }
    }
  }
  .logout_text {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: $font-size-7;
    color: $font-tag-color;
    text-align: center;
  }
}
</style>
