<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="examTypeForm.location" :list="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="examTypeForm.examType" :list="examTypeList" :disabled="isExamTypeDisabled"
            placeholder="选择考生类别" :custom-style="customStyle" key-label="dictLabel" key-value="dictValue"
            :show-arrow="!isExamTypeDisabled"></ie-picker>
        </uv-form-item>
        <uv-form-item v-if="examTypeForm.examType === 'VHS'" label="专业类别" prop="majorType" borderBottom required>
          <ie-picker ref="pickerRef" v-model="examTypeForm.majorType" :list="examMajorList"
            :disabled="!examTypeForm.examType" placeholder="选择专业类别" :custom-style="customStyle" key-label="dictLabel"
            key-value="dictValue"></ie-picker>
        </uv-form-item>
        <uv-form-item label="毕业年份" prop="year" required>
          <ie-picker ref="pickerRef" v-model="examTypeForm.endYear" :list="endYearList"
            :disabled="!examTypeForm.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 v-if="showCulture" title="文化素质">
        <uv-form-item label="语文" prop="form.scores.chinese" borderBottom :required="isImproveMode">
          <uv-input v-model="scoresForm.chinese" border="none" type="number" placeholder="请输入" 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="请输入" 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="请输入" 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="请输入" 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="请输入" 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 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-30 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 { registry, improve } from '@/api/modules/login';
import { useTransferPage } from '@/hooks/useTransferPage';
import { useExamType } from '@/composables/useExamType';
import { useAppStore } from '@/store/appStore';
import { BindCardInfo, ClassItem, SchoolItem, Scores } from '@/types/user';

import { getClassList } from '@/api/modules/user';
const { form: examTypeForm, examTypeList, examMajorList, provinceList, endYearList } = useExamType();
const userStore = useUserStore();
const appStore = useAppStore();
const { prevData, transferTo, transferBack } = useTransferPage();

const form = ref<Partial<BindCardInfo>>({});
const scoresForm = ref<Scores>({})
const formRef = ref();
const customStyle = {
  paddingLeft: '26px'
};

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) || !examTypeForm.value.location);
const handleProvinceChange = (val: string) => {
  if (isProvinceDisabled.value) {
    return;
  }
  form.value.examType = '';
  form.value.majorType = '';
}

const classList = ref<ClassItem[]>([]);
const showCulture = computed(() => {
  return examTypeForm.value.examType === 'OHS';
});
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 = () => {
  form.value = {
    ...form.value,
    ...examTypeForm.value,
  }
  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 (showCulture.value) {
    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') {
          startLogin(params as BindCardInfo);
        } else {
          startBind(params as BindCardInfo)
        }
      } else {
        const { mobile, password, code, uuid } = prevData.value;
        params = {
          ...params,
          mobile,
          password,
          code,
          uuid,
        }
        startLogin(params as BindCardInfo);
      }
    } catch (error) {
      console.error(error)
    }
  }
}

const startBind = async (params: BindCardInfo) => {
  uni.$ie.showLoading();
  await improve(params);
  uni.$ie.hideLoading();
  uni.$ie.showSuccess('绑定成功');
  userStore.getUserInfo();
  goHome();
}

const startLogin = async (params: BindCardInfo) => {
  uni.$ie.showLoading();
  const { token } = await registry(params);
  if (token) {
    const isLogin = await userStore.login(token);
    uni.$ie.hideLoading();
    uni.$ie.showSuccess('登录成功');
    if (isLogin) {
      goHome();
    }
  }
}

const goHome = () => {
  setTimeout(() => {
    transferTo('/pagesMain/pages/index/index', {
      type: 'reLaunch'
    });
  }, 600);
}

const gatherInfo = () => {
  // const { scene, card, phone, code, uuid } = prevData.value;
  const { cardInfo, userInfo, loginInfo } = prevData.value;
  console.log('prevData.value', prevData.value)
  if (userStore.tempInfo?.location) {
    examTypeForm.value.location = userStore.tempInfo?.location;
    setTimeout(() => {
      examTypeForm.value.examType = userStore.tempInfo!.examType;
    }, 0)
  }
  console.log('examTypeForm', examTypeForm)
  const { scene, phone } = loginInfo;
  const { nickName, location, examType, majorType: userMajorType, endYear: userEndYear, scores } = userInfo;
  const { assignLocation, assignExamType, majorType, endYear: cardEndYear, assignSchoolId, assignSchoolName, classId, } = cardInfo;
  if (scene === 'card_improve') {
    // 未登录用户卡注册登录
    form.value = {
      nickName,
      scores,
      // 下面 3 个属性卡的优先级更高
      location: assignLocation || location,
      examType: assignExamType || examType,
      endYear: cardEndYear || userEndYear,
      majorType: majorType || userMajorType,
      schoolId: assignSchoolId,
      schoolName: assignSchoolName,
      classId: classId,
      mobile: phone
      // code
    };
    handleGetClassList();
  } else if (scene === 'phone_improve') {
    // 已登录用户绑卡
    // const { nickName, location, examType, endYear, scores } = userStore.userInfo;
    // const { nickName, location, examType, endYear, scores } = prevData.value.userInfo;
    form.value = {
      nickName,
      location,
      examType,
      // endYear,
      scores
    };
    scoresForm.value = scores;
  }
}

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

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