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

import { BatteryCharge, IcomoonCoin, ResetPassword } from '@vben/icons'
import { useUserStore } from '@vben/stores'
import { downloadFileFromUrl } from '@vben/utils'

import { Share, UploadFilled } from '@element-plus/icons-vue'

import { studentService } from '#/api/service/org/student'
import obj from '#/utils/obj'
import { useSearchSchoolClass } from '#/views/org/hooks/search'

import { cellClassName, user_type_student, useUser } from '../../../hooks/user'
import CoinAccounts from '../common/coin-accounts.vue'
import { userEditForm } from './hooks/edit-form'
import ShareStudent from './share-student.vue'

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

const defaultPwd = '123456'

const schoolClassRender = useSearchSchoolClass({
  prepare: { gridRef },
})
const schoolRender = schoolClassRender.schoolRender

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

// 表格
const grid = {
  toolbarConfig: {
    custom: true,
  },
  columns: obj.joinObjs<any>(
    { type: 'seq' },
    {
      field: 'name',
      title: '姓名',
    },
    {
      field: 'nickName',
      title: '昵称',
    },
    {
      field: 'account',
      title: '账号',
    },
    {
      title: '状态',
      slots: {
        default: 'status',
      },
    },
    {
      field: 'vipEndTime',
      title: '到期时间',
      formatter: 'vipEndTime',
    },
    userInfo.value.isOnlyStaff || {
      field: 'schoolName',
      title: '学校',
    },
    {
      field: 'diamond',
      title: '钻石',
      formatter: 'money',
    },
    {
      field: 'currency',
      title: '乐贝',
      formatter: 'money',
    },
    {
      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
  },
  afterLoadData(data) {
    if (data.rows?.length) {
      for (const item of data.rows) {
        item.year = item.birthday?.slice(0, 4)
      }
    }
    return data
  },
} as MjGridProps

// 编辑表单
const { editForm } = userEditForm({
  userInfo,
  gridRef,
  schoolRender,
  schoolClassRender,
  defaultPwd,
})

const {
  selectedItems,
  selectedBtnDisabled,
  resetPassword,
  statusChange,
  userRenewVisible,
  renewUser,
  renew,
  autoAccount,
} = useUser({
  defaultPwd,
  gridRef,
  userType: user_type_student,
})

// 共享
const shareVisible = ref(false)
function share() {
  shareVisible.value = true
}

// 分享成功
function shareSuccess() {
  selectedItems.value = {}
  gridRef.value.reload()
}

const selectStudent = ref({} as any)

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

// 显示导入
const showImport = ref(false)
const submitImport = async (data: any) => {
  const url = await studentService.importStudent(data)
  if (url) {
    downloadFileFromUrl({
      fileName: '导入结果.xlsx',
      source: url,
    })
  }
}
</script>

<template>
  <div class="student-mgr g-container">
    <user-renew
      v-model="userRenewVisible"
      :user="renewUser"
      @success="gridRef?.reload()"
    />
    <mj-table
      ref="gridRef"
      :search-form="searchForm"
      :edit-form="editForm"
      :grid="grid"
      :service="studentService"
      v-model:selected-items="selectedItems"
      v-bind="$attrs"
      hide-remove
      add-button-text="创建账号"
    >
      <template #operation="{ row }">
        <el-button type="success" :icon="BatteryCharge" @click="renew(row)">
          续费
        </el-button>
        <el-button type="success" :icon="IcomoonCoin" @click="checkCoin(row)">
          乐贝账户
        </el-button>
      </template>

      <template #status="{ row }">
        <el-switch v-model="row.status" @click="statusChange(row)" />
      </template>

      <template #form_tool>
        <el-button type="success" @click="autoAccount">
          自动生成账号名
        </el-button>
      </template>

      <template #toolbarButtonsExtra>
        <el-button :icon="UploadFilled" @click.stop="showImport = true">
          导入
        </el-button>
        <el-button
          type="success"
          :icon="Share"
          :disabled="selectedBtnDisabled"
          @click="share"
        >
          共享
        </el-button>
        <el-button
          type="warning"
          :icon="ResetPassword"
          :disabled="selectedBtnDisabled"
          @click="resetPassword"
        >
          重置密码
        </el-button>
      </template>
    </mj-table>
    <ShareStudent
      v-model="shareVisible"
      :students="selectedItems?.items"
      @success="shareSuccess"
    />
    <CoinAccounts
      v-model="showCoinAccount"
      :user-id="selectStudent.id"
      :user-name="selectStudent.name"
    />

    <import-data
      v-model="showImport"
      :request="submitImport"
      :file-types="['xlsx', 'xls']"
      title="导入学生"
      template-url="https://english-1313840333.cos.ap-guangzhou.myqcloud.com/template/student_import_school.xlsx"
    />
  </div>
</template>

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