<script setup lang="ts" name="bind-device">
import type { MjGridProps } from '#/components/mj/mj-table'

import { OpenEmojiRight, OpenEmojiWrong } from '@vben/icons'

import { bindChildService } from '#/api/service/user/bind-child'
import MjTable from '#/components/mj/mj-table'
import hud from '#/utils/hud'

// 表格
const gridRef = ref()
const grid = {
  columns: [
    { type: 'seq' },
    {
      title: '学员',
      formatter(params) {
        return `${params.row.child.name} / ${params.row.child.account}`
      },
    },
    {
      title: '学员头像',
      slots: {
        default: 'childAvatar',
      },
    },
    {
      title: '家长',
      formatter(params) {
        return `${params.row.parent.name} / ${params.row.parent.account}`
      },
    },
    {
      title: '家长头像',
      slots: {
        default: 'parentAvatar',
      },
    },
    {
      title: '管理员',
      slots: {
        default: 'adminFlag',
      },
    },
    {
      title: '绑定状态',
      slots: {
        default: 'bindFlag',
      },
    },
    { field: 'bindTime', title: '绑定时间' },
    { fixed: 'right', title: '操作', slots: { default: 'operation' } },
  ],
} as MjGridProps

// 解绑
function unbind(row: any) {
  hud.confirmLoad(
    `确定解绑【${row.parent.account}】和【${row.child.account}】吗？`,
    {
      task: async () => {
        await bindChildService.unbind({
          childId: row.child.id,
          parentId: row.parent.id,
        })
        gridRef.value?.reload()
      },
      hideError: true,
      option: '解绑',
    },
  )
}
</script>

<template>
  <div class="bind-device g-container">
    <MjTable
      ref="gridRef"
      :grid="grid"
      :service="bindChildService"
      hide-remove
      hide-toolbar
    >
      <template #operation="{ row }">
        <el-button type="danger" @click="unbind(row)"> 解绑 </el-button>
      </template>
      <template #childAvatar="{ row }">
        <div class="avatar">
          <img v-if="row.child.avatar" :src="row.child.avatar" />
        </div>
      </template>
      <template #parentAvatar="{ row }">
        <div class="avatar">
          <img v-if="row.parent.avatar" :src="row.parent.avatar" />
        </div>
      </template>
      <template #adminFlag="{ row }">
        <div class="flex justify-center">
          <OpenEmojiRight v-if="row.adminFlag === 1" width="36" />
          <OpenEmojiWrong v-else width="36" />
        </div>
      </template>
      <template #bindFlag="{ row }">
        <div class="flex justify-center">
          <OpenEmojiRight v-if="row.bindFlag === 1" width="36" />
          <OpenEmojiWrong v-else width="36" />
        </div>
      </template>
    </MjTable>
  </div>
</template>

<style lang="scss" scoped>
.bind-device {
  height: 100% !important;

  .avatar {
    display: flex;
    justify-content: center;

    img {
      width: 40px;
      height: 40px;
    }
  }
}
</style>
