import { defineComponent, onMounted, reactive, ref, nextTick } from 'vue'
import { Image, Popup, showDialog, Sticky, Tab, Tabs } from 'vant'
import styles from './index.module.less'
// import { useRect } from '@vant/use'
import Apply from './component/apply'
import Payment from './component/payment'
import Order from './component/order'
import { useRoute, useRouter } from 'vue-router'
import qs from 'query-string'
import { goWechatAuth, setLogout } from '@/state'
import request from '@/helpers/request'
import { browser, getUrlCode, removeAuth } from '@/helpers/utils'
import ODialog from '@/components/o-dialog'

export default defineComponent({
  name: 'pre-apply',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const state = reactive({
      tabValue: 'apply',
      heightV: 235,
      registerInfo: {} as any,
      purchase: false, // 购买状态
      register: true, // 是否注册
      // showPopup: false,
      code: '' as any,
      dialogStatus: false,
      dialogMessage: '',
      studentReadStatus: false, // 学生在读
      // 是否开启微信登录（测试使用）默认为false
      testIsWeixin: false
    })
    const showPopup = ref(false)
    // const noPaymentList = ref([
    //   '1656572729093021697',
    //   '1656488025144713217',
    //   '1661221287237820418',
    //   '1661222465069686785',
    //   '1714545500178460674'
    // ])
    // console.log(
    //   '提示乐团报名失败',
    //   route.query.id,
    //   noPaymentList.value.indexOf(route.query.id as string)
    // )
    // if (route.query.id && noPaymentList.value.indexOf(route.query.id as string) != -1) {
    //   console.log('提示乐团报名失败')
    //   // 提示乐团报名失败
    //   showPopup.value = true
    // }
    const onNext = async (name: string) => {
      if (name === 'payment') {
        await getRegisterStatus()
      }

      nextTick(() => {
        state.tabValue = name

        window.scrollTo(0, 0)
      })
    }

    const getRegisterStatus = async () => {
      try {
        const { data } = await request.get(
          '/api-student/orchestraRegister/registerStatus/' + route.query.id
        )
        state.registerInfo = data || {}

        // 判断学生是否在读
        if (data.learningOrchestra?.length) {
          state.studentReadStatus = true
        }

        if (data.registerStatus === 'OUTOF_ORCHESTRA') {
          nextTick(() => {
            state.tabValue = 'apply'
          })
        } else {
          // 判断是否报名注册过
          state.register = data.register
          if (data.register) {
            nextTick(() => {
              state.tabValue = 'payment'
            })
          }

          // 	购买状态, 判断是否已经购买完了
          if (data.purchase) {
            state.purchase = data.purchase
            nextTick(() => {
              state.tabValue = 'order'
            })
          }
        }

        // INITIATION_SURVEY: '启蒙调查',
        // PRE_REGISTER: '预报名',
        // REGISTER: '乐团报名',
        // PARENT_TEACHER_REGISTRATION "家长会报名"
        // DOING: '乐团交付',
        // DONE: '已交付'
        // CLOSE: '已交付'
        // 判断乐团报名，只有 乐团报名 乐团交付 已交付才可以报名
        const oStatus = data.status // 乐团状态
        if (
          oStatus !== 'REGISTER' &&
          oStatus !== 'DOING' &&
          oStatus !== 'DONE' &&
          oStatus !== 'PARENT_TEACHER_REGISTRATION'
        ) {
          state.dialogMessage = '乐团建设中，请稍等'
          state.dialogStatus = true
          return
        }

        // 判断乐团
        if (data.registerOrchestra >= 1) {
          state.dialogMessage = '您已在其它乐团'
          state.dialogStatus = true
          return
        }

        // 判断是否有openId 并且 purchase
        // if (!data.openId && !data.purchase) {
        //   if (browser().weixin) {
        //     // 微信公众号支付
        //     //授权
        //     const code = getUrlCode()
        //     if (!code) {
        //       goAuth(data.wxAppId)
        //     } else {
        //       state.code = code
        //     }
        //   }
        // }

        // nextTick(() => {
        //   state.tabValue = 'order'
        // })
      } catch {
        //
      }
    }

    const getRegisterInfo = async (val: string) => {
      // 重新查询状态
      if (val === 'apply') {
        try {
          const { data } = await request.get(
            '/api-student/orchestraRegister/registerStatus/' + route.query.id
          )
          state.registerInfo = data || {}
        } catch {
          //
        }
      }

      // document.getElementById('app')?.scrollTo(0, 0)
      window.scrollTo(0, 0)
    }

    // const goAuth = (wxAppId: string) => {
    //   // 用户授权
    //   const urlNow = encodeURIComponent(window.location.href)
    //   const scope = 'snsapi_base' //snsapi_userinfo   //静默授权 用户无感知
    //   const appid = wxAppId || 'wx8654c671631cfade'
    //   const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${urlNow}&response_type=code&scope=${scope}&state=STATE&connect_redirect=1#wechat_redirect`
    //   window.location.replace(url)
    // }

    const getAppIdAndCode = async () => {
      try {
        const { data } = await request.get('/api-student/open/paramConfig/wechatAppId')
        // 判断是否有微信appId
        if (data) {
          // goAuth(data)
          goWechatAuth(data)
        }
      } catch {
        //
      }
    }

    const onLoutout = () => {
      setLogout()
      removeAuth()
      const query = {
        returnUrl: route.path,
        ...route.query
      } as any

      window.location.href =
        window.location.origin + window.location.pathname + '#/loginMusic?' + qs.stringify(query)

      router.replace({
        path: '/loginMusic',
        query: query
      })
    }

    // 先请求接口 判断是否有code
    if (state.testIsWeixin) {
      getRegisterStatus()
    } else {
      if (browser().weixin) {
        // 微信公众号支付
        //授权
        const code = getUrlCode()
        if (!code) {
          getAppIdAndCode()
        } else {
          state.code = code
          getRegisterStatus()
        }
      } else {
        onLoutout()
      }
    }

    return () => (
      <div class={styles.preApply}>
        <div class={styles.banner}>
          <p class={styles.orchestraName}>{state.registerInfo.orchestraName}</p>
        </div>

        <Sticky position="top">
          <Tabs
            lineWidth={20}
            lineHeight={4}
            v-model:active={state.tabValue}
            onChange={(val: any) => getRegisterInfo(val)}
          >
            <Tab title="基础信息" name="apply" disabled={state.purchase}></Tab>
            <Tab title="工具准备" name="payment" disabled={state.purchase || !state.register}></Tab>
            <Tab title="完成报名" name="order" disabled={!state.register}></Tab>
          </Tabs>
        </Sticky>

        {state.tabValue === 'apply' && (
          <Apply
            onNext={onNext}
            code={state.code}
            registerInfo={state.registerInfo}
            schoolSystem={state.registerInfo.schoolSystem}
          />
        )}
        {state.tabValue === 'payment' && <Payment onNext={onNext} />}
        {state.tabValue === 'order' && <Order onNext={onNext} />}

        {/* <Popup
          v-model:show={state.showPopup}
          round
          style={{ width: '92%' }}
          closeOnClickOverlay={false}
        >
          <div class={styles.popupContainer}>
            <div class={styles.dialogTitle}>
              <i></i>
              提示
            </div>

            <p class={styles.popupTips}>请使用微信打开</p>
          </div>
        </Popup> */}

        <ODialog
          title="提示"
          v-model:show={state.dialogStatus}
          message={state.dialogMessage}
          confirmButtonText="确定"
          onConfirm={() => {
            setLogout()
            const query = {
              returnUrl: route.path,
              ...route.query
            } as any
            router.replace({
              path: '/loginMusic',
              query: query
            })
          }}
        />

        {/* 学生在读 */}
        <ODialog
          title="提示"
          v-model:show={state.studentReadStatus}
          message={'您已在其他乐团在读，请退团再报名该乐团。'}
          confirmButtonText="确认"
          showCancelButton={false}
          onConfirm={() => {
            // state.submitStatus = false
            onLoutout()
          }}
        />

        <Popup
          v-model:show={showPopup.value}
          round
          style={{ width: '88%', marginTop: '-6vh' }}
          closeOnClickOverlay={false}
          class={styles.wxPopupDialog}
        >
          <div class={styles.popupContainer}>
            <p class={styles.title1}>温馨提示</p>
            <p class={styles.popupTips}>乐团报名时间已过，请等待通知</p>
          </div>
        </Popup>
      </div>
    )
  }
})
