/*! Verify
 */

const string = require('./util.js').string
const Tip = require('./Tip.js')
const Dialog = require('./Dialog.js')

const z = window.Zving = window.Zving || {}
const Verify = window.Verify = z.Verify = z.Verify || {}
const Lang = z.Lang = z.Lang || {}

Lang.Verify = {
  'CharsOrLetters': '{0}个汉字或{1}个字母',
  'Date': '日期',
  'DateTime': '日期及时间',
  'DateWrong': '日期格式错误，',
  'Email': '电子邮箱',
  'FixedTelNumber': '固定电话号码',
  'HasError': '还有未正确填写的项，请参照提示修改',
  'HiddenElemHasError': '还有未正确填写的项!',
  'IDNumber': '身份证号码',
  'InputValue': '输入的值',
  'Int': '整数',
  'Length': '长度',
  'LengthEX': '字数',
  'MobileNumber': '手机号码',
  'MustBe': '必须是',
  'MustBeRight': '必须是正确的',
  'MustChoose': '必须选择',
  'MustEqualOrGreaterThan': '必须大于或等于',
  'MustEqualOrLessThan': '必须小于或等于',
  'MustGreaterThan': '必须大于',
  'MustLessThan': '必须小于',
  'NoDay': '没有日!',
  'NoMonth': '没有月!',
  'NoYear': '没有年!',
  'NotAnOption': '不是可选项',
  'NotNull': '不能为空',
  'NotRight': '不是正确的',
  'Number': '数字',
  'RuleError': '校验规则错误，',
  'TabPageHasError': '页签内有未正确填写的项!',
  'TelNumber': '电话号码',
  'Time': '时间',
  'Zip': '邮政编码',
  'char': '个字符'
}

