<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-[15px]"
            font-size="15px" :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="areaName" key-value="shortName"
            :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"
            @click="handlePreCheck('examType')" @change="handleExamTypeChange">
            <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="examMajor" borderBottom required>
          <ie-picker ref="pickerRef" v-model="examTypeForm.examMajor" :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" @click="handlePreCheck('endYear')"></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="15px"
            :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="isScoreRequired">
          <uv-input v-model.number="scoresForm.chinese" border="none" type="number" :placeholder="inputPlaceholder"
            font-size="15px" :custom-style="customStyle">
          </uv-input>
        </uv-form-item>
        <uv-form-item label="数学" prop="form.score.mathematics" borderBottom :required="isScoreRequired">
          <uv-input v-model.number="scoresForm.mathematics" border="none" type="number" :placeholder="inputPlaceholder"
            font-size="15px" :custom-style="customStyle">
          </uv-input>
        </uv-form-item>
        <uv-form-item label="外语" prop="form.scores.foreign" borderBottom :required="isScoreRequired">
          <uv-input v-model.number="scoresForm.foreign" border="none" type="number" :placeholder="inputPlaceholder"
            font-size="15px" :custom-style="customStyle">
          </uv-input>
        </uv-form-item>
        <uv-form-item label="物理" prop="form.scores.physics" borderBottom :required="isScoreRequired">
          <uv-input v-model.number="scoresForm.physics" border="none" type="number" :placeholder="inputPlaceholder"
            font-size="15px" :custom-style="customStyle">
          </uv-input>
        </uv-form-item>
        <uv-form-item label="政治" prop="form.scores.political" :required="isScoreRequired">
          <uv-input v-model.number="scoresForm.political" border="none" type="number" :placeholder="inputPlaceholder"
            font-size="15px" :custom-style="customStyle">
          </uv-input>
        </uv-form-item>
      </content-card>

      <content-card v-if="showSchoolInfo" 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"
            @click="handlePreCheck('classId')">
            <template v-if="isClassDisabled" #right>
              <ie-image src="/static/image/icon-lock.png" custom-class="w-24 h-30" mode="aspectFill" />
            </template>
          </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, EnumUserType } 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 isScoreRequired = computed(() => examTypeForm.value.examType === EnumExamType.OHS);
const isBindMode = computed(() => [EnumBindScene.LOGIN_BIND, EnumBindScene.REGISTER_BIND].includes(prevData.value.scene));
const isSchoolDisabled = computed(() => isBindMode.value && !!prevData.value.cardInfo.assignSchoolId);
const isClassDisabled = computed(() => isBindMode.value && !!prevData.value.cardInfo.classId);
const isProvinceDisabled = computed(() => isBindMode.value && !!prevData.value.cardInfo.assignLocation);
const isExamTypeDisabled = computed(() => (isBindMode.value && !!prevData.value.cardInfo.assignExamType));
const contactPhone = computed(() => userStore.orgInfo.contactPhone);
const inputPlaceholder = computed(() => {
  return isBindMode.value ? '请输入(提交后不可修改)' : '请输入';
});
const pickerPlaceholder = computed(() => {
  return isBindMode.value ? '请选择(提交后不可修改)' : '请选择';
});

const showSchoolInfo = computed(() => {
  return isBindMode.value;
})

const classList = ref<ClassItem[]>([]);
const showCulture = computed(() => {
  return examTypeForm.value.examType === EnumExamType.OHS;
});
const handleNoSchool = () => {
  if (!contactPhone.value) {
    uni.$ie.showToast('请联系客服处理');
    return;
  }
  uni.showActionSheet({
    title: '联系客服处理',
    itemList: [`拨打电话：${contactPhone.value}`],
    success: (res) => {
      uni.makePhoneCall({
        phoneNumber: contactPhone.value
      });
    }
  });
}
const handleSchoolSelect = () => {
  if (isSchoolDisabled.value) {
    return;
  }
  if (!examTypeForm.value.examType) {
    uni.$ie.showToast('请选择考生类别');
    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 handlePreCheck = (type: string) => {
  switch (type) {
    case 'examType': {
      if (isExamTypeDisabled.value) {
        return true;
      }
      const { location } = examTypeForm.value;
      if (!location) {
        uni.$ie.showToast('请选择省份');
        return false;
      }
      return true;
    }
    case 'endYear': {
      const { examType } = examTypeForm.value;
      const result = handlePreCheck('examType');
      if (!result) {
        return false;
      }
      if (!examType) {
        uni.$ie.showToast('请选择考生类别');
        return false;
      }
      return true;
    }
    case 'classId': {
      const { schoolId } = form.value;
      if (!schoolId) {
        uni.$ie.showToast('请选择学校');
        return false;
      }
      return true;
    }
  }
}


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.examMajor) {
      uni.$ie.showToast('请选择专业类别');
      return false;
    }
  }
  if (!endYear) {
    uni.$ie.showToast('请选择毕业年份');
    return false;
  }
  if (showCulture.value) {
    if (isScoreRequired.value) {
      if (!scoresForm.value.chinese) {
        uni.$ie.showToast('请输入语文成绩');
        return false;
      }
    }
    if (scoresForm.value?.chinese && (scoresForm.value.chinese < 0 || scoresForm.value.chinese > 100)) {
      uni.$ie.showToast('请输入正确的语文成绩');
      return false;
    }
    // 
    if (isScoreRequired.value) {
      if (!scoresForm.value.mathematics) {
        uni.$ie.showToast('请输入数学成绩');
        return false;
      }
    }
    if (scoresForm.value?.mathematics && (scoresForm.value.mathematics < 0 || scoresForm.value.mathematics > 100)) {
      uni.$ie.showToast('请输入正确的数学成绩');
      return false;
    }
    //
    if (isScoreRequired.value) {
      if (!scoresForm.value.foreign) {
        uni.$ie.showToast('请输入外语成绩');
        return false;
      }
    }
    if (scoresForm.value?.foreign && (scoresForm.value.foreign < 0 || scoresForm.value.foreign > 100)) {
      uni.$ie.showToast('请输入正确的外语成绩');
      return false;
    }
    // 
    if (isScoreRequired.value) {
      if (!scoresForm.value.physics) {
        uni.$ie.showToast('请输入物理成绩');
        return false;
      }
    }
    if (scoresForm.value?.physics && (scoresForm.value.physics < 0 || scoresForm.value.physics > 100)) {
      uni.$ie.showToast('请输入正确的物理成绩');
      return false;
    }
    //
    if (isScoreRequired.value) {
      if (!scoresForm.value.political) {
        uni.$ie.showToast('请输入政治成绩');
        return false;
      }
    }
    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 handleExamTypeChange = () => {
  scoresForm.value = {};
}

const handleSubmit = async () => {
  const valid = loginValidate();
  if (valid) {
    let params = {
      ...form.value,
      ...examTypeForm.value,
      scores: scoresForm.value,
    };

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

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

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

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

const gatherInfo = () => {
  console.log('数据预览：', 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,
    };
    // 考生相关信息
    examTypeForm.value.location = cardInfo.assignLocation || userInfo.location || '';
    console.log(examTypeForm.value.location)
    setTimeout(() => {
      examTypeForm.value.examType = cardInfo.assignExamType || userInfo.examType || undefined;
      examTypeForm.value.endYear = cardInfo.endYear || userInfo.endYear;
    }, 0);
    examTypeForm.value.examMajor = userInfo.examMajor || '';
    // 
    scoresForm.value = userInfo.scores || {};
    handleGetClassList();
  }
}

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

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