<template>
  <div class="main">
    <h4>欢迎注册慧添翼课后辅导系统</h4>
    <h5>请完善您的资料信息</h5>
    <van-form @submit="submit">
      <van-field name="radio" colon label="注册身份" required>
        <template #input>
          <van-radio-group v-model="formData.user_role" direction="horizontal">
            <van-radio v-for="role in initial_roles" :name="role.value">{{
              role.label
            }}</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-field
        required
        v-model="formData.real_name"
        colon
        label="姓名"
        :placeholder="'请输入' + (is_teacher ? '您的真实' : '学生') + '姓名'"
      />
      <van-field name="radio" colon label="性别" required>
        <template #input>
          <van-radio-group v-model="formData.sex" direction="horizontal">
            <van-radio :name="1">男</van-radio>
            <van-radio :name="2">女</van-radio>
          </van-radio-group>
        </template>
      </van-field>
<!--      <van-field-->
<!--        required-->
<!--        v-model="formData.mobile"-->
<!--        colon-->
<!--        label="联系方式"-->
<!--        :rules="[-->
<!--          {-->
<!--            required: true,-->
<!--            pattern: /^1\d{10}$/,-->
<!--            message: '请输入正确的手机号码',-->
<!--          },-->
<!--        ]"-->
<!--      />-->
      <template v-if="is_teacher">
        <van-field v-model="formData.academic" colon label="学历" required />
        <van-field
          v-model="formData.experience"
          colon
          label="工作经历"
          type="textarea"
          autosize
          rows="3"
        />
      </template>
      <template v-else>
        <van-field
          required
          v-model="formData.teacher_name"
          is-link
          colon
          readonly
          name="picker"
          label="授课老师"
          @click="showPicker = true"
        />
        <van-popup v-model:show="showPicker" position="bottom">
          <van-picker
            :columns="teachers"
            @confirm="onSelectTeacher"
            @cancel="showPicker = false"
          />
        </van-popup>
        <van-field
          v-model="formData.experience"
          label-width="90"
          colon
          label="过往学习经历"
          type="textarea"
          autosize
          rows="3"
        />
        <van-field v-model="formData.father_job" colon label="父亲职业" />
        <van-field v-model="formData.mother_job" colon label="母亲职业" />
      </template>
      <div class="buttons">
        <van-button
          type="primary"
          :disabled="!can_submit"
          block
          native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, reactive, ref } from "vue";
import useUser from "~/store/user";
import { useRouter } from "vue-router";
import {
  HtyApplyUser,
  HtyBaseRoles,
  HtyStates,
  HtySuperRoles,
  NotifyTypes,
  WeixinUserInfo,
} from "~/types";
import {
  Button,
  CellGroup,
  Empty,
  Field,
  Form,
  Grid,
  GridItem,
  Picker,
  Popup,
  Radio,
  RadioGroup,
  showFailToast,
  showSuccessToast,
} from "vant";
import useNotify from "~/store/notify";

