import {
  NButton,
  NForm,
  NFormItem,
  NInput,
  NSelect,
  NSpace,
  NSpin,
  useMessage
} from 'naive-ui';
import { defineComponent, onMounted, reactive, ref } from 'vue';
import styles from './index.module.less';
import { gradeToCN } from '/src/utils/contants';
import { classGroupList } from '/src/views/home/api';
import { api_getCurrentGradeYear, resetStudentInfo } from '../../api';
import { classArray, getgradeNumList } from '/src/views/classList/contants';

export default defineComponent({
  name: 'update-student',
  props: {
    row: {
      type: Object,
      default: () => ({})
    }
  },
  emits: ['close', 'confirm'],
  setup(props, { emit }) {
    const message = useMessage();
    const state = reactive({
      uploading: false,
      gradeList: [] as any,
      classList: [] as any,
      gradeYearList: [] as any
    });
    const forms = reactive({
      phone: null,
      nickname: null,
      gender: null,
      gradeYear: null,
      currentGradeNum: null,
      currentClass: null as any
    });

    const gradeNumList = ref(getgradeNumList());
    const classArrayRef = ref([...classArray] as any);
    const formsRef = ref();

    const onSubmit = async () => {
      formsRef.value?.validate(async (err: any) => {
        if (err) {
          return;
        }
        state.uploading = true;
        try {
          await resetStudentInfo({
            ...forms,
            id: props.row.id,
            schoolId: props.row.schoolId,
            tenantId: props.row.tenantId
          });
          message.success('修改成功');
          emit('confirm');
          emit('close');
        } catch {
          //
        }
        state.uploading = false;
      });
    };

    const getYearList = async () => {
      try {
        const { data } = await api_getCurrentGradeYear({});
        const temp = [
          {
            label: data + 1 + '学级',
            value: data + 1
          },
          {
            label: data + '学级',
            value: data
          }
        ];
        state.gradeYearList = temp;
      } catch {
        //
      }
    };

    onMounted(async () => {
      const row = props.row;
      getYearList();
      if (row.id) {
        forms.nickname = row.nickname;
        forms.phone = row.phone;
        forms.gender = row.gender;
        forms.currentGradeNum = row.currentGradeNum;
        forms.currentClass = row.currentClass;
        forms.gradeYear = row.gradeYear;
      }

      // 判断学年数组里面是否有存在，如果没有则追加数据
      const hasGradeYear = state.gradeYearList.findIndex(
        (i: any) => i.value === row.gradeYear
      );
      if (hasGradeYear === -1 && row.gradeYear) {
        state.gradeYearList.push({
          label: row.gradeYear,
          value: row.gradeYear
        });
      }
      if (forms.currentGradeNum) {
        const index = gradeNumList.value.findIndex(
          (item: any) => item.value === forms.currentGradeNum
        );
        if (index === -1) {
          forms.currentGradeNum = null;
        }
      }
    });

    const onlyAllowNumber = (value: string) => !value || /^\d+$/.test(value);
    return () => (
      <div class={styles.updateStudentContainer}>
        <NForm
          ref={formsRef}
          model={forms}
          labelAlign="right"
          labelWidth={'auto'}
          labelPlacement="left">
          <NFormItem
            label="姓名"
            path="nickname"
            rule={{
              required: true,
              message: '请填写学生姓名',
              trigger: 'blur'
            }}>
            <NInput
              maxlength={15}
              placeholder="请填写学生姓名"
              v-model:value={forms.nickname}></NInput>
          </NFormItem>
          <NFormItem
            label="手机号"
            path="phone"
            rule={[
              {
                required: true,
                message: '请填写学生手机号',
                trigger: 'blur'
              },
              {
                pattern: /^1[3456789]\d{9}$/,
                message: '手机号格式不正确',
                trigger: 'blur'
              }
            ]}>
            <NInput
              maxlength={11}
              allowInput={onlyAllowNumber}
              placeholder="请填写学生手机号"
              v-model:value={forms.phone}></NInput>
          </NFormItem>
          <NFormItem
            label="性别"
            path="gender"
            rule={[
              {
                required: true,
                message: '请选择性别',
                trigger: 'blur',
                type: 'number'
              }
            ]}>
            <NSelect
              class={styles.select}
              clearable
              filterable
              placeholder="请选择性别"
              options={[
                { label: '男', value: 1 },
                { label: '女', value: 0 }
              ]}
              v-model:value={forms.gender}
            />
          </NFormItem>
          <NFormItem
            label="学年"
            path="gradeYear"
            rule={[
              {
                required: true,
                message: '请选择学年',
                trigger: 'change',
                type: 'number'
              }
            ]}>
            <NSelect
              v-model:value={forms.gradeYear}
              placeholder="请选择学年"
              options={state.gradeYearList as any}
              clearable
              filterable
            />
          </NFormItem>
          <NFormItem
            label="年级"
            path="currentGradeNum"
            rule={[
              {
                required: true,
                message: '请选择年级',
                trigger: 'change',
                type: 'number'
              }
            ]}>
            <NSelect
              v-model:value={forms.currentGradeNum}
              placeholder="请选择年级"
              options={gradeNumList.value as any}
              clearable
              filterable
            />
          </NFormItem>
          <NFormItem
            label="班级"
            path="currentClass"
            rule={[
              {
                required: true,
                message: '请选择班级',
                trigger: 'change',
                type: 'number'
              }
            ]}>
            <NSelect
              filterable
              v-model:value={forms.currentClass}
              placeholder="请选择班级"
              clearable
              options={classArrayRef.value as any}
            />
          </NFormItem>

          <NSpace class={styles.updateBtnGroup}>
            <NButton strong type="default" round onClick={() => emit('close')}>
              取消
            </NButton>
            <NButton
              strong
              type="primary"
              round
              disabled={state.uploading}
              loading={state.uploading}
              onClick={onSubmit}>
              确认
            </NButton>
          </NSpace>
        </NForm>
      </div>
    );
  }
});
