import { defineComponent, onMounted, reactive, ref, watch } from 'vue';
import styles from '../index.module.less';
import {
  NImage,
  NForm,
  NFormItem,
  NInput,
  NGrid,
  NGi,
  NButton,
  NSelect,
  NSpace,
  SelectOption,
  useMessage,
  NModal
} from 'naive-ui';
// import headerD from '../images/headerD.png';
// import defultHeade from '@/components/layout/images/teacherIcon.png';
// import maleIcon from '../images/maleIcon.png';
// import femaleIcon from '../images/femaleIcon.png';
// import { useUserStore } from '/src/store/modules/users';
// import { api_teacherUpdate } from '/src/api/user';
import { api_getCurrentGradeYear, resetStudentInfo } from '../api';
// import UploadFile from '/src/components/upload-file';
import { getgradeNumList, classArray } from '@/views/classList/contants';
import { useRoute } from 'vue-router';
import { modalClickMask } from '/src/state';
export default defineComponent({
  name: 'setting-personInfo',
  props: {
    studentInfo: {
      type: Object,
      default: () => ({
        nickname: '',
        currentGradeNum: '',
        gender: null,
        phone: '',
        id: '',
        currentClass: ''
      })
    }
  },
  setup(props) {
    const route = useRoute();
    const message = useMessage();
    const loading = ref();
    const formOptions = reactive({
      sexs: [
        { label: '男', value: 1, class: 'option' },
        { label: '女', value: 0, class: 'option' }
      ] as SelectOption[],
      areaList: [] as any[]
    });
    const formRef = ref();
    const showUpdate = ref(false);
    const gradeNumList = ref(getgradeNumList());
    const gradeYearList = ref([] as any);
    const historyClassStudent = ref(
      props.studentInfo.historyClassStudent || ''
    );
    const formatGradeNum = () => {
      if (props.studentInfo.currentGradeNum) {
        const index = gradeNumList.value.findIndex(
          (item: any) => item.value === props.studentInfo.currentGradeNum
        );
        if (index === -1) {
          return null;
        } else {
          return props.studentInfo.currentGradeNum;
        }
      } else {
        return null;
      }
    };
    const initGrade = (gradeYear: any) => {
      // 判断学年数组里面是否有存在，如果没有则追加数据
      const hasGradeYear = gradeYearList.value.findIndex(
        (i: any) => i.value === gradeYear
      );
      if (hasGradeYear === -1 && gradeYear) {
        gradeYearList.value.push({
          label: gradeYear,
          value: gradeYear
        });
      }
    };
    const studentForm = reactive({
      upgradeFlag: (route.query.upgradeFlag as any) == 0 ? 1 : 0, // 是否为历史班
      nickname: props.studentInfo.nickname as any,
      phone: props.studentInfo.phone,
      gender: props.studentInfo.gender,
      id: props.studentInfo.id,
      currentGradeNum: formatGradeNum(),
      gradeYear: props.studentInfo.gradeYear,
      currentClass: props.studentInfo.currentClass
    });

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

    const data = reactive({
      disabled: true,
      openChangePwd: false,
      uploadShow: true
    });

    watch(
      () => props.studentInfo,
      val => {
        studentForm.nickname = val.nickname as any;
        studentForm.phone = val.phone;
        studentForm.gender = val.gender;
        studentForm.id = val.id;
        studentForm.currentGradeNum = formatGradeNum();
        studentForm.currentClass = val.currentClass;
        studentForm.gradeYear = val.gradeYear;

        console.log(props.studentInfo, 'props.studentInfo');
        initGrade(val.gradeYear);
      }
    );
    onMounted(async () => {
      await getYearList();
      initGrade(props.studentInfo.gradeYear);
    });

    const handleSave = () => {
      loading.value = true;
      formRef.value.validate(async (err: any) => {
        if (err) {
          return;
        }
        try {
          await resetStudentInfo({ ...props.studentInfo, ...studentForm });
          data.disabled = true;
          message.success('修改成功');
          loading.value = false;
          showUpdate.value = false;
        } catch (e) {
          loading.value = false;
        }
      });
    };
    const cancel = () => {
      studentForm.nickname = props.studentInfo.nickname;
      studentForm.phone = props.studentInfo.phone;
      studentForm.gender = props.studentInfo.gender;
      studentForm.currentGradeNum = formatGradeNum();
      studentForm.currentClass = props.studentInfo.currentClass;
      studentForm.gradeYear = props.studentInfo.gradeYear;
      data.disabled = true;
    };

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

    const onlyAllowNumber = (value: string) => !value || /^\d+$/.test(value);
    return () => (
      <div class={styles.infoWrap}>
        <div class={styles.setInfo}>
          <NForm ref={formRef} model={studentForm} disabled={data.disabled}>
            <NGrid cols={4} x-gap="100">
              <NGi>
                <NFormItem
                  label="姓名"
                  path="nickname"
                  rule={{
                    required: true,
                    message: '请填写学生姓名',
                    trigger: 'blur'
                  }}>
                  <NInput
                    maxlength={15}
                    bordered={!data.disabled}
                    placeholder="请填写学生姓名"
                    v-model:value={studentForm.nickname}></NInput>
                </NFormItem>
              </NGi>
              <NGi>
                <NFormItem
                  label="手机号"
                  path="phone"
                  rule={[
                    {
                      required: true,
                      message: '请填写学生手机号',
                      trigger: 'blur'
                    },
                    {
                      pattern: /^1[3456789]\d{9}$/,
                      message: '手机号格式不正确',
                      trigger: 'blur'
                    }
                  ]}>
                  <NInput
                    maxlength={11}
                    allowInput={onlyAllowNumber}
                    bordered={!data.disabled}
                    placeholder="请填写学生手机号"
                    v-model:value={studentForm.phone}></NInput>
                </NFormItem>
              </NGi>
              <NGi>
                <NFormItem label="性别" path="sex">
                  <NSelect
                    bordered={!data.disabled}
                    class={styles.select}
                    showArrow={!data.disabled}
                    placeholder="请选择性别"
                    options={formOptions.sexs}
                    v-model:value={studentForm.gender}
                  />
                </NFormItem>
              </NGi>
              <NGi>
                <NFormItem label="学年" path="">
                  <NSelect
                    bordered={!data.disabled}
                    class={styles.select}
                    showArrow={!data.disabled}
                    placeholder="请选择学年"
                    options={gradeYearList.value as any}
                    v-model:value={studentForm.gradeYear}
                  />
                </NFormItem>
              </NGi>
              <NGi>
                <NFormItem label="年级" path="">
                  <NSelect
                    bordered={!data.disabled}
                    class={styles.select}
                    showArrow={!data.disabled}
                    placeholder="请选择年级"
                    options={gradeNumList.value as any}
                    v-model:value={studentForm.currentGradeNum}
                  />
                </NFormItem>
              </NGi>
              <NGi>
                <NFormItem label="班级" path="">
                  <NSelect
                    bordered={!data.disabled}
                    class={styles.select}
                    showArrow={!data.disabled}
                    placeholder="请选择班级"
                    options={classArrayRef.value}
                    v-model:value={studentForm.currentClass}
                  />
                </NFormItem>
              </NGi>
            </NGrid>
          </NForm>
        </div>
        {data.disabled ? (
          !studentForm.upgradeFlag && (
            <NSpace class={styles.btnList} align="center" justify="end">
              <NButton
                class={styles.btn}
                strong
                color="#f24433"
                disabled={historyClassStudent.value ? true : false}
                onClick={() => (data.disabled = false)}>
                修改信息
              </NButton>
            </NSpace>
          )
        ) : (
          <NSpace class={styles.btnList} align="center" justify="end">
            <NButton class={styles.btn} onClick={() => cancel()}>
              取消
            </NButton>
            <NButton
              class={styles.btn}
              type="primary"
              onClick={() => (showUpdate.value = true)}>
              完成
            </NButton>
          </NSpace>
        )}

        <NModal
          maskClosable={modalClickMask}
          v-model:show={showUpdate.value}
          preset="card"
          class={['modalTitle', styles.removeVisiable]}
          title={'确认修改'}>
          <div class={styles.studentRemove}>
            <p>是否确认修改学员信息</p>

            <NSpace class={styles.btnGroup} justify="center">
              <NButton
                round
                type="primary"
                onClick={handleSave}
                loading={loading.value}>
                确定
              </NButton>
              <NButton round onClick={() => (showUpdate.value = false)}>
                取消
              </NButton>
            </NSpace>
          </div>
        </NModal>
      </div>
    );
  }
});
