<template>
  <ie-page bg-color="#F6F8FA" :safeAreaInsetBottom="false">
    <ie-navbar title="完善信息"></ie-navbar>
    <uv-form labelPosition="left" :model="form" labelWidth="70px" ref="formRef">
      <content-card title="考生信息">
        <uv-form-item label="学生姓名" prop="name" borderBottom required>
          <uv-input v-model="form.nickName" border="none" placeholder="请输入姓名" placeholderClass="text-30"
            font-size="30rpx" :custom-style="customStyle">
          </uv-input>
        </uv-form-item>
        <uv-form-item label="所在省份" prop="location" borderBottom required>
          <ie-picker ref="pickerRef" v-model="form.location" :list="appStore.provinceList" placeholder="选择省份"
            :custom-style="customStyle" key-label="dictLabel" key-value="dictValue" :disabled="isProvinceDisabled"
            :show-arrow="!isProvinceDisabled" @change="handleProvinceChange"></ie-picker>
        </uv-form-item>
        <uv-form-item label="考生类别" prop="examType" borderBottom required>
          <ie-picker ref="pickerRef" v-model="form.examType" :list="examTypeList" :disabled="isExamTypeDisabled"
            placeholder="选择考生类别" :custom-style="customStyle" key-label="dictLabel" key-value="dictValue"
            :show-arrow="!isExamTypeDisabled" @change="handleExamTypeChange"></ie-picker>
        </uv-form-item>
        <uv-form-item v-if="form.examType === 'VHS'" label="专业类别" prop="majorType" borderBottom required>
          <ie-picker ref="pickerRef" v-model="form.majorType" :list="majorTypes" :disabled="!form.examType"
            placeholder="选择专业类别" :custom-style="customStyle" key-label="dictLabel" key-value="dictValue"
            @change="handleMajorChange"></ie-picker>
        </uv-form-item>
        <uv-form-item label="毕业年份" prop="year" required>
          <ie-picker ref="pickerRef" v-model="form.endYear" :list="endYearList" :disabled="!form.examType"
            placeholder="选择毕业年份" :custom-style="customStyle" key-label="dictLabel" key-value="dictValue"></ie-picker>
        </uv-form-item>

      </content-card>
      <content-card title="邀请信息">
        <uv-form-item label="邀请码" prop="form.inviteCode">
          <uv-input v-model="form.inviteCode" border="none" placeholder="请输入邀请码（非必填）" font-size="30rpx"
            :custom-style="customStyle">
          </uv-input>
        </uv-form-item>
      </content-card>
      <content-card title="文化素质">
        <uv-form-item label="语文" prop="form.scores.chinese" borderBottom :required="isImproveMode">
          <uv-input v-model="scoresForm.chinese" border="none" type="number" placeholder="满分100分" font-size="30rpx"
            :custom-style="customStyle">
          </uv-input>
        </uv-form-item>
        <uv-form-item label="数学" prop="form.score.mathematics" borderBottom :required="isImproveMode">
          <uv-input v-model="scoresForm.mathematics" border="none" type="number" placeholder="满分100分" font-size="30rpx"
            :custom-style="customStyle">
          </uv-input>
        </uv-form-item>
        <uv-form-item label="外语" prop="form.scores.foreign" borderBottom :required="isImproveMode">
          <uv-input v-model="scoresForm.foreign" border="none" type="number" placeholder="满分100分" font-size="30rpx"
            :custom-style="customStyle">
          </uv-input>
        </uv-form-item>
        <uv-form-item label="物理" prop="form.scores.physics" borderBottom :required="isImproveMode">
          <uv-input v-model="scoresForm.physics" border="none" type="number" placeholder="满分100分" font-size="30rpx"
            :custom-style="customStyle">
          </uv-input>
        </uv-form-item>
        <uv-form-item label="政治" prop="form.scores.political" :required="isImproveMode">
          <uv-input v-model="scoresForm.political" border="none" type="number" placeholder="满分100分" font-size="30rpx"
            :custom-style="customStyle">
          </uv-input>
        </uv-form-item>
      </content-card>
      <content-card v-if="isImproveMode" title="学校信息">
        <uv-form-item label="学校名称" prop="form.name" borderBottom :required="isImproveMode">
          <ie-picker ref="pickerRef" v-model="form.schoolName" :disabled="isSchoolDisabled" placeholder="请选择就读学校"
            :custom-style="customStyle" :custom-label="form.schoolName" @click="handleSchoolSelect"
            :show-arrow="!isSchoolDisabled"></ie-picker>
        </uv-form-item>
        <uv-form-item label="所在班级" prop="form.name" :required="isImproveMode">
          <ie-picker ref="pickerRef" v-model="form.classId" :list="classList" :disabled="!form.schoolId" title="选择班级"
            placeholder="请选择所在班级" :custom-style="customStyle" key-label="name" key-value="classId"></ie-picker>
        </uv-form-item>
      </content-card>
    </uv-form>
    <ie-safe-toolbar :height="84" :shadow="false">
      <view class="px-18 py-16">
        <ie-button @click="handleSubmit">确认提交</ie-button>
      </view>
    </ie-safe-toolbar>
  </ie-page>
