import { AuthMenuType } from '../../@types'
import { IndustryType, ResultType, ScaleType } from '../../@types/enumHelper'
import { userDictionmary } from '../../config/dictionary'
import router from '../../router'
import { UserGetter } from '../../store/modules/user/getters'
import { getStoreGetter, setStoreState } from '../../store/utils'
import message from '../../utils/message'
import { formatEnum } from '../../utils/tools'
import { SessionStorage } from 'quasar'
// import message from '@/utils/message'
import { nextTick, reactive, ref } from 'vue'
interface RegistParams {
  mobile: string
  verfityCode: string
  companyName: string
  username: string
  industry: number
  scale: number
  password: string
  confirmPwd: string
}

const useUserRegistModule = () => {
  const userModel: RegistParams = reactive({
    mobile: ref(''),
    verfityCode: ref(''),
    companyName: ref(''),
    username: ref(''),
    industry: ref(0),
    scale: ref(0),
    password: ref(''),
    confirmPwd: ref('')
  })
  const userRule = reactive({
    mobileRule: [(val: any) => !!/^1(3|4|5|6|7|8|9)\d{9}$/.test(val) || '请填写你的手机账号信息'],
    verfityCodeRule: [(val: any) => val.length != 6 || '请填写验证码信息'],
    passwordRule: [(val: any) => (val.length >= 6 && val.length <= 30) || '请输入6-30位密码'],
    confirmPwdRule: [(val: any) => val == userModel.password || '两次密码不一致'],
    companyNameRule: [(val: any) => !!val || '请您填写企业名称'],
    usernameRule: [(val: any) => !!val || '请您填写联系人名称'],
    industryRule: [(val: any) => val != 0 || '请选择企业所属行业'],
    scaleRule: [(val: any) => val != 0 || '请选择']
  })

  const stateManager = reactive({
    sendCodeStatus: ref(0),
    validateRules: ref([]),
    countDown: ref(0),
    timeProvide: ref(),
    canSubmitSetupOne: ref(true),
    subCode: ref(false),
    subSetupOne: ref(false),
    isSended: ref(false),
    verifyCodeLength: ref(6),
    currentSetup: ref('1'),
    induArray: ref(formatEnum(IndustryType)),
    scaleArray: ref(formatEnum(ScaleType)),
    subRegist: ref(false)
  })

  const validateSendStatus = () => {
    if (stateManager.sendCodeStatus == 2) return
    const mr = stateManager.validateRules[0] as any
    nextTick(() => {
      stateManager.sendCodeStatus = mr.hasError ? 0 : 1
    })
  }

  const setValidateRules = (el: HTMLElement) => {
    (stateManager.validateRules as Array<HTMLElement>).push(el)
  }

  const checkCodeStatus = () => {
    if (SessionStorage.has(userDictionmary.sendCodeTimeSpan)) {
      const oldSend = SessionStorage.getItem<number>(userDictionmary.sendCodeTimeSpan) ?? 0
      const cnt = Math.abs(oldSend - Date.parse(new Date().toString())) / 1000

      if (cnt >= 60) {
        SessionStorage.remove(userDictionmary.sendCodeTimeSpan)
        stateManager.countDown = 0
        stateManager.sendCodeStatus = 0
        validateSendStatus()
      } else {
        stateManager.countDown = 60 - cnt
        stateManager.sendCodeStatus = 2
        stateManager.timeProvide = setInterval(beginCutDown, 1000)
      }
    }
  }

  const sendCode = () => {
    if (!stateManager.subCode && stateManager.countDown == 0 && stateManager.sendCodeStatus == 1) {
      stateManager.subCode = true
      //TODO: 完成接口调用
      setTimeout(() => {
        stateManager.isSended = true
        stateManager.countDown = 60
        stateManager.sendCodeStatus = 2
        SessionStorage.set(userDictionmary.sendCodeTimeSpan, Date.parse(new Date().toString()))
        stateManager.subCode = false
        stateManager.timeProvide = setInterval(beginCutDown, 1000)
      }, 3000)
    }
  }

  const beginCutDown = () => {
    stateManager.countDown--
    if (stateManager.countDown == 0) {
      SessionStorage.remove(userDictionmary.sendCodeTimeSpan)
      stateManager.sendCodeStatus = 0
      validateSendStatus()
      if (stateManager.timeProvide) {
        clearInterval(stateManager.timeProvide)
        stateManager.timeProvide = null
      }
    }
  }

  const submitValidateCode = () => {
    if (!stateManager.subSetupOne) {
      stateManager.subSetupOne = true
      let isError = false
      for (let i = 0; i < stateManager.validateRules.length; i++) {
        const mr = stateManager.validateRules[i] as any
        if(mr){
          mr.validate()
        }
      }
      for (let i = 0; i < stateManager.validateRules.length; i++) {
        const mr = stateManager.validateRules[i] as any
        if (mr&&mr.hasError) {
          isError = true
          break
        }
      }
      if (!isError && userModel.verfityCode.length == stateManager.verifyCodeLength && stateManager.isSended) {
        setTimeout(() => {
          stateManager.subSetupOne = false
          if (userModel.verfityCode == '888888') {
            stateManager.currentSetup = '2'
            stateManager.isSended = false
          } else {
            message.warnMsg('验证码错误，请重新输入')
          }
        }, 3000)
      } else {
        stateManager.subSetupOne = false
      }
    }
  }

  const doRegist = () => {
    if (!stateManager.subRegist) {
      stateManager.subRegist = true
      let isError = false
      for (let i = 0; i < stateManager.validateRules.length; i++) {
        const mr = stateManager.validateRules[i] as any
        if(mr){
          mr.validate()
        }
      }
      for (let i = 0; i < stateManager.validateRules.length; i++) {
        const mr = stateManager.validateRules[i] as any
        if (mr&&mr.hasError) {
          isError = true
          break
        }
      }

      if (isError) {
        stateManager.subRegist = false
      } else {
        console.log(userModel)
        //TODO: 调用注册接口
        setTimeout(() => {
          //注册成功应该实现自动登录，让后跳转到首页
          const dissmiss = message.loadMsg('注册成功，正常初始化系统，马上就好')
          setTimeout(() => {
            dissmiss()
            message.successMsg('初始化成功，正在进入系统')

            //#region 测试使用
            const menu: AuthMenuType = {
              menuId: 1,
              menuName: '首页',
              menuUrl: '/index'
            }
            const menus = new Array<AuthMenuType>()
            const auths = getStoreGetter<UserGetter>('user', 'getUserAllAuth')
            if (auths != ResultType.EmptyArray) {
              Object.assign(menus, ...auths)
            }
            menus.push(menu)
            setStoreState('user', 'menuList', menus)
            router.push({
              path: '/index'
            })
            //#endregion
          }, 2000)
        }, 3000)
      }
    }
  }

  return { userModel, setValidateRules, userRule, stateManager, validateSendStatus, checkCodeStatus, sendCode, submitValidateCode, doRegist }
}

export default useUserRegistModule
