import { pinyin } from 'pinyin-pro'

import { resetPwd } from '#/api'
import { userService } from '#/api/service/user/user'
import { pattern_phone } from '#/components/mj/mj-table/fmt'
import dayjs from '#/plugins/dayjs'
import hud from '#/utils/hud'

export const user_type_student = 1
export const user_type_staff = 2
export const user_type_sp_staff = 3

type UseUserType = {
  defaultPwd: any
  gridRef: Ref<any>
  userType: any
}

export function cellClassName(params: any) {
  if (params.column.field !== 'vipEndTime') {
    return undefined
  }
  const time = params.row[params.column.field]
  if (!time || dayjs(time).isBefore(dayjs())) {
    return params.row.activeFlag ? 'progress-60' : 'progress-1'
  }
}

export function useUser(data: UseUserType) {
  const { defaultPwd, gridRef } = data
  // 选中的数据
  const selectedItems = ref([] as any)
  // 跟选中数据相关的按钮
  const selectedBtnDisabled = computed(() => !selectedItems.value.items?.length)
  const userRenewVisible = ref(false)
  const renewUser = ref({} as any)

  function getId(row: any) {
    return row.userId || row.id
  }

  function getName(row: any) {
    return row.userName || row.name
  }

  function batchResetPwd(items: Option[], defaultPwd: any, afterReset: any) {
    if (!items?.length) return
    const content =
      items.length === 1
        ? `将${hud.highlight(items[0]?.label)}的密码重置为${hud.highlight(defaultPwd)}？`
        : `将${items.length}个用户的密码重置为${hud.highlight(defaultPwd)}？`

    hud.confirmLoad(content, {
      task: async () => {
        await resetPwd(items.map((item) => item.value))
        afterReset && afterReset()
      },
      option: '重置',
      hideSuccess: false,
    })
  }

  // 续费
  function renew(row: any) {
    renewUser.value = {
      id: getId(row),
      name: getName(row),
      type: data.userType,
    }
    userRenewVisible.value = true
  }

  // 重置密码
  function resetPassword() {
    batchResetPwd(
      selectedItems.value.items.map((item: any) => ({
        label: item.name,
        value: getId(item),
      })),
      defaultPwd,
      () => {
        gridRef.value.reload()
        selectedItems.value = {}
      },
    )
  }

  // 状态改变
  function statusChange(row: any) {
    const oldFlag = !row.status

    userService.updateStatus(getId(row), row.status).catch(() => {
      row.status = oldFlag
    })
  }

  // 生成拼音+尾号账号
  function autoAccount() {
    const data = gridRef.value.getEditFormData()
    if (!data.name || !data.phone) {
      hud.error('请输入姓名和手机号')
      return
    }
    const regex = new RegExp(pattern_phone, 'i')
    if (!regex.test(data.phone)) {
      hud.error('请输入正确的手机号')
      return
    }

    // 根据汉字转化为拼音
    const namePinyin = pinyin(data.name, {
      toneType: 'none',
      type: 'array',
      v: true, // 转化拼音的ü为v
    }).join('')
    data.account = namePinyin + data.phone.slice(-4)
  }

  return {
    renew,
    selectedItems,
    selectedBtnDisabled,
    resetPassword,
    statusChange,
    autoAccount,
    userRenewVisible,
    renewUser,
  }
}
