import { defineComponent } from 'vue'
import {
  CellGroup,
  Field,
  Button,
  Row,
  Col,
  Toast,
  Checkbox,
  Icon,
  Popup
} from 'vant'
import { checkPhone } from '@/helpers/validate'
import request from '@/helpers/request'
import { setLogin, state } from '@/state'
import { removeAuth, setAuth } from '@/helpers/utils'
import styles from './index.module.less'
import logo from './images/logo.png'
import iconTeacher from '@/common/images/icon_teacher.png'
import activeButtonIcon from '@common/images/icon_checkbox.png'
import inactiveButtonIcon from '@common/images/icon_checkbox_default.png'
import ColPopup from '@/components/col-popup'
import InviteCode from './invite-code'
import TeacherChange from './teacher-change'

export default defineComponent({
  name: 'login',
  data() {
    const query = this.$route.query
    return {
      id: query.id,
      username: '',
      teacherInfo: {} as any, // 当前老师信息
      imgCodeStatus: false,
      checked: false,
      teacherChangeStatus: false,
      changeInfo: {} as any // 更换老师信息
    }
  },
  computed: {
    codeDisable() {
      console.log(this.username ? true : false)
      return (this as any).username ? true : false
    }
  },
  async mounted() {
    removeAuth()
    try {
      const res = await request.get('/api-student/open/getTeacher', {
        params: {
          userId: this.id
        }
      })
      console.log(res)
      this.teacherInfo = res.data || {}
    } catch {}
  },
  methods: {
    async onSendCode() {
      // 发送验证码
      if (!checkPhone(this.username)) {
        return Toast('请输入正确的手机号码')
      }
      if (!this.checked) {
        return Toast('请阅读并同意协议')
      }
      this.imgCodeStatus = true
    },
    previewProtocol(type: string) {
      if (type === 'user') {
        this.$router.push({
          path: '/registerProtocol',
          query: {
            showHeader: 1
          }
        })
      } else if (type === 'privacy') {
        this.$router.push({
          path: '/privacyProtocol',
          query: {
            showHeader: 1
          }
        })
      }
    },
    async onLoginSuccess(isUpdate: boolean = false) {
      try {
        const res = await request.get('/api-student/open/bindTeacher', {
          params: {
            phone: this.username,
            userId: this.id,
            isUpdate
          }
        })
        this.changeInfo = res.data || {}
        const { old, now } = res.data
        if (!isUpdate && now && old && now.userId !== old.userId) {
          this.teacherChangeStatus = true
        } else {
          this.$router.push('/inviteSuccess')
        }
      } catch {}
    }
  },
  render() {
    return (
      <div class={styles.login}>
        <div class={styles.loginTitle}>
          <img src={logo} alt="" />
          <p>
            <span class={styles.txt}>酷乐秀</span>
            <span>你的器乐学习好帮手</span>
          </p>
        </div>
        <div class={styles.teacherInfo}>
          <div class={styles.teacherLogo}>
            <img src={this.teacherInfo.avatar || iconTeacher} alt="" />
          </div>
          <div class={styles.teacherName}>
            <span>{this.teacherInfo.realName}</span>{' '}
            老师邀请您注册酷乐秀一起体验器乐学习的乐趣吧！
          </div>
        </div>
        <CellGroup class={styles.margin34} border={false}>
          <Row style={{ marginBottom: '16px' }}>
            <Col span={24} class={styles.formTitle}>
              手机号
            </Col>
            <Col span={24} class="van-hairline--bottom">
              <Field
                v-model={this.username}
                name="手机号"
                placeholder="请输入您的手机号"
                type="tel"
                maxlength={11}
              />
            </Col>
          </Row>
          <div class={styles.itips}>未注册的手机号码将自动注册酷乐秀账号</div>
        </CellGroup>
        <div class={styles.margin34}>
          <Button
            round
            block
            type="primary"
            disabled={!this.codeDisable}
            onClick={this.onSendCode}
          >
            获取短信验证码
          </Button>
        </div>
        <div class={styles.protocol}>
          <Checkbox
            v-model={this.checked}
            v-slots={{
              icon: (props: any) => (
                <Icon
                  class={styles.boxStyle}
                  name={props.checked ? activeButtonIcon : inactiveButtonIcon}
                  size="15"
                />
              )
            }}
          >
            我已阅读并同意
          </Checkbox>
          <span
            class={styles.protocolText}
            onClick={() => {
              this.previewProtocol('user')
            }}
          >
            《用户注册协议》
          </span>
          和
          <span
            class={styles.protocolText}
            onClick={() => {
              this.previewProtocol('privacy')
            }}
          >
            《隐私政策》
          </span>
        </div>

        <ColPopup v-model={this.imgCodeStatus}>
          {this.imgCodeStatus && (
            <InviteCode
              phone={this.username}
              onLoginSuccess={this.onLoginSuccess}
            />
          )}
        </ColPopup>

        <Popup show={this.teacherChangeStatus} round>
          <TeacherChange
            changeInfo={this.changeInfo}
            onClose={() => {
              this.teacherChangeStatus = false
              this.$router.push('/inviteSuccess')
            }}
            onChangeTeacher={(isUpdate: boolean) => {
              this.onLoginSuccess(isUpdate)
            }}
          />
        </Popup>
      </div>
    )
  }
})
