import request from '@/helpers/request'
import {
  Button,
  CellGroup,
  Dialog,
  Field,
  Form,
  Picker,
  Popup,
  Radio,
  RadioGroup,
  showToast,
  Tag
} from 'vant'
import { defineComponent, onMounted, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import styles from '../index.module.less'
import { setLogout } from '@/state'

// 乐团交付，乐团停止或关闭，有新的交付团；则不允许报名
const classList: any = []
for (let i = 1; i <= 40; i++) {
  classList.push({ text: i + '班', value: i })
}

export default defineComponent({
  name: 'apply',
  props: {
    schoolSystem: {
      type: String,
      default: 'sixYearSystem' // 默认为六年制
    },
    registerInfo: {
      type: Object,
      defualt: {}
    },
    code: {
      type: String,
      default: ''
    }
  },
  emits: ['next'],
  setup(props, { slots, attrs, emit }) {
    const route = useRoute()
    const router = useRouter()
    const state = reactive({
      // code: '' as any, // 微信授权code码
      detail: {} as any, // 学生详情
      currentGrade: [
        { text: '一年级', value: 1 },
        { text: '二年级', value: 2 },
        { text: '三年级', value: 3 },
        { text: '四年级', value: 4 },
        { text: '五年级', value: 5 }
      ], // 年级数组列表
      classList: classList,
      subjectList: [] as any, // 声部列表
      gradeStatus: false,
      classStatus: false,
      subjectStatus: false,
      pattern: /^1(3|4|5|6|7|8|9)\d{9}$/,
      nameReg: /^[\u4E00-\u9FA5]+$/,
      subjectChangeStatus: false // 更换声部时
    })
    const forms = reactive({
      username: null,
      sex: null as any,
      currentGrade: null,
      currentGradeTxt: null, // 年级编号
      currentClass: '', // 班级
      currentClassTxt: null, // 年级编号
      registerSubjectId: '',
      registerSubjectTxt: null, // 所在声部
      parentName: null,
      phone: null
    })

    // 获取乐团报名信息
    const studentRegister = async () => {
      try {
        const { data } = await request.get(
          '/api-student/orchestraRegister/register/' + route.query.id
        )
        const detail = data || {}

        state.detail = detail

        const grade: any = state.currentGrade.find((item: any) => item.value == detail.currentGrade)
        const cls: any = state.classList.find((item: any) => item.value == detail.currentClass)
        const subjects: any = state.subjectList.find(
          (item: any) => item.value == detail.registerSubjectId
        )
        forms.username = detail.username
        forms.sex = detail.sex ? 1 : 0
        forms.currentGrade = detail.currentGrade
        forms.currentGradeTxt = grade.text
        forms.currentClass = detail.currentClass
        forms.currentClassTxt = cls.text
        forms.registerSubjectId = detail.registerSubjectId
        forms.registerSubjectTxt = subjects.text
        forms.parentName = detail.parentName
        forms.phone = detail.phone
      } catch {
        //
      }
    }

    // 获取声部信息
    const getSubjects = async () => {
      try {
        const subjects = await request.post(
          '/api-student/open/orchestraSubjectConfig/pageByOrchestraId',
          {
            data: {
              orchestraId: route.query.id,
              page: 1,
              rows: 100
            }
          }
        )
        const rows = subjects.data.rows || []
        rows.forEach((item: any) => {
          state.subjectList.push({
            text: item.name,
            value: item.subjectId
          })
        })
      } catch {
        //
      }
    }

    const validator = (val: any) => {
      // 校验函数返回 true 表示校验通过，false 表示不通过
      return state.nameReg.test(val) && val.length >= 2 && val.length <= 15
    }
    const message = (value: any) => {
      if (!value) {
        return '请填写学员真实姓名'
      } else if (!state.nameReg.test(value)) {
        return '学员姓名必须为中文'
      } else if (value.length < 2 || value.length > 15) {
        return '学员姓名必须为2~15个字'
      } else {
        return ''
      }
    }

    // 乐团报名
    const onSubmit = async () => {
      try {
        const params: any = {
          orchestraId: route.query.id,
          schoolId: state.detail.schoolId,
          ...forms
        }
        // 判断是否已报过名
        if (state.detail.id) {
          params.id = state.detail.id
        }
        await request.post('/api-student/orchestraRegister/save', {
          data: {
            ...params,
            code: props.code
          }
        })
        setTimeout(() => {
          showToast('报名成功')
          emit('next', 'payment')
        }, 100)
      } catch {
        //
      }
    }

    onMounted(async () => {
      // state.code = route.query.code || ''
      // console.log('pre register code: ' + state.code)
      await getSubjects()
      // 判断学年制
      if (props.schoolSystem === 'sixYearSystem') {
        state.currentGrade.push({ text: '六年级', value: 6 })
      }
      await studentRegister()

      // 判断是否有授权码
      // if (!props.code) {
      //   setLogout()
      //   const query = {
      //     returnUrl: route.path,
      //     ...route.query
      //   } as any
      //   router.replace({
      //     path: '/loginMusic',
      //     query: query
      //   })
      // }
    })
    return () => (
      <div class={styles.preApplyC}>
        <Form validateFirst scrollToError onSubmit={onSubmit} ref="form" class={styles.form}>
          <div class={styles.applyTitle}>学生信息</div>
          <CellGroup inset class={styles.applyCellGroup}>
            <Field
              required
              label="学生信息"
              placeholder="请填写学生真实姓名"
              inputAlign="right"
              v-model={forms.username}
              maxlength={15}
              rules={[{ validator, message }]}
            />
            <Field
              required
              label="性别"
              inputAlign="right"
              rules={[{ required: true, message: '请选择性别' }]}
            >
              {{
                input: () => (
                  <RadioGroup v-model={forms.sex}>
                    <Tag
                      size="large"
                      type="primary"
                      plain={!(forms.sex === 1)}
                      class={styles.radioSection}
                      round
                    >
                      <Radio class={styles.radioItem} name={1}></Radio>男生
                    </Tag>
                    <Tag
                      size="large"
                      type="primary"
                      plain={!(forms.sex === 0)}
                      class={styles.radioSection}
                      round
                    >
                      <Radio class={styles.radioItem} name={0}></Radio>女生
                    </Tag>
                  </RadioGroup>
                )
              }}
            </Field>
            <Field
              required
              label="年级"
              inputAlign="right"
              readonly
              isLink
              placeholder="请选择年级"
              v-model={forms.currentGradeTxt}
              onClick={() => (state.gradeStatus = true)}
              rules={[{ required: true, message: '请选择年级' }]}
            />
            <Field
              required
              label="班级"
              inputAlign="right"
              readonly
              isLink
              placeholder="请选择班级"
              v-model={forms.currentClassTxt}
              onClick={() => (state.classStatus = true)}
              rules={[{ required: true, message: '请选择班级' }]}
            />
          </CellGroup>

          <div class={styles.applyTitle}>声部信息</div>
          <CellGroup inset class={styles.applyCellGroup}>
            <Field
              required
              label="声部"
              inputAlign="right"
              readonly
              isLink
              placeholder="请选择声部"
              v-model={forms.registerSubjectTxt}
              onClick={() => {
                if (state.subjectList.length <= 0) {
                  showToast('暂无报名声部')
                  return
                }

                // 切换订单时判断是否有支付中和已支付的订单，并且已注册过
                if (props.registerInfo?.orderNumber > 0 && props.registerInfo?.register) {
                  state.subjectChangeStatus = true
                  return
                }
                state.subjectStatus = true
              }}
              rules={[{ required: true, message: '请选择声部' }]}
            />
          </CellGroup>

          <div class={styles.applyTitle}>家长信息</div>
          <CellGroup inset class={styles.applyCellGroup}>
            <Field
              required
              label="家长姓名"
              inputAlign="right"
              placeholder="请填写家长真实姓名"
              v-model={forms.parentName}
              maxlength={15}
              rules={[{ required: true, message: '请填写家长真实姓名' }]}
            />
            <Field
              required
              label="手机号"
              inputAlign="right"
              placeholder="请输入手机号"
              v-model={forms.phone}
              maxlength={11}
              type="tel"
              rules={[{ pattern: state.pattern, message: '输入监护人手机号码有误' }]}
            />
          </CellGroup>

          <div class={'btnGroup'} style={{ paddingTop: '30px' }}>
            <Button type="primary" round block native-type="submit">
              下一步
            </Button>
          </div>
        </Form>

        {/* 年级 */}
        <Popup
          v-model:show={state.gradeStatus}
          position="bottom"
          round
          safeAreaInsetBottom
          // duration={0}
          lazyRender={false}
        >
          <Picker
            showToolbar
            columns={state.currentGrade}
            onCancel={() => (state.gradeStatus = false)}
            onConfirm={(val: any) => {
              const selectedOption = val.selectedOptions[0]
              forms.currentGrade = selectedOption.value
              forms.currentGradeTxt = selectedOption.text
              state.gradeStatus = false
            }}
          />
        </Popup>
        {/* 班级 */}
        <Popup v-model:show={state.classStatus} position="bottom" round>
          <Picker
            showToolbar
            columns={state.classList}
            onCancel={() => (state.classStatus = false)}
            onConfirm={(val: any) => {
              const selectedOption = val.selectedOptions[0]
              forms.currentClass = selectedOption.value
              forms.currentClassTxt = selectedOption.text
              state.classStatus = false
            }}
          />
        </Popup>
        {/* 声部 */}
        <Popup v-model:show={state.subjectStatus} position="bottom" round>
          <Picker
            showToolbar
            columns={state.subjectList}
            onCancel={() => (state.subjectStatus = false)}
            onConfirm={(val: any) => {
              const selectedOption = val.selectedOptions[0]
              forms.registerSubjectId = selectedOption.value
              forms.registerSubjectTxt = selectedOption.text
              state.subjectStatus = false
            }}
          />
        </Popup>

        <Dialog
          v-model:show={state.subjectChangeStatus}
          message={'您修改了乐团声部，若确认更换，请先将原声部订单退款，完成后修改声部重新缴费。'}
          messageAlign="left"
          confirmButtonText="去退款"
          cancelButtonText="选错了"
          showCancelButton
          onConfirm={() => {
            emit('next', 'order')
          }}
        >
          {{
            title: () => (
              <div class={styles.dialogTitle}>
                <i></i>
                修改声部
              </div>
            )
          }}
        </Dialog>
      </div>
    )
  }
})
