<script setup lang="ts">
import type {
  MjEditFormProps,
  MjFormProps,
  MjGridProps,
} from '#/components/mj/mj-table'

import { IcomoonCoin } from '@vben/icons'
import { useAccessStore, useUserStore } from '@vben/stores'

import { classStudentService } from '#/api/service/org/class-student'
import { mj_form_text } from '#/components/mj/mj-table'
import { cellClassName } from '#/hooks/user'
import hud from '#/utils/hud'
import obj from '#/utils/obj'

import CoinAccounts from '../common/coin-accounts.vue'
import {
  useSearchClass,
  useSearchSchoolClass,
  useSearchStudent,
} from '../hooks/search'

const gridRef = ref()
const { userInfo } = storeToRefs(useUserStore())
const { accessCodes } = storeToRefs(useAccessStore())

const hasNewAssociationPermission = computed(() => {
  return accessCodes.value.includes('newAssociation')
})
const hasRemoveAssociationPermission = computed(() => {
  return accessCodes.value.includes('removeAssociation')
})

const studentRender = useSearchStudent({
  getData: () => gridRef.value.getEditFormData(),
  props: {
    multiSelectable: true,
  },
})

const schoolClassRender = useSearchSchoolClass({
  prepare: { gridRef },
})
const schoolRender = schoolClassRender.schoolRender
let classRender = schoolClassRender.classRender
if (userInfo.value.isOnlyStaff) {
  classRender = useSearchClass({
    prepare: { gridRef },
  })
}

// 新增学员
const editForm = {
  modal: {
    width: 720,
  },
  form: {
    items: obj.joinObjs<any>(
      userInfo.value.isOnlyStaff || {
        required: true,
        field: 'schoolName',
        title: '学校',
        span: 24,
        itemRender: {
          name: mj_form_text,
          props: {
            linkedRender: schoolRender,
          },
        },
      },
      {
        required: true,
        field: 'className',
        title: '班级',
        span: 12,
        itemRender: {
          name: mj_form_text,
          props: {
            linkedRender: classRender,
          },
        },
      },
      {
        required: true,
        title: '学员',
        field: 'studentId',
        span: 12,
        itemRender: studentRender,
      },
    ),
    data: {},
  },
  addFields: ['studentId', 'classId'],
} as MjEditFormProps

// 搜索表单
const searchForm = {
  items: obj.joinObjs(
    userInfo.value.isOnlyStaff || {
      title: '学校',
      field: 'schoolId',
      span: 6,
      itemRender: schoolRender,
    },
    {
      title: '班级',
      field: 'classId',
      span: 6,
      itemRender: classRender,
    },
  ),
} as MjFormProps

// 表格
const grid = {
  columns: obj.joinObjs<any>(
    { type: 'seq' },
    {
      field: 'userName',
      title: '学员姓名',
    },
    {
      field: 'account',
      title: '学员账号',
    },
    {
      field: 'serialNumber',
      title: '设备编码',
    },
    {
      field: 'diamond',
      title: '钻石',
      formatter: 'money',
    },
    {
      field: 'currency',
      title: '乐贝',
      formatter: 'money',
    },
    {
      field: 'vipEndTime',
      title: '到期时间',
      formatter: 'vipEndTime',
    },
    userInfo.value.isOnlyStaff || { field: 'schoolName', title: '学校' },
    { field: 'className', title: '班级' },
    {
      fixed: 'right',
      title: '操作',
      slots: {
        default: 'operation',
      },
    },
  ),
  cellClassName,
  beforeLoadData(params) {
    if (userInfo.value.isSpStaff) {
      // 如果是服务商人员
      params.providerId = userInfo.value.providerId
    } else if (userInfo.value.isStaff) {
      // 如果是学校人员
      params.schoolId = userInfo.value.schoolId
    }
    return params
  },
} as MjGridProps

// 查看乐贝
const selectUser = ref({} as any)
const showCoinAccount = ref(false)
function checkCoin(row: any) {
  selectUser.value = row
  showCoinAccount.value = true
}

// 解绑设备
function unbindDevice(row: any) {
  hud.confirmLoad(`确定解绑【${row.userName}】的设备吗？`, {
    task: async () => {
      await classStudentService.unbindDevice(row.userId)
      gridRef.value?.reload()
    },
    hideError: true,
    option: '解绑',
  })
}
</script>

<template>
  <div class="class-student g-container">
    <MjTable
      ref="gridRef"
      add-button-text="新增关联"
      delete-button-text="移除关联"
      :edit-form="editForm"
      :search-form="searchForm"
      :grid="grid"
      :service="classStudentService"
      :hide-add="!hasNewAssociationPermission"
      :hide-remove="!hasRemoveAssociationPermission"
      v-bind="$attrs"
      hide-edit
    >
      <template #operation="{ row }">
        <el-button type="success" :icon="IcomoonCoin" @click="checkCoin(row)">
          乐贝账户
        </el-button>
        <el-button type="danger" @click="unbindDevice(row)"> 解绑 </el-button>
      </template>
    </MjTable>

    <CoinAccounts
      v-model="showCoinAccount"
      :user-id="selectUser.userId"
      :user-name="selectUser.userName"
    />
  </div>
</template>

<style lang="scss" scoped></style>