</template>

<script lang="ts" setup>
import ContentCard from './components/content-card.vue';
import { useUserStore } from '@/store/userStore';
import { } from '@/api/modules/login';
import { getExamTypes, getExamMajors, getGraduateYears } from '@/api/modules/system';
import { registry, improve } from '@/api/modules/login';
import { useTransferPage } from '@/hooks/useTransferPage';

import { useAppStore } from '@/store/appStore';
import { BindCardInfo, ClassItem, RegisterInfo, SchoolItem, Scores, StudentBindCardInfo } from '@/types/user';
import { DictItem } from '@/types';
import { STUDENT_BIND_INFO } from '@/types/injectionSymbols';
import { getClassList } from '@/api/modules/user';
const userStore = useUserStore();
const appStore = useAppStore();
const { prevData, transferTo, transferBack } = useTransferPage();

// const form2 = ref<Partial<StudentBindCardInfo>>({});
// provide(STUDENT_BIND_INFO, form2);
const form = ref<Partial<BindCardInfo>>({});
const scoresForm = ref<Scores>({})
const formRef = ref();
const customStyle = {
  paddingLeft: '26px'
};
const examTypeList = ref<DictItem[]>([]);
const endYearList = ref<DictItem[]>([]);
const majorTypes = ref<DictItem[]>([]);
const isImproveMode = computed(() => prevData.value.scene === 'phone_improve' || prevData.value.scene === 'card_improve');
const isSchoolDisabled = computed(() => prevData.value.scene === 'card_improve' && prevData.value.card.assignSchoolId);
const isProvinceDisabled = computed(() => prevData.value.scene === 'card_improve' && prevData.value.card.assignLocation);
const isExamTypeDisabled = computed(() => (prevData.value.scene === 'card_improve' && prevData.value.card.assignExamType) || !form.value.location);
const handleProvinceChange = (val: string) => {
  if (isProvinceDisabled.value) {
    return;
  }
  form.value.examType = '';
  form.value.majorType = '';
  loadExamTypes();
}

const handleExamTypeChange = (val: string) => {
  if (isExamTypeDisabled.value) {
    return;
  }
  form.value.majorType = '';
  loadMajorTypes();
  loadGraduateYears();
}

const loadExamTypes = async () => {
  console.log(111, form.value.location)
  if (!form.value.location) {
    return;
  }
  getExamTypes(form.value.location).then(res => {
    examTypeList.value = res.data;
  }).catch(err => {
    console.log('获取考生类别失败', err)
  });
};

const loadMajorTypes = async () => {
  if (!form.value.location || !form.value.examType) {
    return;
  }
  getExamMajors(form.value.location, form.value.examType).then(res => {
    majorTypes.value = res.data;
  }).catch(err => {
    console.log('获取专业类别失败', err)
  });
}

const loadGraduateYears = async () => {
  if (!form.value.location || !form.value.examType) {
    return;
  }
  getGraduateYears(form.value.location, form.value.examType).then(res => {
    endYearList.value = res.data;
  }).catch(err => {
    console.log('获取毕业年份失败', err)
  });
}

const handleMajorChange = (val: string) => {

}

const classList = ref<ClassItem[]>([]);
const handleSchoolSelect = () => {
  if (isSchoolDisabled.value) {
    return;
  }
  transferTo('/pagesSystem/pages/school-select/school-select', {
    data: form.value
  }).then(res => {
    const school = res as SchoolItem;
    form.value.schoolId = school.id;
    form.value.schoolName = school.name;
    console.log(form.value)
    form.value.classId = undefined;
    classList.value = [];
    handleGetClassList();
  });
}
const handleGetClassList = () => {
  if (!form.value.schoolId) {
    return;
  }
  getClassList({ schoolId: form.value.schoolId }).then(res => {
    classList.value = res.data;
    console.log(classList.value)
  });
}


