import {
  Popup,
  Field,
  Form,
  CellGroup,
  Button,
  Toast,
  Picker,
  DatetimePicker,
  Overlay
} from 'vant'
import ImgCode from '@/components/col-img-code'
import { defineComponent, onMounted, reactive } from 'vue'
import styles from './index.module.less'
import bg from './images/bg.png'
import rejectLogo from './images/rejectLogo.png'
import rejectSchool from './images/rejest-school.png'
import subTitle from './images/subTitle.png'
import centerLogo from './images/center.png'
import studentText from './images/studentText.png'
import { useRoute, useRouter } from 'vue-router'
import icon_arrow from './images/icon_arrow.png'
import rejectBtn from './images/rejectBtn.png'
import studentSuccess from './images/studentSuccess.png'
import request from '@/helpers/request'
import dayjs from 'dayjs'
import { removeAuth, setAuth } from '@/helpers/utils'
import { state } from '@/helpers/helpState'
import { setLogin } from '@/state'
export default defineComponent({
  name: 'tenantStudentRejest',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const forms = reactive({
      gender: '',
      name: '',
      phone: '',
      subjectId: '',
      subjectName: '',
      tenantGroupName: '',
      tenantGroupId: '',
      birthdate: '',
      code: '',
      genderName: '',
      tenantId: route.query.tenantId
    })

    const data = reactive({
      birthdate: new Date(dayjs().year(), dayjs().month() + 1, dayjs().date()),
      schoolName: route.query.name || '',
      id: route.query.tenantId,
      tenantGroupId: route.query.tenantGroupId,
      userSchoolName: '',
      cityName: '', // 所属城市
      showArea: false,
      checked: true,
      success: false,
      areaList: {} as any,
      sendMsg: '获取验证码',
      imgCodeStatus: false,
      subjectList: [],
      searchStatus: false,
      openStatus: false,
      dateState: false,
      tenantGroupList: [] as any,
      tenantGroupStatus: false,
      genderState: false,
      genderList: [
        { text: '男', value: '1' },
        { text: '女', value: '0' }
      ],
      showSuccess: false,
      secondConfirm: false,
      minDate: new Date(1980, 0, 1),
      maxDate: new Date()
    })
    const handleSubmit = async () => {
      try {
        if (!forms.name) {
          Toast('请输入姓名')
          return
        }
        if (!forms.gender) {
          Toast('请选择性别')
          return
        }

        if (!forms.birthdate) {
          Toast('请选择出生年月')
          return
        }
        if (!forms.phone) {
          Toast('请输入手机号')
          return
        }
        if (!forms.code) {
          Toast('请输入验证码')
          return
        }
        if (!forms.subjectId) {
          Toast('请选择声部')
          return
        }
        if (!forms.tenantGroupId) {
          Toast('请选择小组')
          return
        }

        const loginCode = route.query.taId ? true : false
        const res = await request.post('/api-tenant/open/student/save', {
          data: { ...forms, loginCode },
          hideLoading: true
        })
        if (res.code == 200) {
          if (loginCode) {
            onLogin(res.data)
          } else {
            data.showSuccess = true
          }
        }

        if (res.code == 5004) {
          data.secondConfirm = true
          data.userSchoolName = res.msg
        }
      } catch {
        //
      }
    }

    const onLogin = async code => {
      try {
        if (!code) {
          Toast('注册失败，请重新注册')
          return
        }
        const res = await request.post('/api-auth/smsLogin', {
          requestType: 'form',
          data: {
            clientId: 'student',
            clientSecret: 'student',
            phone: forms.phone,
            smsCode: code
          }
        })
        const { authentication } = res.data
        setAuth(authentication.token_type + ' ' + authentication.access_token)

        const userCash = await request.get(
          '/api-student/student/queryUserInfo',
          {
            initRequest: true // 初始化接口
          }
        )
        setLogin(userCash.data)

        router.replace({
          path: '/train-tool',
          query: {
            ...route.query
          }
        })
      } catch {
        //
      }
    }

    const getSubjectList = async () => {
      try {
        const res = await request.get('/api-tenant/open/subject/queryPage', {
          params: { page: 1, rows: 9999, queryType: 'list' }
        })
        const rows = res.data.rows || []
        const tempList: any = []
        rows.forEach((item: any) => {
          // if (item.parentSubjectId > 0) {
          tempList.push({
            text: item.name,
            value: item.id
          })
          // }
        })

        data.subjectList = tempList
        // res.data.rows.map((item: any) => {
        //   return {
        //     text: item.name,
        //     value: item.id
        //   }
        // }) || []
      } catch (e) {
        console.log(e)
      }
    }
    const confirmSubject = (val: any) => {
      forms.subjectName = val.text
      forms.subjectId = val.value
      data.searchStatus = false
    }

    const confirmTenant = (val: any) => {
      console.log(val, 'confirmTenant')
      forms.tenantGroupName = val.text
      forms.tenantGroupId = val.value
      data.tenantGroupStatus = false
    }

    const confirmDate = (val: any) => {
      forms.birthdate = dayjs(val).format('YYYY-MM-DD')
      data.dateState = false
    }
    const tenantGroupList = async () => {
      try {
        const res = await request.post('/api-tenant/open/tenantGroup/page', {
          data: {
            page: 1,
            rows: 999,
            tenantId: data.id
          }
        })

        data.tenantGroupList =
          res.data.rows.map((item: any) => {
            return {
              text: item.name,
              value: item.id
            }
          }) || []
      } catch {
        //
      }
    }
    onMounted(() => {
      removeAuth()
      if (data.tenantGroupId) {
        forms.tenantGroupId = data.tenantGroupId as any
      }
      tenantGroupList()
      getSubjectList()
    })
    const confirmGender = (val: any) => {
      if (val.value) {
        forms.gender = val.value
        forms.genderName = val.text
      } else {
        forms.gender = ''
        forms.genderName = ''
      }
      data.genderState = false
    }
    /** 发送验证码 */
    const onSendSms = async () => {
      if (!forms.phone) {
        Toast('请输入手机号码')
        return
      }
      if (!/^1[3456789]\d{9}$/.test(forms.phone)) {
        Toast('手机号码格式不正确')
        return
      }
      // await request.post('/api-student/code/sendSmsCode', {
      //   requestType: 'form',
      //   data: {
      //     mobile: forms.phone,
      //     type: 'REGISTER'
      //   }
      // })
      // onCountDown()
      // setTimeout(() => {
      //   Toast('验证码已发送')
      // }, 100)
      data.imgCodeStatus = true
    }

    const onCountDown = () => {
      data.sendMsg = '60s'
      let count = 60
      const timer = setInterval(() => {
        count--
        data.sendMsg = `${count}s`
        if (count <= 0) {
          data.sendMsg = '获取验证码'
          clearInterval(timer)
        }
      }, 1000)
    }

    const downApp = () => {
      window.open(location.origin + '/student/#/download')
      data.showSuccess = false
    }

    const submitSecond = async () => {
      try {
        await request.post('/api-tenant/open/student/save', {
          data: { ...forms, updateTenant: true },
          hideLoading: true
        })
        data.showSuccess = true
        data.secondConfirm = false
      } catch (e) {
        console.log(e)
      }
    }

    return () => (
      <>
        <div class={styles.videoClass}>
          {/* <ColHeader
          class={styles.classHeader}
          border={false}
          isFixed={false}
          background="#fff"
        /> */}
          <div class={styles.resjetStudentWrap}>
            <img src={rejectLogo} class={styles.rejectLogo} alt="" />
            <img src={studentText} class={styles.studentText} alt="" />
            <img src={bg} class={styles.bgWrap} alt="" />
            <div class={styles.schoolNameWrap}>
              <img src={rejectSchool} class={styles.rejectSchool} alt="" />
              <p>{data.schoolName}</p>
            </div>
            <img class={styles.centerLogo} src={centerLogo} alt="" />
            <div class={styles.infoWrap}>
              <div class={styles.infoWrapCore}>
                <img src={subTitle} class={styles.subTitle} alt="" />

                <Form onSubmit={() => handleSubmit()}>
                  <CellGroup class={styles.group} border={false}>
                    <Field
                      class={styles.noArrow}
                      inputAlign="right"
                      label="姓名"
                      placeholder="请输入姓名"
                      maxlength={14}
                      v-model={forms.name}

                      // onUpdate: modelValue={(val: string) => {
                      //   forms.nickname = val.trim();
                      // }}
                    />
                    <Field
                      readonly
                      inputAlign="right"
                      label="性别"
                      placeholder="请选择性别"
                      v-model={forms.genderName}
                      onClick={() => {
                        data.genderState = true
                      }}
                      // onUpdate: modelValue={(val: string) => {
                      //   forms.nickname = val.trim();
                      // }}
                    >
                      {{
                        button: () => (
                          <img
                            style={{
                              display: 'block',
                              width: '12px',
                              height: '12px'
                            }}
                            src={icon_arrow}
                          />
                        )
                      }}
                    </Field>
                    <Field
                      readonly
                      inputAlign="right"
                      label="出生日期"
                      placeholder="请选择出生日期"
                      maxlength={20}
                      v-model={forms.birthdate}
                      onClick={() => {
                        data.dateState = true
                      }}
                      // onUpdate: modelValue={(val: string) => {
                      //   forms.nickname = val.trim();
                      // }}
                    >
                      {{
                        button: () => (
                          <img
                            style={{
                              display: 'block',
                              width: '12px',
                              height: '12px'
                            }}
                            src={icon_arrow}
                          />
                        )
                      }}
                    </Field>
                    <Field
                      inputAlign="right"
                      label="手机号"
                      class={styles.noArrow}
                      maxlength={11}
                      placeholder="手机号码"
                      v-model={forms.phone}
                    />
                    <div class={styles.tips}>
                      手机号码为酷乐秀机构版登录账号
                    </div>

                    <Field
                      class={styles.inputCode}
                      inputAlign="left"
                      label="验证码"
                      labelWidth={0}
                      v-model={forms.code}
                      maxlength={6}
                    >
                      {{
                        button: () => (
                          <Button
                            disabled={data.sendMsg.includes('s')}
                            class={styles.sendBtn}
                            onClick={() => onSendSms()}
                          >
                            {data.sendMsg}
                          </Button>
                        )
                      }}
                    </Field>
                    <Field
                      border={false}
                      inputAlign="right"
                      label="声部"
                      placeholder="请选择声部"
                      readonly
                      v-model={forms.subjectName}
                      onClick={() => (data.searchStatus = true)}
                    >
                      {{
                        button: () => (
                          <img
                            style={{
                              display: 'block',
                              width: '12px',
                              height: '12px'
                            }}
                            src={icon_arrow}
                          />
                        )
                      }}
                    </Field>
                    {data.tenantGroupId ? (
                      ''
                    ) : (
                      <Field
                        border={false}
                        inputAlign="right"
                        label="小组"
                        placeholder="请选择小组"
                        readonly
                        v-model={forms.tenantGroupName}
                        onClick={() => (data.tenantGroupStatus = true)}
                      >
                        {{
                          button: () => (
                            <img
                              style={{
                                display: 'block',
                                width: '12px',
                                height: '12px'
                              }}
                              src={icon_arrow}
                            />
                          )
                        }}
                      </Field>
                    )}
                  </CellGroup>
                </Form>
              </div>
              <img
                src={rejectBtn}
                onClick={() => {
                  handleSubmit()
                }}
                class={styles.rejectBtn}
                alt=""
              />
            </div>
          </div>
          <Popup
            show={data.searchStatus}
            position="bottom"
            round
            columns-field-names={{ text: '' }}
            safe-area-inset-bottom
            onClose={() => (data.searchStatus = false)}
            onClosed={() => (data.openStatus = false)}
          >
            <Picker
              columns={data.subjectList}
              onCancel={() => {
                data.searchStatus = false
              }}
              onConfirm={confirmSubject}
            ></Picker>
          </Popup>

          <Popup
            show={data.tenantGroupStatus}
            position="bottom"
            round
            columns-field-names={{ text: '' }}
            safe-area-inset-bottom
            onClose={() => (data.tenantGroupStatus = false)}
            onClosed={() => (data.openStatus = false)}
          >
            <Picker
              columns={data.tenantGroupList}
              onCancel={() => {
                data.tenantGroupStatus = false
              }}
              onConfirm={confirmTenant}
            ></Picker>
          </Popup>

          <Popup
            show={data.dateState}
            position="bottom"
            round
            columns-field-names={{ text: '' }}
            safe-area-inset-bottom
            onClose={() => (data.dateState = false)}
            onClosed={() => (data.dateState = false)}
          >
            <DatetimePicker
              min-date={data.minDate}
              max-date={data.maxDate}
              type="date"
              v-model={data.birthdate}
              onCancel={() => {
                data.dateState = false
              }}
              onConfirm={confirmDate}
            ></DatetimePicker>
          </Popup>

          <Popup
            show={data.genderState}
            position="bottom"
            round
            columns-field-names={{ text: '' }}
            safe-area-inset-bottom
            onClose={() => (data.genderState = false)}
            onClosed={() => (data.genderState = false)}
          >
            <Picker
              columns={data.genderList}
              onCancel={() => {
                data.genderState = false
              }}
              onConfirm={confirmGender}
            ></Picker>
          </Popup>

          <Overlay show={data.showSuccess} z-index={1000}>
            <div class={styles.showWrap}>
              <img class={styles.showWrapTop} src={studentSuccess} alt="" />
              <h2>恭喜您已成功登记为</h2>
              <h4>
                {data.schoolName} <span>【学员】</span>{' '}
              </h4>
              <p>请下载酷乐秀机构版APP进行学习</p>
              <div class={styles.downApp} onClick={downApp}>
                立即下载
              </div>
            </div>
          </Overlay>

          <Popup
            show={data.secondConfirm}
            position="center"
            round
            onClose={() => (data.secondConfirm = false)}
            onClosed={() => (data.secondConfirm = false)}
          >
            <div class={styles.secondWrap}>
              <h2>提示</h2>
              <p>
                当前账号已存在 <span>【{data.userSchoolName}】</span>{' '}
                ，是否确认更换到
                <span>{data.schoolName}</span>
                吗?
              </p>
              <div class={styles.buttonWrap}>
                <div
                  class={styles.closeBtn}
                  onClick={() => {
                    data.secondConfirm = false
                  }}
                >
                  {' '}
                  取消
                </div>
                <div class={styles.submitBtn} onClick={submitSecond}>
                  确定
                </div>
              </div>
            </div>
          </Popup>

          {data.imgCodeStatus ? (
            <ImgCode
              v-model:value={data.imgCodeStatus}
              phone={forms.phone}
              registerType="REGISTER"
              onClose={() => {
                data.imgCodeStatus = false
              }}
              onSendCode={onCountDown}
            />
          ) : null}
        </div>
      </>
    )
  }
})