const getDom = function (el) {
  if (!el) {
    return el
  }
  if (typeof el === 'string') {
    return document.getElementById(el.replace(/^#/, ''))
  }
  if (!el.nodeName && el.length && el[0] && el[0].nodeName) { // 如果是一个jquery对象
    return el[0]
  }
  return el
}
const isVisible = function (elem) {
  elem = getDom(elem)
  if (
    !elem.parentNode ||
    (elem.tagName !== 'BODY' &&
      elem.parentNode.tagName !== 'BODY' &&
      !elem.offsetParent)
  ) {
    return false // 不在节点内，或为隐藏元素
  }
  var curStyle = elem.currentStyle
  if (!curStyle && window.getComputedStyle) {
    curStyle = window.getComputedStyle(elem, null)
    if (!curStyle) {
      return false
    }
  }
  if (curStyle.display === 'none') {
    return false
  } else if (
    elem.offsetWidth === 0 && elem.offsetHeight === 0 && elem.tagName !== 'TR'
  ) {
    return false
  }
  return true
}
const getValueById = z.getValueById = function (elem) {
  // console.warn('Node.getValue方法将在下次JS框架重构中删除，请改用jQuery的val方法代替。')
  var ele = getDom(elem)
  if (!ele) {
    window.console &&
      console.error(
        window.location.pathname +
        ' - getValueById : 表单元素"' +
        elem +
        '"不存在 '
      )
    return
  }
  if (!ele.type) {
    return ele.value
  }
  switch (ele.type.toLowerCase()) {
    case 'text':
    case 'textarea':
      return ele.value
    case 'submit':
    case 'hidden':
    case 'password':
    case 'file':
    case 'image':
    case 'select-one':
      return ele.value
    case 'checkbox':
    case 'radio':
      if (ele.checked) {
        return ele.value
      }
      return null
    default:
      return ''
  }
}
const getValuesByName = z.getValuesByName = function (name) {
  name = name.replace(/^#/, '')
  var eleList = document.getElementsByName(name)
  var arr = []
  var ele
  if (!eleList || !eleList.length) {
    ele = document.getElementById(name)
    if (ele && 'SELECT,INPUT,TEXTAREA,BUTTON'.indexOf(ele.tagName) !== -1) {
      return [getValueById(ele)] // 作一下兼容处理，如果没有特定name的元素，就取特定的id的元素
    } else {
      return arr
    }
  }
  for (var i = 0; i < eleList.length; i++) {
    ele = eleList[i]
    if (
      ele.tagName &&
      'SELECT,INPUT,TEXTAREA,BUTTON'.indexOf(ele.tagName) !== -1
    ) {
      var v = getValueById(ele)
      if (v !== null) {
        arr.push(v)
      }
    }
  }
  return arr
}

var isFeedbackLikeBS
var hasFeedbackLikeBS = function () {
  if (isFeedbackLikeBS !== undefined) {
    return isFeedbackLikeBS
  }
  if ($.event && $.event.special.bsTransitionEnd) {
    isFeedbackLikeBS = true
    return true
  }
  var $tempSpan = $('<span class="form-control-feedback"></span>').appendTo(document.body)
  if ($tempSpan.css('position') === 'absolute') {
    isFeedbackLikeBS = true
    $tempSpan.remove()
    return true
  }
  isFeedbackLikeBS = false
  $tempSpan.remove()
  return false
}
Verify.autoCloseOther = function (evt, ele) {
  if (!ele) {
    ele = evt.target || evt.srcElement
  }
}

// 校验并返回错误消息数组
Verify.getErrors = function (value, validStr) {
  var msg = []

  var features = validStr.split('&&')

  for (var i = 0; i < features.length; i++) {
    var arr = features[i].split('|')
    var name = ''
    var rule
    if (arr.length === 2) {
      name = arr[0]
      rule = arr[1]
    } else {
      rule = features[i]
    }
    if (!rule) {
      continue
    }
    var op = '='
    if (rule.indexOf('=') < 0) {
      if (rule.indexOf('>') > 0) {
        op = '>'
      } else if (rule.indexOf('<') > 0) {
        op = '<'
      }
    } else {
      if (rule.charAt(rule.indexOf('=') - 1) === '>') {
        op = '>='
      } else if (rule.charAt(rule.indexOf('=') - 1) === '<') {
        op = '<='
      }
    }
    var fName = null
    var fValue = null
    var pattern
    if (rule.indexOf(op) > 0) {
      fName = rule.substring(0, rule.indexOf(op))
      fValue = rule.substring(rule.indexOf(op) + op.length)
    } else {
      fName = rule
    }
    if (fName === 'Any') {
      // var anyFlag = true
    } else if (fName === 'Regex') {
      fValue = rule.substring(6)
      if (value === null || value === '' || !fValue) {
        continue
      }
      var reg = fValue
      if (!reg.startsWith('^')) {
        reg = '^' + reg
      }
      if (!reg.endsWith('$')) {
        reg += '$'
      }
      if (!new RegExp(reg).test(value)) {
        msg.push(name)
      }
    } else if (fName === 'Script') {
      if (!fValue) {
        continue
      }
      if (!new Function('value', 'return ' + fValue + ';')(value)) {
        msg.push(name)
      }
    } else if (fName === 'NotNull') {
      if (value === null || value === '') {
        msg.push(name + Lang.Verify.NotNull)
      }
    } else if (fName === 'Number') {
      if (value === null || value === '') {
        continue
      }
      if (!string.isNumber(value)) {
        msg.push(name + Lang.Verify.MustBe + Lang.Verify.Number)
      }
    } else if (fName === 'Time') {
      if (value === null || value === '') {
        continue
      }
      if (!string.isTime(value)) {
        msg.push(value + Lang.Verify.NotRight + Lang.Verify.Time)
      }
    } else if (fName === 'Int') {
      if (value === null || value === '') {
        continue
      }
      if (!string.isInt(value)) {
        msg.push(name + Lang.Verify.MustBe + Lang.Verify.Int)
      }
    } else if (fName === 'Date') {
      if (value === null || value === '') {
        continue
      }
      if (!string.isDate(value)) {
        msg.push(name + Lang.Verify.MustBeRight + Lang.Verify.Date)
      }
    } else if (fName === 'Time') {
      if (value === null || value === '') {
        continue
      }
      if (!string.isTime(value)) {
        msg.push(name + Lang.Verify.MustBeRight + Lang.Verify.Time)
      }
    } else if (fName === 'DateTime') {
      if (value === null || value === '') {
        continue
      }
      if (!string.isDateTime(value)) {
        msg.push(name + Lang.Verify.MustBeRight + Lang.Verify.DateTime)
      }
    } else if (fName === 'Email') {
      if (value === null || value === '') {
        continue
      }
      pattern = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      if (value && value.match(pattern) === null) {
        msg.push(name + Lang.Verify.NotRight + Lang.Verify.Email)
      }
    } else if (fName === 'ZipCode') {
      if (value === null || value === '') {
        continue
      }
      pattern = /^[0-9]\d{5}(?!\d)$/
      if (value && value.match(pattern) === null) {
        msg.push(name + Lang.Verify.NotRight + Lang.Verify.Zip)
      }
    } else if (fName === 'CnTel') {
      if (value === null || value === '') {
        continue
      }
      pattern = /^\d{3}-\d{8}|\d{4}-\d{7}$/
      if (value && value.match(pattern) === null) {
        msg.push(name + Lang.Verify.NotRight + Lang.Verify.FixedTelNumber)
      }
    } else if (fName === 'CnPhone') {
      if (value === null || value === '') {
        continue
      }
      var pattern1 = /^\d{3,4}-\d{7,8}$/
      var pattern2 = /^\d{11}$/
      if (value && value.match(pattern1) === null && value.match(pattern2) === null) {
        msg.push(name + Lang.Verify.NotRight + Lang.Verify.TelNumber)
      }
    } else if (fName === 'CnMobile') {
      if (value === null || value === '') {
        continue
      }
      pattern = /^\d{11}$/
      if (value && value.match(pattern) === null) {
        msg.push(name + Lang.Verify.NotRight + Lang.Verify.MobileNumber)
      }
    } else if (fName === 'IDCardNo') {
      if (value === null || value === '') {
        continue
      }
      if (!Verify.isIDCardNo(value)) {
        msg.push(name + Lang.Verify.NotRight + Lang.Verify.IDNumber)
      }
    } else if (fName === 'Length') {
      if (value === null || value === '') {
        continue
      }
      if (isNaN(fValue)) {
        msg.push(Lang.Verify.RuleError + Lang.Verify.BackOfLength + Lang.Verify.Number)
      } else {
        try {
          var len = parseInt(fValue, 10)
          if (op === '=' && value.length !== len) {
            msg.push(name + Lang.Verify.Length + Lang.Verify.MustBe + len + Lang.Verify.char)
          } else if (op === '>' && value.length <= len) {
            msg.push(name + Lang.Verify.Length + Lang.Verify.MustGreaterThan + len + Lang.Verify.char)
          } else if (op === '>=' && value.length < len) {
            msg.push(name + Lang.Verify.Length + Lang.Verify.MustEqualOrGreaterThan + len + Lang.Verify.char)
          } else if (op === '<' && value.length >= len) {
            msg.push(name + Lang.Verify.Length + Lang.Verify.MustLessThan + len + Lang.Verify.char)
          } else if (op === '<=' && value.length > len) {
            msg.push(name + Lang.Verify.Length + Lang.Verify.MustEqualOrLessThan + len + Lang.Verify.char)
          }
        } catch (ex) {
          msg.push(Lang.Verify.RuleError + Lang.Verify.BackOfLength + Lang.Verify.Int + ex.message)
        }
      }
    } else if (fName === 'LengthEX') {
      if (value === null || value === '') {
        continue
      }
      if (isNaN(fValue)) {
        msg.push(Lang.Verify.RuleError + Lang.Verify.BackOfLengthEX + Lang.Verify.Number)
      } else {
        try {
          len = parseInt(fValue, 10)
          var charLen = Math.floor(len / 3)
          var tip = string.tmpl(Lang.Verify.CharsOrLetters, {
            0: charLen,
            1: len
          })
          var textLen = string.getLengthEx(value)
          if (op === '=' && textLen !== len) {
            msg.push(name + Lang.Verify.LengthEX + Lang.Verify.MustBe + tip)
          } else if (op === '>' && textLen <= len) {
            msg.push(name + Lang.Verify.LengthEX + Lang.Verify.MustGreaterThan + tip)
          } else if (op === '>=' && textLen < len) {
            msg.push(name + Lang.Verify.LengthEX + Lang.Verify.MustEqualOrGreaterThan + tip)
          } else if (op === '<' && textLen >= len) {
            msg.push(name + Lang.Verify.LengthEX + Lang.Verify.MustLessThan + tip)
          } else if (op === '<=' && textLen > len) {
            msg.push(name + Lang.Verify.LengthEX + Lang.Verify.MustEqualOrLessThan + tip)
          }
        } catch (ex) {
          msg.push(Lang.Verify.RuleError + Lang.Verify.BackOfLengthEX + Lang.Verify.Int + ex.message)
        }
      }
    }
  }
  return msg
}

Verify.checkOne = function (evt, ele) { // evt,ele二者只填一个
  if (!ele) {
    ele = evt.target || evt.srcElement
  }
  if (ele.disabled || !isVisible(ele)) {
    // 如果有bootstrap - 2015 by wyuch
    if (hasFeedbackLikeBS()) {
      var group = $(ele).closest('.form-group')
      if (group.length > 0) {
        group.removeClass('has-error')
        group.find('.verify-message').hide()
      }
    }
    Verify.closeTip(null, ele)
    return // 隐藏及不可用的元素不校验
  }
  if (ele._verifyFor) {
    ele = ele._verifyFor
  }

  var $ele = $(ele)
  var validStr = ele.getAttribute('verify')
  if (!validStr) { // verify属性可能有变动
    Verify.closeTip(null, ele)
    return
  }
  var condition = ele.getAttribute('condition')
  if (condition && !new Function('elem', 'return ' + condition + ';')(ele)) {
    Verify.closeTip(null, ele)
    return
  }
  var value = getValueById(ele)
  if (ele.type === 'radio' || ele.type === 'checkbox') {
    // 2012年6月14日 加上对ordio及checkbox的
    if (ele.name) {
      value = getValuesByName(ele.name)
    }
  }
  if (value) { /*  */
    value = ('' + value).trim().replace(/\u00a0/g, '\u0020')
  }

  var msg = Verify.getErrors(value, validStr)
  if ($ele.attr('hasVerifyError')) { // 是否有自定义错误消息
    msg.push($ele.attr('verifyMessage'))
  }

  if (msg.length > 0) {
    var txt = msg.join('<br>')
    Verify.closeTip(null, ele)
    var tip
    ele._VerifyMsg = txt
    ele._VerifyHasErr = true
    // 如果有bootstrap - 2015 by wyuch
    if (hasFeedbackLikeBS()) {
      txt = '<li>' + msg.join('</li><li>') + '</li>'
      group = $ele.closest('.form-group')
      if (group.length > 0) {
        group.addClass('has-error')
        group.find('.verify-message').html(txt)
        group.find('.verify-message').show()
        group.find('.verify-success').hide()
        return
      }
    }

    if (isVisible(ele)) {
      if (!$ele.data('Tip')) {
        var afterEle = $(ele).data('showTipAfter')
        if (afterEle) {
          tip = new Tip(getDom(afterEle), {
            msg: txt,
            theme: 'notice'
          })
        } else {
          tip = new Tip(ele, {
            msg: txt,
            theme: 'notice'
          })
        }
        tip.AutoClose = true
        $ele.data('Tip', tip)
      }
      $ele.data('Tip').setMessage(txt)
      $ele.data('Tip').show()
    } else {
      var $page = $(ele).closest('div.ui-page')
      var $tabs = $('a.z-tab')
      var pageurl = $page.attr('data-url')
      if ($page.length && $tabs.length && pageurl) { // 如果ele在隐藏的页签内
        $tabs.each(function () {
          if (this.getAttribute('data-href')) {
            var a = this
            var $a = $(a)
            // console.log(pageurl,a.getAttribute('data-href'));
            if (pageurl.indexOf(a.getAttribute('data-href').replace(/^(\.\.\/)+/, '')) !== -1) {
              if (!$a.data('Tip')) {
                var tip = new Tip(a, {
                  msg: Lang.Verify.TabPageHasError,
                  theme: 'notice'
                })
                tip.AutoClose = true
                tip.Clock = 9
                $a.data('Tip', tip)
              }
              // console.log('show',$a.data('Tip'));
              setTimeout(function () {
                $a.data('Tip').setMessage(txt)
                $a.data('Tip').show()
              }, 200)
            }
          }
        })
      }
      if (!$tabs.length) {
        Dialog.tips(Lang.Verify.HiddenElemHasError) // 如果不在页签页面
      }
    }
    return true
  } else {
    ele._VerifyHasErr = ele._VerifyMsg = null
    if ((ele.type === 'radio' || ele.type === 'checkbox') && ele.name) {
      [].slice.call(document.getElementsByName(ele.name)).forEach(function (el) {
        Verify.closeTip(null, el)
      })
    } else {
      Verify.closeTip(null, ele)
    }
    //  如果有bootstrap - 2015 by wyuch
    if (hasFeedbackLikeBS()) {
      group = $ele.closest('.form-group')
      if (group.length > 0) {
        group.removeClass('has-error')
        group.find('.verify-message').hide()
        group.find('.verify-mandatory').hide()
        if (value) { // 空值时不显示成功状态
          group.addClass('has-success')
          group.find('.verify-success').show()
        }
      }
    }
  }
}

Verify.closeTip = function (evt, ele) {
  if (!ele) {
    ele = evt.target || evt.srcElement
  }
  if (ele.type === 'blur') {
    ele = ele.target || ele.srcElement
  }
  if (ele._verifyFor) {
    ele = ele._verifyFor
  }
  if ($(ele).data('Tip')) {
    $(ele).data('Tip').hide()
    ele._VerifyMsg = null
    ele._VerifyHasErr = null
  }
}
Verify.closeAllTip = function (ele) {
  ele = getDom(ele || document.body)
  var $inputs
  ele = getDom(ele || document.body)
  $inputs = $('input,textarea,select', ele)
  $inputs.each(function () {
    Verify.closeTip(null, this)
  })
}
Verify.hasError = function (noCheckSelector, ele, noDialog) {
  var $inputs
  ele = getDom(ele || document.body)
  if ('INPUT,TEXTAREA,SELECT'.indexOf(ele.tagName) !== -1) {
    $inputs = $(ele)
  } else {
    $inputs = $('input,textarea,select', ele)
  }
  if (noCheckSelector) {
    if (typeof noCheckSelector !== 'string') {
      window.console && console.error('传入Verify.hasError的第一个参数应该为一个元素选择器字符串')
      return
    }
    $inputs = $inputs.not(noCheckSelector)
    $(noCheckSelector).each(function () {
      Verify.closeTip(null, this)
    })
  }
  var firstEle = false
  for (var i = 0; i < $inputs.length; i++) {
    var el = $inputs[i]
    Verify.checkOne(null, el)
    if (!firstEle && el.getAttribute('verify') && el._VerifyHasErr) {
      firstEle = el
    }
  }
  // console.log(firstEle);
  if (firstEle) {
    if (noDialog === true) {
      try {
        firstEle.focus()
      } catch (e) {}
    } else {
      Dialog.alert(Lang.Verify.HasError, function () {
        try {
          firstEle.focus()
        } catch (e) {}
      })
    }
    return true
  }
  return false
}

Verify.check = function (ele) { // 不自动弹出对话框
  return Verify.hasError(null, ele, true)
}

Verify._cache = {}

Verify.initCtrl = function (ele) {
  // console.log(elem)

  ele = getDom(typeof ele === 'string' ? ele : ele.id || ele)

  if (!ele) {
    return
  }
  var validStr = ele.getAttribute('verify')
  var ztype
  if (validStr) {
    ztype = ele.getAttribute('ztype')
    if (ztype) {
      ztype = ztype.toLowerCase()
    }
    var eventTarget
    if (ztype && ztype === 'select') {
      eventTarget = $(ele).next().get(0)
      eventTarget._verifyFor = ele
    } else {
      eventTarget = ele
    }
    var $eventTarget = $(eventTarget)
    $eventTarget.on('focus', Verify.checkOne)
    $eventTarget.on('focus', Verify.autoCloseOther)
    $eventTarget.on('keyup', Verify.checkOne)
    $eventTarget.on('change', Verify.checkOne)
    $eventTarget.on('blur', Verify.closeTip)
    if (!z.isIE) {
      $(ele).on('input', Verify.checkOne, false)
    }
    if (ztype === 'select') {
      ele = $(ele).closest('div')[0] // 有时候要校验的select内容已经被替换过，移出了dom树
    }
    if (/^date|time|Number$/i.test(ztype)) {
      var nextEl = getDom(ele.id || ele).nextSibling
      if (nextEl && nextEl.tagName === 'IMG') {
        ele = nextEl
      }
    }
    if (ele.type === 'radio' || ele.type === 'checkbox') {
      if (ele.name) {
        var sameNameEls = document.getElementsByName(ele.name)
        ele = sameNameEls[sameNameEls.length - 1]
        $.each(sameNameEls, function (i, el) {
          $(el).data('showTipAfter', ele)
        })
      }
      return
    }
    if (ele.getAttribute('showtipafter')) {
      $(ele).data('showTipAfter', $(ele.getAttribute('showtipafter'))[0])
    }

    /*
    为适应自定义表单,调整节点获取位置为判断重复前,
    当input外面的div拥有form-control类时目标容器节点向外移一层
    判断重复方式由判断input后面紧跟的元素的ztype属性,
    改为目标容器中查找span[ztype=Verify]
    */

    var $ele = $(ele)

    if ($ele.parent().hasClass('form-control')) $ele = $ele.parent()

    if ($ele.parent().hasClass('input-group')) {
      $ele = $ele.parent()

      if ($ele.find('.input-group-addon').length > 1) {
        $ele = $ele.find('.input-group-addon')
      }
    }

    if ($ele.parent().find('span[ztype=Verify]').length === 0) {
      var display = ''
      if (!isVisible(ele) && isVisible(ele.parentNode)) { // ele是隐藏的，但父元素是显示的，才隐藏星号
        display = 'display:none'
      }
      if (validStr.indexOf('NotNull') < 0) {
        display = 'display:none'
      }
      if (!hasFeedbackLikeBS()) { // 没有Bootstrap时
        var html = "<span style='color:red;padding-left:2px;" + display + "' ztype='Verify'>*</span>"
        ele.insertAdjacentHTML('afterEnd', html)
      } else {
        html = ''
        html += "<span class='verify-mandatory form-control-feedback' style='color:red;" + display + "' ztype='Verify'>*</span>"
        html += "<span class='verify-success form-control-feedback' style='display:none' aria-hidden='true'><span class='fa fa-check-circle'></span></span>"
        // html += "<span class='verify-mandatory form-control-feedback' style='color:red;" + display + "' ztype='Verify'>*</span>"
        html += "<span class='verify-message help-block text-left' style='display:none'></span>"

        $ele.after(html)
        var g = $(ele).closest('.form-group')
        g.addClass('has-feedback')
        g.parent().find('.form-group').css('vertical-align', 'top') // inline的控件需要设置这个，不会显示消息后会对不齐
      }
    }
  }
}

Verify.getBirthDateFromIDCardNo = function (id) {
  if (id === null) {
    return null
  }
  if (id.length === 15) {
    return '19' + id.substring(6, 8) + '-' + id.substring(8, 10) + '-' + id.substring(10, 12)
  }
  if (id.length === 18) {
    return id.substring(6, 10) + '-' + id.substring(10, 12) + '-' + id.substring(12, 14)
  }
  return null
}

Verify.getGenderFromIDCardNo = function (id) {
  if (id === null) {
    return null
  }
  if (id.length === 15) {
    return '13579'.indexOf(id.substring(14, 15)) !== -1 ? 'M' : 'F'
  }
  if (id.length === 18) {
    return '13579'.indexOf(id.substring(16, 17)) !== -1 ? 'M' : 'F'
  }
  return null
}

Verify.isIDCardNo = function (id) {
  if (!id) {
    return false
  }
  id = id.toLowerCase()
  if (id.length !== 15 && id.length !== 18) {
    return false
  }
  var y, m, d
  if (id.length === 15) {
    y = parseInt('19' + id.substring(6, 8), 10)
    m = parseInt(id.substring(8, 10), 10)
    d = parseInt(id.substring(10, 12), 10)
  } else if (id.length === 18) {
    if (id.indexOf('x') >= 0 && id.indexOf('x') !== 17) {
      return false
    }
    var verifyBit
    var sum = id.charAt(0) * 7 + id.charAt(1) * 9 + id.charAt(2) * 10 + id.charAt(3) * 5 + id.charAt(4) * 8 + id.charAt(5) * 4 + id.charAt(6) * 2 + id.charAt(7) * 1 + id.charAt(8) * 6 + id.charAt(9) * 3 + id.charAt(10) * 7 + id.charAt(11) * 9 + id.charAt(12) * 10 + id.charAt(13) * 5 + id.charAt(14) * 8 + id.charAt(15) * 4 + id.charAt(16) * 2

    sum = sum % 11
    switch (sum) {
      case 0:
        verifyBit = '1'
        break
      case 1:
        verifyBit = '0'
        break
      case 2:
        verifyBit = 'x'
        break
      case 3:
        verifyBit = '9'
        break
      case 4:
        verifyBit = '8'
        break
      case 5:
        verifyBit = '7'
        break
      case 6:
        verifyBit = '6'
        break
      case 7:
        verifyBit = '5'
        break
      case 8:
        verifyBit = '4'
        break
      case 9:
        verifyBit = '3'
        break
      case 10:
        verifyBit = '2'
        break
    }
    if (id.charAt(17) !== verifyBit) {
      return false
    }
    y = parseInt(id.substring(6, 10), 10)
    m = parseInt(id.substring(10, 12), 10)
    d = parseInt(id.substring(12, 14), 10)
  }
  var currentY = new Date().getFullYear()
  if (!y || y > currentY || y < 1870) {
    return false
  }
  if (!m || m < 1 || m > 12) {
    return false
  }
  if (!d || d < 1 || d > 31) {
    return false
  }
  return true
}

const initComponentFromElements = function (ele) {
  ele = getDom(ele)
  if (!ele) {
    return
  }
  var $inputs
  if (ele.tagName === 'INPUT') {
    $inputs = $(ele)
  } else if (ele.tagName === 'TEXTAREA') {
    $inputs = $(ele)
  } else if (ele.tagName === 'SELECT') {
    $inputs = $(ele)
  } else if (ele.children.length) {
    $inputs = $('input,textarea,select', ele)
  } else {
    return
  }
  $inputs.each(function () {
    var verify = this.getAttribute('verify')
    if (verify) {
      Verify.initCtrl(this)
    }
  })
}

/**
 * 暴露init方法用于动态添加input时初始化(仅用于编辑器)
 */
Verify.init = function (dom) {
  initComponentFromElements(dom || document.body)
}

$(function () {
  Verify.init()
})

module.exports = Verify
// export default Verify