const loginValidate = () => {
  const { nickName, location, examType, endYear } = form.value;
  if (!nickName || nickName.trim() === '') {
    uni.$ie.showToast('请输入姓名');
    return false;
  }
  if (!location || location.trim() === '') {
    uni.$ie.showToast('请选择省份');
    return false;
  }
  if (!examType || examType.trim() === '') {
    uni.$ie.showToast('请选择考生类别');
    return false;
  }
  if (examType === 'VHS') {
    if (!form.value.majorType) {
      uni.$ie.showToast('请选择专业类别');
      return false;
    }
  }
  if (!endYear) {
    uni.$ie.showToast('请选择毕业年份');
    return false;
  }
  if (isImproveMode.value) {
    if (!scoresForm.value.chinese || scoresForm.value.chinese < 0 || scoresForm.value.chinese > 100) {
      uni.$ie.showToast('请输入正确的语文成绩');
      return false;
    }
  }
  if (isImproveMode.value) {
    if (!scoresForm.value.mathematics || scoresForm.value.mathematics < 0 || scoresForm.value.mathematics > 100) {
      uni.$ie.showToast('请输入正确的数学成绩');
      return false;
    }
  }
  if (isImproveMode.value) {
    if (!scoresForm.value.foreign || scoresForm.value.foreign < 0 || scoresForm.value.foreign > 100) {
      uni.$ie.showToast('请输入正确的外语成绩');
      return false;
    }
  }
  if (isImproveMode.value) {
    if (!scoresForm.value.physics || scoresForm.value.physics < 0 || scoresForm.value.physics > 100) {
      uni.$ie.showToast('请输入正确的物理成绩');
      return false;
    }
  }
  if (isImproveMode.value) {
    if (!scoresForm.value.political || scoresForm.value.political < 0 || scoresForm.value.political > 100) {
      uni.$ie.showToast('请输入正确的政治成绩');
      return false;
    }
  }
  if (isImproveMode.value) {
    if (!form.value.schoolId) {
      uni.$ie.showToast('请选择学校');
      return false;
    }
  }
  if (isImproveMode.value) {
    if (!form.value.classId) {
      uni.$ie.showToast('请选择班级');
      return false;
    }
  }
  return true;
}
const handleSubmit = async () => {
  const valid = loginValidate();
  if (valid) {
    let params = {
      ...form.value,
      scores: scoresForm.value,
    };
    try {
      if (isImproveMode.value) {
        const { cardNo, password } = prevData.value;
        params = {
          ...params,
          username: cardNo,
          password,
        }
        console.log('params', params)
        if (prevData.value.scene === 'card_improve') {
          uni.$ie.showLoading();
          const { token } = await registry(params as BindCardInfo);
          if (token) {
            await userStore.login(token);
          }
          uni.$ie.hideLoading();
          uni.$ie.showSuccess('登录成功');
          setTimeout(() => {
            transferTo('/pagesMain/pages/index/index', {
              type: 'reLaunch'
            });
          }, 800);
        } else {
          uni.$ie.showLoading();
          await improve(params as BindCardInfo);
          uni.$ie.hideLoading();
          uni.$ie.showSuccess('绑定成功');
          setTimeout(() => {
            transferTo('/pagesMain/pages/index/index', {
              type: 'reLaunch'
            });
          }, 800);
        }
      } else {
        const { mobile, password, code, uuid } = prevData.value;
        params = {
          ...params,
          mobile,
          password,
          code,
          uuid,
        }
        uni.$ie.showLoading();
        const { token } = await registry(params as RegisterInfo);
        if (token) {
          const isLogin = await userStore.login(token);
          uni.$ie.hideLoading();
          uni.$ie.showSuccess('登录成功');
          if (isLogin) {
            setTimeout(() => {
              transferTo('/pagesMain/pages/index/index', {
                type: 'reLaunch'
              });
            }, 88);
          }
        }
      }
    } catch (error) {
      console.error(error)
    }
  }
}

const gatherInfo = () => {
  const { scene, card, phone, code, uuid } = prevData.value;
  console.log('prevData.value', prevData.value)
  if (scene === 'card_improve') {
    form.value = {
      location: card.assignLocation,
      examType: card.assignExamType,
      endYear: card.endYear,
      majorType: card.majorType,
      schoolId: card.assignSchoolId,
      schoolName: card.assignSchoolName,
      classId: card.classId,
      mobile: phone
      // code
    };
    loadExamTypes();
    handleGetClassList();
  } else if (scene === 'phone_improve') {
    const { nickName, location, examType, endYear, scores } = userStore.userInfo;
    form.value = {
      nickName,
      location,
      examType,
      endYear,
      scores
    };
    scoresForm.value = scores;
    if (location) {
      loadExamTypes();
    }
    if (examType) {
      loadMajorTypes();
    }
    if (endYear) {
      loadGraduateYears();
    }
  }
}

onLoad(() => {
  gatherInfo();
});
</script>

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