<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'

import { pinyin } from 'pinyin-pro'

import { addUserRemark, editUserRemark } from '#/api'
import getDict from '#/hooks/useDict'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: '新建账号',
  },
  diaData: {
    type: Object,
    default: () => ({}),
  },
})
const emits = defineEmits(['update:modelValue', 'onRefresh'])
const sexList = [
  {
    code: '0',
    value: '未知',
  },
  {
    code: '1',
    value: '男',
  },
  {
    code: '2',
    value: '女',
  },
]

const vipList = [
  {
    value: '年',
  },
  {
    value: '月',
  },

  {
    value: '天',
  },
]
const educationList: any[] = getDict('education_type')
// const schoolList: any[] = getDict('user_school')
// const classList: any[] = getDict('user_class')
// const gradeList: any[] = getDict('user_grade_config')
const userViplength = ref({
  value: 1,
  label: '年',
})

const show = computed({
  get() {
    return props.modelValue
  },
  set(val) {
    emits('update:modelValue', val)
  },
})
const classNumber = ref<number | string>()

// 表单数据

const _formData = {
  name: '',
  nickName: '',
  account: '',
  sex: '1',
  schoolPersonType: 0,
  education: educationList[0]?.code,
  // schoolName: '',
  vipLengthTime: '1年',
  // classInSchool: '',
  // gradeName: '',
  phone: '', // 手机号
  userRemark: '', // 备注
}
const formRef = ref<FormInstance | undefined>()
const formData = reactive<Record<string, any>>({
  ..._formData,
})
const rules = reactive<FormRules>({
  name: [{ required: true, message: '请输入用户姓名', trigger: 'blur' }],
  // nickName: [{ required: true, message: '请输入用户昵称', trigger: 'blur' }],
  account: [{ required: true, message: '请输入用户账号', trigger: 'blur' }],
  schoolPersonType: [
    { required: true, message: '请选择用户类型', trigger: 'blur' },
  ],
  sex: [{ required: true, message: '请选择性别', trigger: 'blur' }],
  education: [{ required: true, message: '请选择学段', trigger: 'blur' }],
  // schoolName: [{ required: true, message: '请选择学校', trigger: 'blur' }],
  // classInSchool: [{ required: true, message: '请选择班级', trigger: 'blur' }],
  vipLengthTime: [
    { required: true, message: '请选择会员时长', trigger: 'blur' },
  ],
})

// 确定添加
async function handleSave() {
  await formRef.value?.validate((valid) => {
    if (valid) {
      if (props.diaData.id) {
        // 编辑
        editUserRemark({
          id: props.diaData.id,
          phone: formData.phone,
          name: formData.name,
          nickName: formData.name,
          userRemark: formData.userRemark,
        }).then(() => {
          show.value = false
          onClear()
          emits('onRefresh')
        })
        return
      }
      formData.nickName = formData.name
      formData.vipLengthTime = `${userViplength.value.value}${userViplength.value.label}`
      addUserRemark(formData).then(() => {
        show.value = false
        onClear()
        emits('onRefresh')
      })
    }
  })
}

function handleChangeAccount() {
  formData.name = formData.account
  formData.nickName = formData.account
}

function handleChangePhone() {
  if (props.diaData.id) return
  // 当填入手机号时，如果账号、姓名、昵称是空的，那就显示成手机号。
  if (!formData.account && !formData.name && !formData.nickName) {
    formData.account = formData.name = formData.nickName = formData.phone
  }
}

// function onBlur(value: string) {
//   if (!formData.classInSchool) return
//   if (isNaN(Number(classNumber.value))) {
//     classNumber.value = formData.classInSchool = ''
//     return
//   }
//   formData.classInSchool = `${formData.gradeName}${classNumber.value}班`
// }

// function onfocus() {
//   formData.classInSchool = classNumber.value
// }

// function handleChangeClass(val: string) {
//   if (!val) return
//   if (isNaN(Number(val)))
//     return (formData.classInSchool = classNumber.value = val.slice(0, -1))
//   classNumber.value = val
// }

// function changeGrade(value: string) {
//   // 选择年级
//   if (formData.classInSchool) {
//     formData.classInSchool = `${value}${classNumber.value}班`
//   }
// }

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

function onOpen() {
  onClear()
  if (props.diaData.id) {
    for (const i in formData) {
      formData[i] = props.diaData[i]
    }
  }
}

function onClear() {
  Object.assign(formData, _formData)
  userViplength.value = {
    value: 1,
    label: '年',
  }
  classNumber.value = undefined
}
</script>

