<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="pickerPlaceholder" :custom-style="customStyle" key-label="dictLabel" key-value="dictValue"
            :disabled="isProvinceDisabled">
            <template v-if="isProvinceDisabled" #right>
              <ie-image src="/static/image/icon-lock.png" custom-class="w-24 h-30" mode="aspectFill" />
            </template>
          </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="pickerPlaceholder" :custom-style="customStyle" key-label="dictLabel" key-value="dictValue">
            <template v-if="isExamTypeDisabled" #right>
              <ie-image src="/static/image/icon-lock.png" custom-class="w-24 h-30" mode="aspectFill" />
            </template>
          </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="pickerPlaceholder" :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="pickerPlaceholder" :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="isBindMode">
          <uv-input v-model.number="scoresForm.chinese" border="none" type="number" :placeholder="inputPlaceholder"
            font-size="30rpx" :custom-style="customStyle">
          </uv-input>
        </uv-form-item>
        <uv-form-item label="数学" prop="form.score.mathematics" borderBottom :required="isBindMode">
          <uv-input v-model.number="scoresForm.mathematics" border="none" type="number" :placeholder="inputPlaceholder"
            font-size="30rpx" :custom-style="customStyle">
          </uv-input>
        </uv-form-item>
        <uv-form-item label="外语" prop="form.scores.foreign" borderBottom :required="isBindMode">
          <uv-input v-model.number="scoresForm.foreign" border="none" type="number" :placeholder="inputPlaceholder"
            font-size="30rpx" :custom-style="customStyle">
          </uv-input>
        </uv-form-item>
        <uv-form-item label="物理" prop="form.scores.physics" borderBottom :required="isBindMode">
          <uv-input v-model.number="scoresForm.physics" border="none" type="number" :placeholder="inputPlaceholder"
            font-size="30rpx" :custom-style="customStyle">
          </uv-input>
        </uv-form-item>
        <uv-form-item label="政治" prop="form.scores.political" :required="isBindMode">
          <uv-input v-model.number="scoresForm.political" border="none" type="number" :placeholder="inputPlaceholder"
            font-size="30rpx" :custom-style="customStyle">
          </uv-input>
        </uv-form-item>
      </content-card>
      <content-card v-if="isBindMode" title="学校信息">
        <template #right>
          <view class="text-26 text-primary underline" @click="handleNoSchool">没有我的学校班级?</view>
        </template>
        <uv-form-item label="学校名称" prop="form.name" borderBottom :required="isBindMode">
          <ie-picker ref="pickerRef" v-model="form.schoolName" disabled :placeholder="pickerPlaceholder"
            :custom-style="customStyle" :custom-label="form.schoolName" @click="handleSchoolSelect">
            <template v-if="isSchoolDisabled" #right>
              <ie-image src="/static/image/icon-lock.png" custom-class="w-24 h-30" mode="aspectFill" />
            </template>
          </ie-picker>
        </uv-form-item>
        <uv-form-item label="所在班级" prop="form.name" :required="isBindMode">
          <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-46 pt-24">
        <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, improveWithToken } from '@/api/modules/login';
import { useTransferPage } from '@/hooks/useTransferPage';
import { useExamType } from '@/composables/useExamType';
import { useAppStore } from '@/store/appStore';
import { BindCardInfo, CardInfo, ClassItem, LoginInfo, RegisterInfo, SchoolItem, Scores, UserInfo } from '@/types/user';

import { getClassList } from '@/api/modules/user';
import { EnumBindScene, EnumExamRecordType, EnumExamType } from '@/common/enum';
type PrevDataInfo = {
  cardInfo: CardInfo;
  userInfo: UserInfo;
  registerInfo: RegisterInfo;
  scene: EnumBindScene;
  token: string; // 绑定已有账号时需要 token
}

const { form: examTypeForm, examTypeList, examMajorList, provinceList, endYearList } = useExamType();
const userStore = useUserStore();
const { prevData, transferTo, transferBack } = useTransferPage();

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

const isBindMode = computed(() => [EnumBindScene.LOGIN_BIND, EnumBindScene.REGISTER_BIND].includes(prevData.value.scene));
const isSchoolDisabled = computed(() => isBindMode.value && prevData.value.cardInfo.assignSchoolId);
const isProvinceDisabled = computed(() => isBindMode.value && prevData.value.cardInfo.assignLocation);
const isExamTypeDisabled = computed(() => (isBindMode.value && prevData.value.cardInfo.assignExamType) || !examTypeForm.value.location);

const inputPlaceholder = computed(() => {
  return isBindMode.value ? '请输入(提交后不可修改)' : '请输入';
});
const pickerPlaceholder = computed(() => {
  return isBindMode.value ? '请选择(提交后不可修改)' : '请选择';
});