export default defineComponent({
  name: "guest-register",
  components: {
    [Button.name!]: Button,
    [Empty.name!]: Empty,
    [Field.name!]: Field,
    [CellGroup.name!]: CellGroup,
    [Grid.name!]: Grid,
    [GridItem.name!]: GridItem,
    [Picker.name!]: Picker,
    [Radio.name!]: Radio,
    [RadioGroup.name!]: RadioGroup,
    [Form.name!]: Form,
    [Popup.name!]: Popup,
  },
  props: ["params"],
  setup() {
    const router = useRouter();
    const {
      store,
      setRole,
      getValidTeachers,
      chooseRole,
      register,
      claimTeacher,
      getUserByUnionid,
      rollback,
    } = useUser(router);
    const { notify_uc } = useNotify();

    console.log("register...", store.wxPayload, store.unionid);

    const formData = reactive({
      real_name: "",
      user_role: HtyBaseRoles.STUDENT,
      mobile: "",
      experience: "",
      sex: 1,
      academic: "",
      teacher_id: "",
      teacher_name: "",
      mother_job: "",
      father_job: "",
    });
    const showPicker = ref(false);

    getValidTeachers();

    const teachers = computed(() =>
      store.teachers.valid.map((x) => ({ text: x.real_name, value: x.hty_id }))
    );

    const has_teacher = computed(
      () => !is_teacher.value && store.teachers.mine.length > 0
    );

    const initial_roles = [
      { value: HtyBaseRoles.STUDENT, label: "学生" },
      { value: HtyBaseRoles.TEACHER, label: "老师" },
    ];
    const is_teacher = computed(
      () => formData.user_role === HtyBaseRoles.TEACHER
    );
    const activeRoles = computed(() =>
      store.current.roles?.filter((r) => r.role_status === HtyStates.ACTIVE)
    );

    const can_submit = computed(() => {
      let { real_name, sex, user_role, academic, teacher_id } =
        formData;
      return (
        real_name &&
        sex &&
        (user_role === HtyBaseRoles.TEACHER ? academic : teacher_id)
      );
    });

    const onSelectTeacher = ({ selectedOptions }: any) => {
      let [{ text, value }] = selectedOptions;
      formData.teacher_name = text;
      formData.teacher_id = value;
      showPicker.value = false;
    };

    const submit = async () => {
      let {
        unionid,
        wxPayload: { nickName, avatarUrl, openid },
      } = store;
      if (!unionid || !openid) {
        showFailToast({
          message:
            "未获取到UnionID或OpenID，请点击屏幕右上角•●•选择重新进入小程序",
        });
        return;
      }
      let exist = await getUserByUnionid(unionid);
      if (exist) {
        if (exist.enabled && exist.is_registered) {
          showFailToast({
            message: "用户已注册，请点击屏幕右上角•●•选择重新进入小程序",
          });
          return;
        }
        if (exist.enabled) {
          showFailToast({ message: "用户已注册，但尚未通过审核，请联系老师审核。" });
        }
        showFailToast({ message: "用户已注册，请联系你的老师。" });
      }

      let {
        real_name,
        sex,
        user_role,
        academic,
        experience,
        teacher_id,
        mother_job,
        father_job,
      } = formData;
      let data = {
        real_name,
        unionid,
        openid,
        sex,
        role: user_role,
        meta: { nickName, avatarUrl, mother_job, father_job } as WeixinUserInfo,
        teacher_id,
      } as HtyApplyUser;
      let notify_type: NotifyTypes,
        is_student = user_role === HtyBaseRoles.STUDENT;
      if (!is_student) {
        data.teacher_info = { academic, experience };
        notify_type = NotifyTypes.TeacherRegister;
      } else {
        data.student_info = { experience };
        data.enabled = true;
        notify_type = NotifyTypes.StudentRegister;
      }
      // 1. save user info
      let { hty_id, infos, info_roles } = await register(data);
      // @ts-ignore
      let user_app_id = infos[0]?.id,
        user_info_role_id = info_roles[0]?.the_id as string;
      try {
        if (is_student) {
          // 2. for student user, claim teacher
          await claimTeacher(hty_id, teacher_id);
        }
        showSuccessToast({ message: "注册成功！" });
        // 3. send weixin notification to related manager(admin for teacher, claimed teacher for student)
        if (is_student) {
          await notify_uc(
            { hty_id: teacher_id, hty_id2: hty_id, notify_type },
            HtyBaseRoles.TEACHER
          );
        } else {
          await notify_uc({ hty_id, notify_type }, HtySuperRoles.ADMIN);
        }
        await router.replace("/?status=2");
      } catch (e) {
        // if claim teacher failed, we need to rollback saved user info
        await rollback([hty_id, user_app_id, user_info_role_id]);
        showFailToast("注册失败！请联系管理员！");
      }
    };

    return {
      showPicker,
      teachers,
      is_teacher,
      activeRoles,
      chooseRole,
      setRole,
      store,
      initial_roles,
      formData,
      submit,
      onSelectTeacher,
      can_submit,
      has_teacher,
    };
  },
});
</script>

<style scoped lang="less">
.main {
  height: 100%;
  overflow-y: auto;
  h4,
  h5 {
    text-align: center;
    color: #555555;
  }

  .buttons {
    margin-top: 1rem;
    padding: 0.32rem;
  }

  .text-warning {
    font-size: small;
    color: #ed6a0c;
  }
}
</style>
