<script setup lang="ts">
import type { VxeGridPropTypes } from 'vxe-table'

import type { MjFormProps, MjGridProps } from '#/components/mj/mj-table'

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

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

import { staffService } from '#/api/service/subject/staff'
import { useAuthStore } from '#/store/auth'
import hud from '#/utils/hud'
import obj from '#/utils/obj'
import { useSearchSchoolClass } from '#/views/org/hooks/search'

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

const gridRef = ref()
const authStore = useAuthStore()
const { userInfo } = storeToRefs(useUserStore())
const schoolClassRender = useSearchSchoolClass({
  prepare: { gridRef },
})
const schoolRender = schoolClassRender.schoolRender

const defaultPwd = 'syx666666'

const roles_options = [
  {
    label: '教师',
    value: '1943169126285271041',
  },
  {
    label: '教研组长',
    value: '1944364130005508097',
  },
  {
    label: '年级主任',
    value: '1944364322851217410',
  },
  {
    label: '学校管理员',
    value: '1943173895854841858',
  },
]
const roles_map = obj.options2map(roles_options)
// 搜索表单
// 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<VxeGridPropTypes.Column>(
    { type: 'seq' },
    {
      field: 'name',
      title: '姓名',
    },
    {
      field: 'subjectName',
      title: '学科',
    },
    {
      field: 'gradeName',
      title: '年级',
    },
    {
      field: 'account',
      title: '账号',
    },
    // {
    //   title: "状态",
    //   slots: {
    //     default: "status",
    //   },
    // },
    {
      field: 'vipEndTime',
      title: '到期时间',
      formatter: 'vipEndTime',
    },
    {
      field: 'roleId',
      title: '角色',
      formatter({ cellValue }) {
        return roles_map[cellValue]
      },
    },
    (userInfo.value.isOnlyStaff || {
      field: 'schoolName',
      title: '学校',
    }) as any,
    {
      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
    }
    params.selfInfo = 1
    return params
  },
} as MjGridProps

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

// 对话框
const bookSelectVisible = ref(false)
const curTeacher = ref({} as any)
function showBookSelect(teacher: any) {
  if (typeof teacher.config === 'string') {
    teacher.config = JSON.parse(teacher.config)
  }
  curTeacher.value = teacher
  bookSelectVisible.value = true
}

function onBookSelect(books: any) {
  hud.load({
    task: async () => {
      await staffService.saveOrUpdate({
        id: curTeacher.value.id,
        textbookIds: books.map((item: any) => item.id),
        config: JSON.stringify({ books }),
      })
      gridRef.value.reload()
      await authStore.updateUserInfo()
    },
    option: '保存',
    hideSuccess: false,
  })
}

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

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

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

<template>
  <div class="teacher-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="staffService"
      v-bind="$attrs"
      add-button-text="创建账号"
      hide-remove
      hide-edit
      hide-search
      hide-toolbar
    >
      <template #operation="{ row }">
        <el-button
          type="primary"
          :icon="BookOutline"
          @click="showBookSelect(row)"
        >
          设置教材
        </el-button>
      </template>

      <!-- <template #toolbarButtonsExtra>
        <el-button
          type="primary"
          @click="showImport = true"
          :icon="UploadFilled"
        >
          导入
        </el-button>
        <el-button
          type="warning"
          :icon="ResetPassword"
          :disabled="selectedBtnDisabled"
          @click="resetPassword"
        >
          重置密码
        </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>
    </mj-table>
    <textbook-multi-select v-model="bookSelectVisible" @ok="onBookSelect" />
    <CoinAccounts
      v-model="showCoinAccount"
      :user-id="selectUser.id"
      :user-name="selectUser.name"
    />

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

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