const classList = ref<ClassItem[]>([]);
const showCulture = computed(() => {
  return examTypeForm.value.examType === EnumExamType.OHS;
});
const handleNoSchool = () => {
  uni.showActionSheet({
    title: '联系客服处理',
    itemList: ['拨打电话：400-1797-985'],
    success: (res) => {
      uni.makePhoneCall({
        phoneNumber: '400-1797-985'
      });
    }
  });
}
const handleSchoolSelect = () => {
  // if (isSchoolDisabled.value || !examTypeForm.value.examType) {
  //   return;
  // }
  transferTo('/pagesSystem/pages/school-select/school-select', {
    data: {
      examType: examTypeForm.value.examType,
    }
  }).then(res => {
    if (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 (isBindMode.value) {
      if (!scoresForm.value.chinese || scoresForm.value.chinese < 0 || scoresForm.value.chinese > 100) {
        uni.$ie.showToast('请输入正确的语文成绩');
        return false;
      }
    }
    if (isBindMode.value) {
      if (!scoresForm.value.mathematics || scoresForm.value.mathematics < 0 || scoresForm.value.mathematics > 100) {
        uni.$ie.showToast('请输入正确的数学成绩');
        return false;
      }
    }
    if (isBindMode.value) {
      if (!scoresForm.value.foreign || scoresForm.value.foreign < 0 || scoresForm.value.foreign > 100) {
        uni.$ie.showToast('请输入正确的外语成绩');
        return false;
      }
    }
    if (isBindMode.value) {
      if (!scoresForm.value.physics || scoresForm.value.physics < 0 || scoresForm.value.physics > 100) {
        uni.$ie.showToast('请输入正确的物理成绩');
        return false;
      }
    }
    if (isBindMode.value) {
      if (!scoresForm.value.political || scoresForm.value.political < 0 || scoresForm.value.political > 100) {
        uni.$ie.showToast('请输入正确的政治成绩');
        return false;
      }
    }
  }
  if (isBindMode.value) {
    if (!form.value.schoolId) {
      uni.$ie.showToast('请选择学校');
      return false;
    }
  }
  if (isBindMode.value) {
    if (!form.value.classId) {
      uni.$ie.showToast('请选择班级');
      return false;
    }
  }
  return true;
}
const handleSubmit = async () => {
  const valid = loginValidate();
  if (valid) {
    let params = {
      ...form.value,
      ...examTypeForm.value,
      scores: scoresForm.value,
    };

    // 接下来补充注册登录信息
    try {
      if (prevData.value.scene === EnumBindScene.REGISTER) {
        startRegister(params as BindCardInfo);
      } else {
        // startRegisterBind(params as BindCardInfo);
        // params = {
        //   ...params,
        //   username: prevData.value.registerInfo.username,
        //   password: prevData.value.registerInfo.password,
        // };
        console.log('初步提交信息:', params);
        if (prevData.value.scene === EnumBindScene.LOGIN_BIND) {
          startLoginBind(params as BindCardInfo);
        } else {
          startRegister(params as BindCardInfo);
        }
      }
      // if (isBindMode.value) {
      //   const { cardNo, password } = prevData.value;
      //   params = {
      //     ...params,
      //     username: cardNo,
      //     password,
      //   }
      //   console.log('params', params)
      //   if (prevData.value.scene === 'card_improve') {
      //     startRegister(params as BindCardInfo);
      //   } else {
      //     startRegisterBind(params as BindCardInfo)
      //   }
      // } else {
      //   const { mobile, password, code, uuid } = prevData.value;
      //   params = {
      //     ...params,
      //     mobile,
      //     password,
      //     code,
      //     uuid,
      //   }
      //   startRegister(params as BindCardInfo);
      // }
    } catch (error) {
      console.error(error)
    }
  }
}

const startLoginBind = async (params: BindCardInfo) => {
  uni.$ie.showLoading();
  const token = prevData.value.token;
  await improveWithToken(params, token);
  uni.$ie.hideLoading();
  uni.$ie.showSuccess('绑定成功');
  const userStore = useUserStore();
  userStore.setToken(token);
  setTimeout(() => {
    userStore.getUserInfo();
    goHome();
  }, 50);
}

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

const startRegister = 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'
    });
  }, 800);
}

const gatherInfo = () => {
  console.log('数据预览：', prevData.value)
  // const { scene, card, phone, code, uuid } = prevData.value;
  let { cardInfo = {} as CardInfo, userInfo = {} as UserInfo, registerInfo = {} as RegisterInfo, scene, token } = prevData.value as PrevDataInfo;
  form.value = {
    code: registerInfo.code,
    uuid: registerInfo.uuid,
    mobile: registerInfo.mobile,
    username: registerInfo.username,
    password: registerInfo.password,
  }
  // 注册时，如果以游客身份使用过，则从临时信息中获取省份和考试类型
  if (scene === EnumBindScene.REGISTER) {
    console.log('自动填写临时信息：', userStore.tempInfo)
    examTypeForm.value.location = userStore.tempInfo?.location;
    setTimeout(() => {
      examTypeForm.value.examType = userStore.tempInfo!.examType;
    }, 0);
  } else if ([EnumBindScene.LOGIN_BIND, EnumBindScene.REGISTER_BIND].includes(scene)) {
    // 已有卡信息，补充信息
    if (scene === EnumBindScene.LOGIN_BIND) {
      form.value = {
        ...form.value,
        ...userInfo,
      };
    }
    form.value = {
      ...form.value,
      schoolName: cardInfo.assignSchoolName,
      schoolId: cardInfo.assignSchoolId,
      classId: cardInfo.classId,
      //
      // code: registerInfo.code,
      // uuid: registerInfo.uuid,
      // mobile: registerInfo.mobile,
      // username: registerInfo.username,
      // password: registerInfo.password,
    };
    // 考生相关信息
    examTypeForm.value.location = cardInfo.assignLocation || userInfo.location || '';
    setTimeout(() => {
      examTypeForm.value.examType = cardInfo.assignExamType || userInfo.examType || '';
      examTypeForm.value.endYear = cardInfo.endYear || userInfo.endYear;
    }, 0);
    examTypeForm.value.majorType = userInfo.majorType || '';
    // 
    scoresForm.value = userInfo.scores || {};
    handleGetClassList();
  }
  console.log('初始化整理的信息:')
  console.log('form.value:', form.value)
  console.log('examTypeForm.value:', examTypeForm.value)
  console.log('scoresForm.value:', scoresForm.value)
  // if (scene === EnumBindScene.LOGIN_BIND) {
  // 未登录用户卡注册登录
  // 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>