<template>
  <el-dialog
    v-model="show"
    width="600px"
    :title="title"
    class="box"
    destroy-on-close
    @closed="onClear"
    @open="onOpen"
  >
    <el-form ref="formRef" label-width="80px" :model="formData" :rules="rules">
      <el-form-item label="手机号">
        <el-input
          v-model="formData.phone"
          placeholder="请输入"
          @change="handleChangePhone"
        />
      </el-form-item>
      <el-form-item label="用户姓名" prop="name">
        <el-input v-model="formData.name" placeholder="请输入" />
      </el-form-item>
      <el-row>
        <el-col :span="props.diaData.id ? 24 : 18">
          <el-form-item label="用户账号" prop="account">
            <el-input
              v-model="formData.account"
              placeholder="请输入"
              :disabled="Boolean(props.diaData.id)"
              @change="handleChangeAccount"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-button
            v-if="!props.diaData.id"
            style="margin-left: 20px"
            type="primary"
            @click="getPinyinByName"
          >
            拼音账号名
          </el-button>
        </el-col>
      </el-row>

      <!-- <el-form-item label="用户昵称" prop="nickName">
                <el-input v-model="formData.nickName" placeholder="请输入" />
            </el-form-item> -->
      <el-row v-if="!props.diaData.id">
        <el-col :span="12" style="padding-right: 8px">
          <el-form-item label="用户类型" prop="schoolPersonType">
            <el-select
              v-model="formData.schoolPersonType"
              placeholder="请选择用户类型"
            >
              <el-option label="学生" :value="0" />
              <el-option label="教师" :value="1" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="会员时长" prop="vipLengthTime">
            <el-row>
              <el-col :span="14" style="margin-right: 8px">
                <el-input
                  v-model.number="userViplength.value"
                  placeholder="请输入"
                />
              </el-col>
              <el-col :span="9">
                <el-select v-model="userViplength.label" placeholder="请选择">
                  <el-option
                    v-for="item in vipList"
                    :key="item.value"
                    :label="item.value"
                    :value="item.value"
                  />
                </el-select>
              </el-col>
            </el-row>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="!props.diaData.id">
        <el-col :span="12" style="padding-right: 8px">
          <el-form-item label="性别" prop="sex">
            <el-select v-model="formData.sex" placeholder="请选择性别">
              <el-option
                v-for="item in sexList"
                :key="item.value"
                :label="item.value"
                :value="item.code"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="学段" prop="education">
            <el-select
              v-model="formData.education"
              placeholder="请选择学段"
              class="education"
            >
              <el-option
                v-for="item in educationList"
                :key="item.value"
                :label="item.value"
                :value="item.code"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- <el-form-item v-if="!props.diaData.id" label="学校">
                <el-select v-model="formData.schoolName" placeholder="请选择学校">
                    <el-option
                        v-for="item in schoolList"
                        :key="item.value"
                        :label="item.value"
                        :value="item.value"
                    />
                </el-select>
            </el-form-item> -->
      <!--   <el-form-item label="班级" prop="classInSchool">
                <el-select v-model="formData.classInSchool" placeholder="请选择班级">
                    <el-option
                        v-for="item in classList"
                        :key="item.value"
                        :label="item.value"
                        :value="item.value"
                    />
                </el-select>
            </el-form-item> -->

      <!-- <el-form-item v-if="!props.diaData.id" label="年级">
                <el-select
                    v-model="formData.gradeName"
                    placeholder="请选择年级"
                    @change="changeGrade"
                >
                    <el-option
                        v-for="item in gradeList"
                        :key="item.value"
                        :label="item.value"
                        :value="item.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item v-if="!props.diaData.id" label="班级">
                <el-input
                    v-model="formData.classInSchool"
                    class="number-input"
                    placeholder="请输入"
                    @input="handleChangeClass"
                    @blur="onBlur"
                    @focus="onfocus"
                />
            </el-form-item> -->
      <el-form-item label="备注">
        <el-input
          v-model="formData.userRemark"
          :style="{ width: props.diaData.id ? '100%' : '192px' }"
          type="textarea"
          class="number-input"
          placeholder="请输入"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="show = false">取消</el-button>
        <el-button type="primary" @click="handleSave"> 提交 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.box {
  .number-input {
    width: 192px;
  }
}

.el-form-item__content > .el-select {
  width: 192px;

  &.education {
    width: 214px;
  }
}
</style>
