import { Tag, Button, Popup, Form, Field, RadioGroup, Radio } from 'vant';
import { computed, defineComponent, onMounted, reactive } from 'vue';
import styles from './detail.module.less';
import MSticky from '@/components/m-sticky';
// import MVideo from '@/components/m-video';
import { useRoute, useRouter } from 'vue-router';
import request from '@/helpers/request';
import loginSuccess from './images/login-success.png';
import bannerBg from './images/banner1.png';

import SelectStudent from '@/views/student-register/modal/select-student';

export default defineComponent({
  name: 'activation-register',
  setup() {
    const route = useRoute();
    const forms = reactive({
      activationCodeRecordId: route.query.activationCodeRecordId,
      statusShow: false,
      schoolId: null as any,
      schoolAreaId: null, // 学校区域编号
      activationCode: route.query.code as any, // 互通码
      paymentType: '', // 支付类型
      paymentChannel: '',
      multi_user_limit: 1, // 限制注册学生数量
      // popupShow: false,
      registerDetails: {} as any,
      details: [] as any[],
      // schoolType: '', // 学校类型
      gradeYear: '', // 学制
      schoolInstrumentSetType: null as any,
      submitLoading: false,
      showSelectStudent: false, // 选择学生
      studentList: [], // 手机号关联学生列表
      studentItem: {} as any, // 选择的学生

      registerAllFlag: false // 是否全部登记
    });

    const studentInfo = reactive({
      nickname: '',
      areaName: '',
      schoolName: '',
      currentGradeNum: '' as any,
      gender: 1 as any,
      registerType: null as any // 报名类型
    });

    const btnText = computed(() => {
      if (forms.registerAllFlag) {
        return '该账号学生已全部登记';
      }
      if (forms.studentItem?.registerFlag) {
        return '该学生已登记';
      }
      return '登记';
    });

    const getDetail = async () => {
      try {
        const { data } = await request.post(
          '/edu-app/open/instrumentRegister/getStudentActivationRecord',
          {
            requestType: 'form',
            data: {
              mobile: route.query.mobile
            }
          }
        );

        const result = data || [];
        result.forEach((item: any) => {
          item.userId = item.activationCodeRecordId;
        });
        forms.studentList = result;

        let count = 0;
        forms.studentList.forEach((item: any) => {
          if (!item.registerFlag && !forms.studentItem?.userId) {
            forms.studentItem = item;
          }
          if (item.registerFlag) {
            count++;
          }
        });
        if (forms.studentList.length === count) {
          forms.registerAllFlag = true;
          forms.studentItem = forms.studentList[0];
        }
        formatData(forms.studentItem);
      } catch {
        //
      }
    };

    const formatData = (item: any) => {
      studentInfo.nickname = item.nickname;
      studentInfo.gender = item.gender;
      const tempArea = [] as any;
      if (item.provinceName) {
        tempArea.push(item.provinceName);
      }
      if (item.cityName) {
        tempArea.push(item.cityName);
      }
      if (item.regionName) {
        tempArea.push(item.regionName);
      }
      studentInfo.areaName = tempArea.join(' ');

      studentInfo.schoolName = item.schoolName;
      studentInfo.currentGradeNum =
        item.currentGradeNum + '年级' + item.currentClass + '班';
    };

    const onSubmit = async () => {
      forms.submitLoading = true;
      try {
        const { data } = await request.post(
          '/edu-app/open/instrumentRegister/instrumentUseRegister',
          {
            requestType: 'form',
            data: {
              activationCodeRecordId: forms.studentItem.activationCodeRecordId
            }
          }
        );

        forms.statusShow = true;
      } catch {}
      forms.submitLoading = false;
    };

    onMounted(() => {
      getDetail();
    });
    return () => (
      <div class={[styles['student-register']]}>
        <img src={bannerBg} class={styles.bannerBg} />
        <div class={styles.studentRegisterContainer}>
          <div class={[styles.studentSection]}>
            <Form labelAlign="left" class={styles.registerForm}>
              <Field
                clearable={false}
                required
                inputAlign="right"
                label="学生姓名"
                placeholder="请输入学生姓名"
                autocomplete="off"
                readonly
                center
                maxlength={14}
                v-model={studentInfo.nickname}>
                {{
                  extra: () =>
                    forms.studentList.length > 1 && (
                      <div
                        class={[styles.selectStudentGroup]}
                        onClick={() => (forms.showSelectStudent = true)}>
                        <span>切换学生</span>
                      </div>
                    )
                }}
              </Field>
              <Field
                clearable={false}
                required
                inputAlign="right"
                label="学生性别"
                placeholder="请选择性别"
                autocomplete="off">
                {{
                  input: () => (
                    <RadioGroup
                      checked-color="linear-gradient( 135deg, #31C7FF 0%, #007AFE 100%)"
                      v-model={studentInfo.gender}
                      direction="horizontal"
                      disabled>
                      <Tag
                        size="large"
                        type="primary"
                        color={
                          !(studentInfo.gender === 1)
                            ? '#F5F6FA'
                            : 'linear-gradient( 135deg, #31C7FF 0%, #007AFE 100%)'
                        }
                        textColor={
                          !(studentInfo.gender === 1) ? '#626264' : '#fff'
                        }
                        class={styles.radioSection}>
                        <Radio class={styles.radioItem} name={1}></Radio>男
                      </Tag>
                      <Tag
                        size="large"
                        type="primary"
                        color={
                          !(studentInfo.gender === 0)
                            ? '#F5F6FA'
                            : 'linear-gradient( 135deg, #31C7FF 0%, #007AFE 100%)'
                        }
                        textColor={
                          !(studentInfo.gender === 0) ? '#626264' : '#fff'
                        }
                        class={styles.radioSection}>
                        <Radio class={styles.radioItem} name={0}></Radio>女
                      </Tag>
                    </RadioGroup>
                  )
                }}
              </Field>
              <Field
                clearable={false}
                required
                inputAlign="right"
                label="所在地区"
                placeholder="请选择地区"
                readonly
                clickable={false}
                modelValue={studentInfo.areaName}
              />
              <Field
                clearable={false}
                required
                inputAlign="right"
                label="互通学校"
                placeholder="请选择互通学校"
                readonly
                clickable={false}
                modelValue={studentInfo.schoolName}
              />
              <Field
                clearable={false}
                required
                inputAlign="right"
                label="所在班级"
                placeholder="请选择班级"
                readonly
                clickable={false}
                modelValue={studentInfo.currentGradeNum}
              />
            </Form>
          </div>

          <MSticky position="bottom">
            <div class={styles.paymentContainer}>
              <Button
                onClick={() => {
                  onSubmit();
                }}
                round
                block
                disabled={
                  forms.submitLoading ||
                  forms.registerAllFlag ||
                  forms.studentItem.registerFlag
                }
                loading={forms.submitLoading}>
                {btnText.value}
              </Button>
            </div>
          </MSticky>
        </div>

        <Popup
          v-model:show={forms.showSelectStudent}
          round
          position="bottom"
          safeAreaInsetBottom
          closeable>
          <SelectStudent
            showAdd={false}
            studentItem={forms.studentItem}
            list={forms.studentList}
            onClose={() => (forms.showSelectStudent = false)}
            onConfirm={(val: any) => {
              console.log(val, 'val');
              formatData(val);
              forms.studentItem = val;
            }}
          />
        </Popup>

        <Popup
          show={forms.statusShow}
          style={{
            background: 'transparent',
            overflow: 'visible !important'
          }}>
          <div class={styles.popupContainer}>
            <img class={styles.title} src={loginSuccess} />

            <div class={styles.content}>
              <span>{forms.studentItem.nickname}</span>
              已登记成功，乐器将在开课时发至学生
            </div>
            <div class={styles.pBtnGroup}>
              <Button
                round
                block
                onClick={() => {
                  forms.statusShow = false;
                  forms.studentItem.registerFlag = true;

                  forms.studentList.forEach((item: any) => {
                    if (item.userId === forms.studentItem?.userId) {
                      item.registerFlag = true;
                    }
                  });
                }}
                color="linear-gradient( 305deg, #007AFE 0%, #31C7FF 100%)">
                我知道了
              </Button>
            </div>
          </div>
        </Popup>
      </div>
    );
  }
});
