const Verify = require('./Verify.js')
const addressData = require('./addressData.js')
const Tip = require('./Tip.js')

require('./picker.js')
require('./picker.date.js')
require('./picker.time.js')
require('./zform.css')

var zForm = (window.$ZF = window.zForm = {})
var components = (zForm.components = {})
var params = (zForm.params = {})
zForm.addressData = addressData
var formInfo = (zForm.formInfo = window.formInfo = {})

/**
 * 文本输入框
 * @param param
 * @returns {jQuery.fn.init|jQuery|HTMLElement}
 * @constructor
 */
params['InputWidget'] = {
  name: '文本输入框',
  tag: 'InputWidget',
  params: [
    {
      name: 'type',
      label: '控件类型',
      type: 'type',
      _default: '',
      editable: true
    },
    {
      name: 'input_name',
      label: '字段代码',
      type: 'name',
      _default: '',
      editable: false
    },
    {
      name: 'col',
      label: '控件宽度',
      type: 'col',
      min: '2',
      max: '24',
      _default: '12',
      editable: true
    },
    {
      name: 'input_value',
      label: '默认值',
      type: 'text',
      _default: '',
      editable: true
    },
    {
      name: 'placeholder',
      label: '提示信息',
      type: 'text',
      _default: '',
      editable: true
    },
    {
      name: 'verify',
      label: '验证条件',
      type: 'verify',
      _default: '',
      editable: true
    },
    {
      name: 'prefix',
      label: '前缀文字',
      type: 'text',
      _default: '',
      editable: true
    },
    {
      name: 'suffix',
      label: '后缀文字',
      type: 'text',
      _default: '',
      editable: true
    }
  ]
}
components['InputWidget'] = function (param, field) {
  var temp =
    '<div class="col-{{col}}">' +
    '<div class="pw-zform-input-group">' +
    (param.prefix ? '<span class="pw-zform-prefix pw-zform-fix">{{prefix}}</span>' : '') +
    '<div class="pw-zform-input">' +
    '<input class="pw-zform-input" type="text" name="{{input_name}}" value="{{input_value}}" placeholder="{{placeholder}}" verify="{{verify}}"/>' +
    '</div>' +
    (param.suffix ? '<span class="pw-zform-suffix pw-zform-fix">{{suffix}}</span>' : '') +
    '</div>' +
    '</div>'

  return htmlTemplateTool(temp, param)
}

/**
 * 多行输入框
 * @param param
 * @returns {jQuery.fn.init|jQuery|HTMLElement}
 * @constructor
 */
params['TextareaWidget'] = {
  name: '多行输入框',
  tag: 'TextareaWidget',
  params: [
    {
      name: 'type',
      label: '控件类型',
      type: 'type',
      _default: '',
      editable: false
    },
    {
      name: 'input_name',
      label: '字段代码',
      type: 'name',
      _default: '',
      editable: false
    },
    {
      name: 'col',
      label: '控件宽度',
      type: 'col',
      min: '2',
      max: '24',
      _default: '12',
      editable: true
    },
    {
      name: 'input_value',
      label: '默认值',
      type: 'text',
      _default: '',
      editable: true
    },
    {
      name: 'placeholder',
      label: '提示信息',
      type: 'text',
      _default: '',
      editable: true
    },
    {
      name: 'verify',
      label: '验证条件',
      type: 'verify',
      _default: '',
      editable: true
    }
  ]
}
components['TextareaWidget'] = function (param, field) {
  var temp =
    '<div class="col-{{col}}">' +
    '<div class="pw-zform-input-group">' +
    (param.prefix ? '<span class="pw-zform-prefix pw-zform-fix">{{prefix}}</span>' : '') +
    '<div class="pw-zform-input">' +
    '<textarea class="pw-zform-input" name="{{input_name}}" value="{{input_value}}" placeholder="{{placeholder}}" verify="{{verify}}"></textarea>' +
    '</div>' +
    (param.suffix ? '<span class="pw-zform-suffix pw-zform-fix">{{suffix}}</span>' : '') +
    '</div>' +
    '</div>'

  return htmlTemplateTool(temp, param)
}

/**
 * 下拉选择框
 * @param param
 * @returns {jQuery.fn.init|jQuery|HTMLElement}
 * @constructor
 */
params['SelectWidget'] = {
  name: '下拉选择框',
  tag: 'SelectWidget',
  params: [
    {
      name: 'type',
      label: '控件类型',
      type: 'type',
      _default: '',
      editable: false
    },
    {
      name: 'input_name',
      label: '字段代码',
      type: 'name',
      _default: '',
      editable: false
    },
    {
      name: 'col',
      label: '控件宽度',
      type: 'col',
      min: '2',
      max: '24',
      _default: '12',
      editable: true
    },
    {
      name: 'multiple',
      label: '是否多选',
      type: 'boolean',
      _default: '',
      editable: true
    },
    {
      name: 'options',
      label: '选项',
      type: 'option',
      _default: '',
      editable: true
    },
    {
      name: 'prefix',
      label: '前缀文字',
      type: 'text',
      _default: '',
      editable: true
    },
    {
      name: 'suffix',
      label: '后缀文字',
      type: 'text',
      _default: '',
      editable: true
    }
  ]
}
components['SelectWidget'] = function (param, field) {
  var options = ''
  $.each(param.options.split('\n'), function () {
    if (this) options += '<option value="' + this + '">' + this + '</option>'
  })

  var temp =
    '<div class="col-{{col}}">' +
    '<div class="pw-zform-input-group">' +
    (param.prefix ? '<span class="pw-zform-prefix pw-zform-fix">{{prefix}}</span>' : '') +
    '<select class="pw-zform-input" name="{{input_name}}"' +
    (param.multiple ? ' multiple="multiple"' : '') +
    '>' +
    options +
    '</select>' +
    (param.suffix ? '<span class="pw-zform-suffix pw-zform-fix">{{suffix}}</span>' : '') +
    '</div>' +
    '</div>'

  return htmlTemplateTool(temp, param)
}

/**
 * 多选框组
 * @param param
 * @returns {jQuery.fn.init|jQuery|HTMLElement}
 * @constructor
 */
params['CheckboxGroupWidget'] = {
  name: '多选框组',
  tag: 'CheckboxGroupWidget',
  params: [
    {
      name: 'type',
      label: '控件类型',
      type: 'type',
      _default: '',
      editable: false
    },
    {
      name: 'input_name',
      label: '字段代码',
      type: 'name',
      _default: '',
      editable: false
    },
    {
      name: 'col',
      label: '控件宽度',
      type: 'col',
      min: '2',
      max: '24',
      _default: '12',
      editable: true
    },
    {
      name: 'inline',
      label: '是否单行',
      type: 'boolean',
      _default: '',
      editable: true
    },
    {
      name: 'options',
      label: '选项',
      type: 'option',
      _default: '',
      editable: true
    }
  ]
}
components['CheckboxGroupWidget'] = function (param, field) {
  var options = ''
  var data = {
    name: param.input_name,
    labelClass: param.inline === 'inline' ? 'pw-zform-checkbox-inline' : 'pw-zform-checkbox'
  }
  var optTemp =
    '<label class="{{labelClass}}">' +
    '<input type="checkbox" name="{{name}}" value="{{item}}"/>' +
    (navigator.userAgent.indexOf('MSIE 8') > 0 && !window.innerWidth ? '{{item}}' : '<span>{{item}}</span>') +
    '</label>'

  $.each(param.options.split('\n'), function () {
    if (this.toString()) {
      data.item = this.toString()
      options += htmlTemplateTool(optTemp, data)
    }
  })

  var temp = '<div class="col-{{col}}">' + options + '</div>'
  var el = $(htmlTemplateTool(temp, param))

  if (field.required) {
    var tip = new Tip(el, {
      msg: '必须选择一项',
      theme: 'notice'
    })
    zForm.on('submit', function () {
      tip.hide()
      var tag = false
      el.find('input[type=checkbox]').each(function () {
        if (this.checked) {
          tag = true
          return false
        }
      })

      if (tag) {
        return true
      } else {
        tip.show()
        return false
      }
    })

    el.on('mouseover', function () {
      tip.hide()
    })
  }

  return el
}

/**
 * 单选框组
 * @param param
 * @returns {jQuery.fn.init|jQuery|HTMLElement}
 * @constructor
 */
params['RadioGroupWidget'] = {
  name: '单选框组',
  tag: 'RadioGroupWidget',
  params: [
    {
      name: 'type',
      label: '控件类型',
      type: 'type',
      _default: '',
      editable: false
    },
    {
      name: 'input_name',
      label: '字段代码',
      type: 'name',
      _default: '',
      editable: false
    },
    {
      name: 'col',
      label: '控件宽度',
      type: 'col',
      min: '2',
      max: '24',
      _default: '12',
      editable: true
    },
    {
      name: 'inline',
      label: '是否单行',
      type: 'boolean',
      _default: '',
      editable: true
    },
    {
      name: 'options',
      label: '选项',
      type: 'option',
      _default: '',
      editable: true
    }
  ]
}
components['RadioGroupWidget'] = function (param, field) {
  var options = ''
  var data = {
    name: param.input_name,
    labelClass: param.inline === 'inline' ? 'pw-zform-radio-inline' : 'pw-zform-radio'
  }
  var optTemp =
    '<label class="{{labelClass}}">' +
    '<input type="radio" name="{{name}}" value="{{item}}"/>' +
    (navigator.userAgent.indexOf('MSIE 8') > 0 && !window.innerWidth ? '{{item}}' : '<span>{{item}}</span>') +
    '</label>'

  $.each(param.options.split('\n'), function () {
    if (this.toString()) {
      data.item = this.toString()
      options += htmlTemplateTool(optTemp, data)
    }
  })

  var temp = '<div class="col-{{col}}">' + options + '</div>'
  var el = $(htmlTemplateTool(temp, param))

  if (field.required) {
    var tip = new Tip(el, {
      msg: '必须选择一项',
      theme: 'notice'
    })
    zForm.on('submit', function () {
      tip.hide()
      var tag = false
      el.find('input[type=radio]').each(function () {
        if (this.checked) {
          tag = true
          return false
        }
      })

      if (tag) {
        return true
      } else {
        tip.show()
        return false
      }
    })

    el.on('mouseover', function () {
      tip.hide()
    })
  }

  return el
}

/**
 * 拖动条
 * @param param
 * @returns {jQuery.fn.init|jQuery|HTMLElement}
 * @constructor
 */
params['SliderWidget'] = {
  name: '滑块',
  tag: 'SliderWidget',
  params: [
    {
      name: 'type',
      label: '控件类型',
      type: 'type',
      _default: '',
      editable: false
    },
    {
      name: 'input_name',
      label: '字段代码',
      type: 'name',
      _default: '',
      editable: false
    },
    {
      name: 'col',
      label: '控件宽度',
      type: 'col',
      min: '2',
      max: '24',
      _default: '12',
      editable: true
    },
    {
      name: 'min',
      label: '最小值',
      type: 'number',
      _default: 0,
      editable: true
    },
    {
      name: 'max',
      label: '最大值',
      type: 'number',
      _default: 100,
      editable: true
    },
    {
      name: 'input_value',
      label: '默认值',
      type: 'number',
      _default: 0,
      editable: true
    }
  ]
}
components['SliderWidget'] = function (param, field) {
  var action = false
  var body = $('body')
  var lastX, maxWidth
  var min = parseInt(param.min || 0)
  var max = parseInt(param.max || 100)
  var unit, value

  value = parseInt(param.input_value) || min

  var temp =
    '<div class="col-{{col}}">' +
    (param.prefix ? '<span class="pw-zform-prefix">{{prefix}}</span>' : '') +
    '<div class="pw-zform-slider">' +
    '<input min="0" max="100" name="{{input_name}}" type="number" class="pw-zform-solid-input">' +
    '<div class="pw-zform-slider-bar">' +
    '<div class="pw-zform-slider-rate">' +
    '<span class="pw-zform-slider-dot"></span>' +
    '<span class="pw-zform-slider-tip">0</span>' +
    '<span class="pw-zform-slider-triangle"></span>' +
    '</div>' +
    '</div>' +
    '</div>' +
    (param.suffix ? '<span class="pw-zform-prefix">{{suffix}}</span>' : '') +
    '</div>'

  var boxEl = $(htmlTemplateTool(temp, param))
  var sliderEl = boxEl.find('.pw-zform-slider')
  var inputEl = boxEl.find('input')
  var sliderBarEl = boxEl.find('.pw-zform-slider-bar') // 背部条
  var sliderRateEl = boxEl.find('.pw-zform-slider-rate') // 当前值条
  var sliderDotEl = boxEl.find('.pw-zform-slider-dot') // 当前值点
  var sliderTipEl = boxEl.find('.pw-zform-slider-tip') // 当前值提示

  // 表单创建完成后初始化值
  zForm.on('created', function () {
    valChange(value)
  })

  // 点被按下,改变样式
  sliderDotEl.on('mousedown', function (evt) {
    evt.stopPropagation()
    sliderDotEl.addClass('action')
    action = true
    maxWidth = sliderBarEl.width()
  })

  // 点弹起,改变样式,垂直一部分值
  body.on('mouseup', function () {
    sliderDotEl.removeClass('action')
    action = false
    lastX = undefined
  })

  // 鼠标进入,现实提示
  sliderEl.on('mouseover', function () {
    sliderEl.addClass('hover')
    valChange(value)
  })

  // 鼠标移出,隐藏提示
  sliderEl.on('mouseout', function () {
    sliderEl.removeClass('hover')
  })

  // 鼠标在bar内按下,直接赋值
  sliderBarEl.on('mousedown', function (evt) {
    unit = sliderBarEl.width() / (max - min)
    var width = evt.offsetX
    var remainder = width % unit
    width -= remainder
    if (remainder > unit / 2) width += unit
    sliderRateEl.width(width)
    valChange(parseInt(width / unit))
  })

  // 鼠标拖动
  body.on('mousemove', function (evt) {
    unit = sliderBarEl.width() / (max - min)
    if (action && lastX) {
      var moveX = evt.pageX - lastX
      var width = sliderRateEl.width() + moveX
      if (width >= 0 && width <= maxWidth) lastX = evt.pageX
      if (width > maxWidth) width = maxWidth
      if (width < 0) width = 0
      var remainder = width % unit
      width -= remainder
      if (remainder > unit / 2) width += unit
      sliderRateEl.width(width)
      valChange(parseInt(width / unit))
    } else {
      lastX = evt.pageX
    }
  })

  // 当值发生变化,改变input和提示的值,计算提示的偏移
  function valChange (val) {
    value = val
    sliderTipEl.text(val)
    inputEl.val(val)
    sliderTipEl.css('right', '-' + sliderTipEl[0].offsetWidth / 2 + 'px')
  }

  zForm.on('reset', function () {
    sliderRateEl.width(0)
    valChange(parseInt(param.input_value) || min)
  })

  return boxEl
}

/**
 * 评级
 * @param param
 * @returns {jQuery.fn.init|jQuery|HTMLElement}
 * @constructor
 */
params['RateWidget'] = {
  name: '评级',
  tag: 'RateWidget',
  params: [
    {
      name: 'type',
      label: '控件类型',
      type: 'type',
      _default: '',
      editable: false
    },
    {
      name: 'input_name',
      label: '字段代码',
      type: 'name',
      _default: '',
      editable: false
    },
    {
      name: 'col',
      label: '控件宽度',
      type: 'col',
      min: '2',
      max: '24',
      _default: '12',
      editable: true
    },
    {
      name: 'max_value',
      label: '最大数量',
      type: 'number',
      min: '1',
      _default: '5',
      editable: true
    },
    {
      name: 'item',
      label: '选中符号',
      type: 'text',
      _default: '★',
      editable: true
    }
  ]
}
components['RateWidget'] = function (param, field) {
  var max = parseInt(param.max_value) || 5
  var item = param.item ? param.item : '★'
  var options = ''
  var optData = {
    name: param.input_name
  }

  for (var i = 1; i <= max; i++) {
    optData.zIndex = 1000 - i
    optData.value = i
    optData.content = Array(i + 1).join(item)
    options += htmlTemplateTool(
      '<label style="z-index: {{zIndex}}" class="pw-zform-rate-item">' +
        '<input type="radio" name="{{name}}" value="{{value}}"/>' +
        '<span>{{content}}</span>' +
        '</label>',
      optData
    )
  }

  var temp =
    '<div class="col-{{col}}">' +
    '<div class="pw-zform-rate">' +
    '<label class="pw-zform-rate-back">' +
    '<input type="radio" name="{{input_name}}" value="0" />' +
    '<span>' +
    Array(max + 1).join(item) +
    '' +
    '<span class="pw-zform-rate-clear">x</span>' +
    '</span>' +
    '</label>' +
    options +
    '</div>' +
    '</div>'

  var box = $(htmlTemplateTool(temp, param))
  var rateBox = box.find('.pw-zform-rate')
  // 背景层
  var input0 = box.find('input')
  // 清除按钮
  var clearEl = box.find('.pw-zform-rate-clear')
  var items = box.find('.pw-zform-rate-item')
  var inputs = box.find('input[type=radio]')
  var value

  input0[0].checked = true

  items.on('mouseover', function () {
    items.removeClass('hover')
    $(this).addClass('hover')
  })

  items.on('mouseout', function () {
    $(this).removeClass('hover')
    checkValue()
  })

  inputs.on('change', function () {
    if (this.checked) value = parseInt(this.value)
  })

  function checkValue () {
    items.removeClass('hover')
    if (value) $(items[value - 1]).addClass('hover')
  }

  clearEl.on('mouseover', function () {
    clearEl.addClass('hover')
  })

  clearEl.on('mouseout', function () {
    clearEl.removeClass('hover')
  })

  clearEl.on('click', function () {
    value = 0
    input0[0].checked = true
    checkValue()
  })

  zForm.on('reset', function () {
    value = 0
    input0[0].checked = true
    checkValue()
  })

  box.append(rateBox)
  return box
}

/**
 * 日期选择器(使用pickadate.js)
 * @param param
 * @returns {jQuery.fn.init|jQuery|HTMLElement}
 * @constructor
 */
params['DatePickerWidget'] = {
  name: '日期',
  tag: 'DatePickerWidget',
  params: [
    {
      name: 'type',
      label: '控件类型',
      type: 'type',
      _default: '',
      editable: false
    },
    {
      name: 'input_name',
      label: '字段代码',
      type: 'name',
      _default: '',
      editable: false
    },
    {
      name: 'col',
      label: '控件宽度',
      type: 'col',
      min: '2',
      max: '24',
      _default: '12',
      editable: true
    }
  ]
}
components['DatePickerWidget'] = function (param, field) {
  var temp =
    '<div class="col-{{col}}">' +
    '<div class="pw-zform-input-group">' +
    (param.prefix ? '<span class="pw-zform-prefix pw-zform-fix">{{prefix}}</span>' : '') +
    '<input class="pw-zform-input" name="{{input_name}}"/>' +
    (param.suffix ? '<span class="pw-zform-suffix pw-zform-fix">{{suffix}}</span>' : '') +
    '</div>' +
    '</div>'

  var boxEl = $(htmlTemplateTool(temp, param))
  var inputEl = boxEl.find('input')

  zForm.on('created', function () {
    inputEl.pickadate({
      // 翻译
      monthsFull: ['一　月', '二　月', '三　月', '四　月', '五　月', '六　月', '七　月', '八　月', '九　月', '十　月', '十一月', '十二月'],
      monthsShort: ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二'],
      weekdaysFull: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
      weekdaysShort: ['日', '一', '二', '三', '四', '五', '六'],
      // 按钮
      today: '今天',
      clear: '清除',
      close: '关闭',
      // 标签翻译
      labelMonthNext: '下一月',
      labelMonthPrev: '上一月',
      labelMonthSelect: '选择月',
      labelYearSelect: '选择年',
      // 格式
      format: 'yyyy-mm-dd',
      // 允许输入
      editable: false,
      // 下拉选择器
      selectYears: true,
      selectMonths: true,
      // 一周为第一天
      firstDay: true,
      // 日期范围
      min: undefined,
      max: undefined,
      // 隐藏输入容器
      containerHidden: false,
      // 关闭用户操作
      closeOnSelect: true,
      closeOnClear: true
    })
  })

  if (field.required) {
    var tip = new Tip(boxEl, {
      msg: '不能为空',
      theme: 'notice'
    })
    zForm.on('submit', function () {
      tip.hide()
      if (!inputEl.val()) {
        tip.show()
        return false
      } else {
        return true
      }
    })

    inputEl.on('mouseover', function () {
      tip.hide()
    })
  }

  return boxEl
}

/**
 * 时间选择
 * @param param
 * @returns {*|HTMLElement}
 * @constructor
 */
params['TimePickerWidget'] = {
  name: '时间',
  tag: 'TimePickerWidget',
  params: [
    {
      name: 'type',
      label: '控件类型',
      type: 'type',
      _default: '',
      editable: false
    },
    {
      name: 'input_name',
      label: '字段代码',
      type: 'name',
      _default: '',
      editable: false
    },
    {
      name: 'col',
      label: '控件宽度',
      type: 'col',
      min: '2',
      max: '24',
      _default: '12',
      editable: true
    }
  ]
}
components['TimePickerWidget'] = function (param, field) {
  var temp =
    '<div class="col-{{col}}">' +
    '<div class="pw-zform-input-group">' +
    (param.prefix ? '<span class="pw-zform-prefix pw-zform-fix">{{prefix}}</span>' : '') +
    '<input class="pw-zform-input" name="{{input_name}}"/>' +
    (param.suffix ? '<span class="pw-zform-suffix pw-zform-fix">{{suffix}}</span>' : '') +
    '</div>' +
    '</div>'

  var boxEl = $(htmlTemplateTool(temp, param))
  var inputEl = boxEl.find('input')

  zForm.on('created', function () {
    inputEl.pickatime({
      // 翻译
      clear: '清除',

      // 格式
      format: 'HH:i',

      // 时间间隔
      interval: 30,

      // 关闭用户操作
      closeOnSelect: true,
      closeOnClear: true
    })
  })

  if (field.required) {
    var tip = new Tip(boxEl, {
      msg: '不能为空',
      theme: 'notice'
    })
    zForm.on('submit', function () {
      tip.hide()
      if (!inputEl.val()) {
        tip.show()
        return false
      } else {
        return true
      }
    })

    inputEl.on('mouseover', function () {
      tip.hide()
    })
  }

  return boxEl
}

/**
 * 数字输入框
 * @param param
 * @returns {jQuery.fn.init|jQuery|HTMLElement}
 * @constructor
 */
params['InputNumberWidget'] = {
  name: '数字输入框',
  tag: 'InputNumberWidget',
  params: [
    {
      name: 'type',
      label: '控件类型',
      type: 'type',
      _default: '',
      editable: false
    },
    {
      name: 'input_name',
      label: '字段代码',
      type: 'name',
      _default: '',
      editable: false
    },
    {
      name: 'col',
      label: '控件宽度',
      type: 'col',
      min: '2',
      max: '24',
      _default: '12',
      editable: true
    },
    {
      name: 'input_value',
      label: '默认值',
      type: 'number',
      _default: 0,
      editable: true
    },
    {
      name: 'prefix',
      label: '前缀文字',
      type: 'text',
      _default: '',
      editable: true
    },
    {
      name: 'suffix',
      label: '后缀文字',
      type: 'text',
      _default: '',
      editable: true
    }
  ]
}
components['InputNumberWidget'] = function (param, field) {
  var value = parseInt(param.input_value) || 0
  var data = JSON.parse(JSON.stringify(param))
  data.value = value

  var temp =
    '<div class="col-{{col}}">' +
    '<div class="pw-zform-input-group">' +
    (param.prefix ? '<span class="pw-zform-prefix pw-zform-fix">{{prefix}}</span>' : '') +
    '<div class="pw-zform-number">' +
    '<input class="pw-zform-input" type="text" name="{{input_name}}" value="{{value}}" verify="NotNull&&Number&&Int" />' +
    '<span class="pw-zform-number-dw">&nbsp;-&nbsp;</span>' +
    '<span class="pw-zform-number-up">&nbsp+&nbsp</span>' +
    '</div>' +
    (param.suffix ? '<span class="pw-zform-suffix pw-zform-fix">{{suffix}}</span>' : '') +
    '</div>' +
    '</div>'

  var el = $(htmlTemplateTool(temp, data))

  var inputBoxEl = el.find('.pw-zform-number')
  var inputEl = el.find('.pw-zform-input')
  var dwEl = el.find('.pw-zform-number-dw')
  var upEl = el.find('.pw-zform-number-up')

  inputBoxEl.on('mouseover', function () {
    inputBoxEl.addClass('hover')
  })

  inputBoxEl.on('mouseout', function () {
    inputBoxEl.removeClass('hover')
  })

  dwEl.on('mouseover', function () {
    dwEl.addClass('hover')
  })

  dwEl.on('mouseout', function () {
    dwEl.removeClass('hover')
  })

  upEl.on('mouseover', function () {
    upEl.addClass('hover')
  })

  upEl.on('mouseout', function () {
    upEl.removeClass('hover')
  })

  dwEl.on('click', function () {
    inputEl.val(--value)
  })

  upEl.on('click', function () {
    inputEl.val(++value)
  })

  inputEl.on('change', function () {
    value = parseInt($(this).val()) || 0
  })

  return el
}

/**
 * 开关
 * @param param
 * @returns {jQuery.fn.init|jQuery|HTMLElement}
 * @constructor
 */
params['SwitchWidget'] = {
  name: '开关',
  tag: 'SwitchWidget',
  params: [
    {
      name: 'type',
      label: '控件类型',
      type: 'type',
      _default: '',
      editable: false
    },
    {
      name: 'input_name',
      label: '字段代码',
      type: 'name',
      _default: '',
      editable: false
    },
    {
      name: 'col',
      label: '控件宽度',
      type: 'col',
      min: '2',
      max: '24',
      _default: '12',
      editable: true
    }
  ]
}
components['SwitchWidget'] = function (param, field) {
  var temp =
    '<div class="col-{{col}}">' +
    '<label style="max-width: 100%">' +
    '<label class="pw-zform-switch">' +
    '<input type="checkbox" value="true" name="{{input_name}}"/>' +
    '<span class="pw-zform-switch-back"></span>' +
    '<span class="pw-zform-switch-dot"></span>' +
    '</label>' +
    '</label>' +
    '</div>'

  var el = $(htmlTemplateTool(temp, param))
  var label = el.find('.pw-zform-switch')
  var inputEl = el.find('input')
  inputEl.on('change', function () {
    if (inputEl[0].checked) {
      label.addClass('checked')
    } else {
      label.removeClass('checked')
    }
  })
  return el
}

/**
 * 文件选择
 * @param param
 * @returns {jQuery|HTMLElement}
 * @constructor
 */
params['UploadWidget'] = {
  name: '文件选择',
  tag: 'UploadWidget',
  params: [
    {
      name: 'type',
      label: '控件类型',
      type: 'type',
      _default: '',
      editable: false
    },
    {
      name: 'input_name',
      label: '字段代码',
      type: 'name',
      _default: '',
      editable: false
    },
    {
      name: 'col',
      label: '控件宽度',
      type: 'col',
      min: '2',
      max: '24',
      _default: '12',
      editable: true
    },
    {
      name: 'accept',
      label: '文件类型',
      type: 'accept',
      _default: '',
      editable: true
    }
  ]
}
components['UploadWidget'] = function (param, field) {
  var data = JSON.parse(JSON.stringify(param))
  data.input_id = new ObjectId().toString()
  var temp =
    '<div class="col-{{col}}">' +
    '<input style="width: 100%;margin: 4px 0" type="file" id="{{input_id}}" name="{{input_name}}" accept="{{accept}}"/>' +
    '</div>'

  var box = $(htmlTemplateTool(temp, data))
  var inputEl = box.find('input[type=file]')

  var tip

  if (inputEl[0].files) {
    inputEl.css('opacity', '0')
    inputEl.css('z-index', '-1')
    inputEl.css('position', 'absolute')

    var view = $('<div class="pw-zform-upload"></div>')
    var btn = $('<label class="pw-zform-btn" for="' + data.input_id + '">选择文件</label>')
    var info = $('<div class="pw-zform-upload-info"><div>')
    var name = $('<span class="pw-zform-upload-name">暂未选择文件</span>')
    var clear = $('<a href="javascript: void(0)" class="pw-zform-upload-clear">X</a>')
    info.append(name)
    info.append(clear)
    view.append(btn)
    view.append(info)
    box.append(view)

    tip = new Tip(btn, {
      msg: '必须选择一个文件!',
      theme: 'notice'
    })

    inputEl.on('change', function () {
      if (this.files.length && this.files[0] && this.files[0].name) {
        name.text(this.files[0].name)
        info.addClass('action')
      } else {
        name.text('暂未选择文件')
        info.removeClass('action')
      }
    })

    clear.on('click', function () {
      inputEl[0].value = ''
      name.text('暂未选择文件')
      info.removeClass('action')
    })

    zForm.on('reset', function () {
      inputEl[0].value = ''
      name.text('暂未选择文件')
      info.removeClass('action')
    })
  } else {
    tip = new Tip(box, {
      msg: '必须选择一个文件!',
      theme: 'notice'
    })
  }

  if (field.required) {
    zForm.on('submit', function () {
      if (inputEl.val() === '') {
        tip.show()
        return false
      } else return true
    })
  }

  box.on('mouseover', function () {
    tip.hide()
  })

  return box
}

/**
 * 文件选择
 * @param param
 * @returns {jQuery|HTMLElement}
 * @constructor
 */
params['AddressWidget'] = {
  name: '地址选择',
  tag: 'AddressWidget',
  params: [
    {
      name: 'type',
      label: '控件类型',
      type: 'type',
      _default: '',
      editable: false
    },
    {
      name: 'input_name',
      label: '字段代码',
      type: 'name',
      _default: '',
      editable: false
    },
    {
      name: 'col',
      label: '控件宽度',
      type: 'col',
      min: '2',
      max: '24',
      _default: '12',
      editable: true
    },
    {
      name: 'address',
      label: '地址范围',
      type: 'address',
      _default: {
        province: '',
        city: ''
      },
      editable: true
    }
  ]
}
components['AddressWidget'] = function (param, field) {
  var temp =
    '<div class="col-{{col}}">' +
    '<div class="col-8"><select class="pw-zform-input" name="{{input_name}}-province"></select></div>' +
    '<div class="col-8"><select class="pw-zform-input" name="{{input_name}}-city"></select></div>' +
    '<div class="col-8"><select class="pw-zform-input" name="{{input_name}}-county"></select></div>' +
    '</div>'

  var box = $(htmlTemplateTool(temp, param))

  var value = {}

  var provinceSelector = box.find('select.pw-zform-input[name$=-province]')
  var citySelector = box.find('select.pw-zform-input[name$=-city]')
  var countySelector = box.find('select.pw-zform-input[name$=-county]')

  function provinceOptions () {
    var opts = ''
    $.each(addressData, function (v) {
      opts += '<option value="' + v + '">' + v + '</option>'
    })
    return opts
  }

  function cityOptions () {
    var opts = ''
    if (value.province) {
      $.each(addressData[value.province], function (v) {
        opts += '<option value="' + v + '">' + v + '</option>'
      })
    }
    return opts
  }

  function countyOptions () {
    var opts = ''
    if (value.province && value.city) {
      $.each(addressData[value.province][value.city], function (i, v) {
        opts += '<option value="' + v + '">' + v + '</option>'
      })
    }
    return opts
  }

  function onProvinceChange () {
    value.province = provinceSelector.val()
    citySelector.html(cityOptions())
    onCityChange()
  }

  function onCityChange () {
    value.city = citySelector.val()
    countySelector.html(countyOptions())
  }

  provinceSelector.on('change', onProvinceChange)
  citySelector.on('change', onCityChange)

  zForm.on('created', function () {
    setTimeout(function () {
      provinceSelector.html(provinceOptions())
      if (param.address && param.address.province) {
        provinceSelector.val(param.address.province)
        provinceSelector.attr('disabled', 'disabled')
      }
      onProvinceChange()
      if (param.address && param.address.city) {
        citySelector.val(param.address.city)
        citySelector.attr('disabled', 'disabled')
      }
    }, 500)
  })

  return box
}

params.item = [
  {
    name: 'required',
    label: '是否必填',
    type: 'boolean',
    _default: '',
    editable: true
  },
  {
    name: 'label',
    label: '标签文字',
    type: 'text',
    _default: '标签',
    editable: true
  },
  {
    name: 'top',
    label: '顶部文字',
    type: 'text',
    _default: '',
    editable: true
  },
  {
    name: 'help',
    label: '帮助文字',
    type: 'text',
    _default: '',
    editable: true
  },
  {
    name: 'layout',
    label: '标签宽度',
    type: 'layout',
    _default: {
      label: 8,
      content: 16
    },
    editable: true
  },
  {
    name: 'controls',
    label: '控件参数',
    type: 'controls',
    _default: [],
    editable: true
  }
]

/**
 * 构建表单行
 * @param field
 * @param index
 * @returns {jQuery.fn.init|jQuery|HTMLElement}
 */
function getFormItemEl (field, index) {
  var layout = typeof field.layout === 'object'
    ? field.layout
    : {
      label: 8,
      content: 16
    }
  // 外壳
  var itemEl = $('<div class="pw-zform-item" item-index="' + index + '"></div>')
  // label部分
  var labelEl = $('<div class="pw-zform-item-label"></div>')
  labelEl.text(field.label || '')
  labelEl.addClass(layout.label ? 'col-' + layout.label : 'col-8')
  if (field.required) labelEl.addClass('required')
  if (!field.label) labelEl.addClass('pw-zform-item-label-no')
  itemEl.append(labelEl)
  // 内容部分
  var controlEl = $('<div class="pw-zform-item-content"></div>')
  controlEl.addClass(layout.content ? 'col-' + layout.content : 'col-16')
  // top
  if (field.top) {
    controlEl.append('<div class="pw-zform-item-control-top">' + field.top + '</div>')
  }
  // 核心内容部分
  var contentLineEl = $('<div class="pw-zform-control-box"></div>')
  // 前缀
  if (field.prefix) {
    contentLineEl.append('<span class="pw-zform-item-prefix">' + field.prefix + '</span>')
  }
  // 控件
  contentLineEl.append(getControlEl($('<div class="pw-zform-item-control"></div>'), field))
  // 后缀
  if (field.suffix) {
    contentLineEl.append('<span class="pw-zform-item-suffix">' + field.suffix + '</span>')
  }
  controlEl.append(contentLineEl)
  // 帮助
  if (field.help) {
    controlEl.append('<div class="pw-zform-item-help">' + field.help + '</div>')
  }

  itemEl.append(controlEl)
  return itemEl
}

function getControlEl (el, field) {
  var box = $('<div class="pw-zform-item-control-box"></div>')
  for (var i = 0, len = field.controls.length; i < len; i++) {
    var control = field.controls[i]
    var component = components[control.type]
    if (typeof component === 'function') {
      box.append(component(control, field))
    }
  }
  el.append(box)
  return el
}

params.form = [
  {
    name: 'title',
    label: '表单标题',
    type: 'text',
    _default: '',
    editable: true
  },
  {
    name: 'help',
    label: '表单说明',
    type: 'text',
    _default: '',
    editable: true
  },
  {
    name: 'layout',
    label: '标签宽度',
    type: 'layout',
    _default: {
      label: 8,
      content: 16
    },
    editable: true
  },
  {
    name: 'method',
    label: '提交方式',
    type: 'text',
    _default: 'POST',
    editable: false
  },
  {
    name: 'action',
    label: '提交目标',
    type: 'text',
    _default: 'front/customforms',
    editable: false
  },
  {
    name: 'auth',
    label: '验证码地址',
    type: 'text',
    _default: 'front/authCode.png',
    editable: false
  }
]

/**
 * 创建表单(element)
 * @param data 模板数据
 * @param moduleId 模块ID
 */
function getFormEl (data, moduleId, siteID) {
  var url = window.frontAppContext || '/'
  zForm.iframeName = 'hidden_iframe_' + new ObjectId().toString()

  var form = $(
    '<form class="pw-zform" enctype="multipart/form-data"' +
      (data.method ? ' method="' + data.method + '"' : '') +
      (data.action ? ' action="' + (url + data.action) + '"' : '') +
      ' target="' +
      zForm.iframeName +
      '"></form>'
  )

  if (moduleId) {
    var moduleIdEl = '<input type="hidden" name="moduleId" value="' + moduleId + '"/>'
    form.append(moduleIdEl)
  }

  if (siteID) {
    var siteIDEl = '<input type="hidden" name="siteID" value="' + siteID + '"/>'
    form.append(siteIDEl)
  }

  var timeEl = $('<input type="hidden" name="answerTime" value=""/>')
  form.append(timeEl)
  formInfo.timeEl = timeEl

  var titleBox = $('<div class="pw-zform-title-box"></div>')
  titleBox.append('<h4 class="pw-zform-title">' + (data.title || '') + '</h4>')
  titleBox.append('<p class="pw-zform-help">' + (data.help || '') + '</p>')
  form.append(titleBox)

  var itemBox = $('<div class="pw-zform-item-box"></div>')
  for (var i = 0, len = data.fields.length; i < len; i++) {
    itemBox.append(getFormItemEl(data.fields[i], i))
  }
  form.append(itemBox)

  var layout = typeof data.layout === 'object'
    ? data.layout
    : {
      label: 8,
      content: 16
    }
  var authCode = $('<div class="pw-zform-footer"></div>')
  var labelElAuth = $('<div class="pw-zform-item-label required">验证码</div>')
  labelElAuth.addClass(layout.label ? 'col-' + layout.label : 'col-8')
  authCode.append(labelElAuth)
  var controlElAuth = $('<div class="pw-zform-item-content"></div>')
  controlElAuth.addClass(layout.content ? 'col-' + layout.content : 'col-16')
  var authControlBox = $('<div class="col-24"></div>')
  var tab = $('<div class="pw-zform-input-group"></div>')
  var authBox = $('<span class="pw-zform-prefix pw-zform-fix"></span>')
  var auth = $('<img class="pw-zform-auth-code" src="' + (url + data.auth + '?' + new Date().getTime()) + '"/>')

  auth.on('click', function () {
    this.src = url + data.auth + '?' + new Date().getTime()
  })

  authBox.append(auth)
  authBox.append('<span></span>')
  tab.append(authBox)
  var inputGroup = $('<div class="pw-zform-input"></div>')
  var inputEl = $('<input class="pw-zform-input" type="text" name="authCode" placeholder="请输入验证码" verify="NotNull"/>')
  inputGroup.append(inputEl)
  tab.append(inputGroup)
  authControlBox.append(tab)
  controlElAuth.append(authControlBox)
  authCode.append(controlElAuth)
  form.append(authCode)

  // 提交重置按钮
  var footer = $('<div class="pw-zform-footer"></div>')
  var labelElBtn = $('<div class="pw-zform-item-label pw-zform-item-label-no"></div>')
  labelElBtn.addClass(layout.label ? 'col-' + layout.label : 'col-8')

  var controlElBtn = $('<div class="pw-zform-item-content"></div>')
  controlElBtn.addClass(layout.content ? 'col-' + layout.content : 'col-16')

  var submitEl = $('<input type="submit" class="pw-zform-btn pw-zform-btn-success" value="提交"/>')
  controlElBtn.append(submitEl)

  var resetEl = $('<input type="reset" class="pw-zform-btn pw-zform-btn-default" value="重置"/>')
  controlElBtn.append(resetEl)
  footer.append(labelElBtn)
  footer.append(controlElBtn)
  form.append(footer)

  form.on('reset', function () {
    zForm.onReset()
  })

  var submitCallback = function (data) {
    console.log(data)
    zForm.formInfo.submitting = false
    if (data.status === 1) {
      alert(data.message)
      // todo:跳转到其他页面
    } else {
      alert(data.message)
      submitEl.attr('disabled', false)
      submitEl.removeClass('pw-zform-loading')
      resetEl.attr('disabled', false)
    }
  }

  form.on('submit', function () {
    if (zForm.formInfo.submitting) {
      return false
    } else {
      var time = Date.now() - formInfo.createTime
      console.log('时间: ', time)
      formInfo.timeEl.val(time)

      var submit = zForm.onSubmit()
      var verify = Verify.hasError(null, form)
      console.log('定义验证状态: ', submit)
      console.log('验证框架状态: ', verify)

      if (submit && !verify) {
        zForm.formInfo.submitting = true
        submitEl.attr('disabled', true)
        submitEl.addClass('pw-zform-loading')
        resetEl.attr('disabled', true)

        var iframe = document.createElement('iframe')
        iframe.style.display = 'none'
        iframe.name = zForm.iframeName
        document.body.appendChild(iframe)
        var state = 0
        var url = window.location.protocol + '//' + window.location.host + '/proxy.html'

        $(iframe).on('load', function () {
          if (state === 1) {
            state = 0
            submitCallback(JSON.parse(iframe.contentWindow.name))
            document.body.removeChild(iframe)
          } else if (state === 0) {
            state = 1
            iframe.contentWindow.location = url
          }
        })

        return true
      } else {
        return false
      }
    }
  })

  return form
}

/**
 * 创建表单
 * @param dom
 * @param data
 */
zForm.createForm = function (dom, data, moduleId, siteID) {
  dom = $(dom)
  if (dom) {
    zForm.createdEventListeners = []
    zForm.resetEventListeners = []
    zForm.submitEventListeners = []
    var form = getFormEl(data, moduleId, siteID)
    if (form) {
      dom.html('')
      dom.append(form)
      zForm.onCreated()
      Verify.init(dom)
      form.find('span.verify-mandatory.form-control-feedback[ztype=Verify]').hide()
      formInfo.createTime = Date.now()
    }
  }
}

zForm.createdEventListeners = []
zForm.resetEventListeners = []
zForm.submitEventListeners = []

zForm.on = function (type, callback) {
  if (zForm[type + 'EventListeners'] && typeof callback === 'function') {
    zForm[type + 'EventListeners'].push(callback)
  } else {
    console.warn('绑定' + type + '事件发生参数错误!')
  }
}

zForm.onReset = function () {
  $.each(zForm.resetEventListeners, function () {
    this()
  })
}

zForm.onCreated = function () {
  $.each(zForm.createdEventListeners, function () {
    this()
  })
}

zForm.onSubmit = function () {
  var tag = true
  $.each(zForm.submitEventListeners, function () {
    if (!this()) {
      tag = false
    }
  })
  return tag
}

/**
 * 整理数据(寻找入口,映射对象,方便索引)
 * @param temp
 */
zForm.zcmsDataFormat = function (temp) {
  var dataMap = {}
  var main = ''
  var filterKeys = ['Section', 'Breakpoint', 'ColumnGridSettings', 'UserSettings']
  $.each(temp, function (typeName, typeContent) {
    if ($.inArray(typeName, filterKeys) < 0) {
      $.each(typeContent, function (id, value) {
        dataMap[value.id] = value
      })
    } else if (typeName === 'Section') {
      $.each(typeContent, function (id, value) {
        if (value.child_containers.length) {
          main = value.child_containers[0]
          return false
        }
      })
    }
  })
  return zForm.formatDataToJson(dataMap, main)
}

/**
 * 转化数据为zform需要的json格式
 * @param map
 * @param main
 */
zForm.formatDataToJson = function (map, main) {
  var jData = {}
  // 目标数据
  var fields = [] // 字段信息
  if (main) {
    var form = map[main]
    var formItems = []
    // 查找所有form-item
    $.each(form.child_containers, function (i1, itemId) {
      var formItem = map[itemId]
      formItem.content = []
      $.each(formItem.child_containers, function (i2, contentId) {
        formItem.content.push(map[contentId])
      })
      formItems.push(formItem)
    })

    // 遍历form-item生成字段信息
    $.each(formItems, function (i1, formItem) {
      // form-item内容区设置信息
      var field = {}
      $.each(params.item, function () {
        if (this.type === 'controls') {
          var controls = []
          $.each(formItem.content, function (i2, contentItem) {
            if (contentItem._cls && params[contentItem._cls]) {
              var contentData = {}
              $.each(params[contentItem._cls].params, function () {
                if (this.name === 'type') {
                  contentData.type = contentItem._cls
                } else {
                  if (contentItem[this.name]) {
                    contentData[this.name] = contentItem[this.name]
                  } else if (typeof this._default === 'object') {
                    contentData[this.name] = JSON.parse(JSON.stringify(this._default))
                  } else {
                    contentData[this.name] = this._default
                  }
                }
              })
              controls.push(contentData)
            }
          })
          field.controls = controls
        } else if (typeof this._default === 'object') {
          field[this.name] = JSON.parse(JSON.stringify(this._default))
        } else {
          field[this.name] = formItem[this.name] || this._default
        }
      })

      fields.push(field)
    })

    // 映射form信息
    $.each(params.form, function () {
      jData[this.name] = form[this.name] || this._default
    })
    jData.fields = fields
  }

  return jData
}

/**
 * 转化数据为专题数据格式
 * @param json
 */
zForm.formatJsonToData = function (json) {
  var data = {
    Style: {},
    CssClass: {},
    Container: {},
    TextWidget: {},
    ImageWidget: {},
    GridWidget: {},
    SVGWidget: {},
    NavigationToggleWidget: {},
    NavigationWidget: {},
    SlideshowWidget: {},
    VideoWidget: {},
    HTMLWidget: {},
    DynamicListWidget: {},
    ChartWidget: {},
    Breakpoint: {},
    ColumnGridSettings: {},
    UserSettings: {},
    Section: {},
    FormWidget: {},
    FormItemWidget: {}
  }

  $.each(params, function (k, v) {
    if (k !== 'form' && k !== 'item') data[k] = {}
  })

  var sectionId = new ObjectId().toString()
  var formId = new ObjectId().toString()
  data.Section[sectionId] = {
    _cls: 'Section',
    child_containers: [formId],
    css_classes: [],
    disallow_block_tags: false,
    id: sectionId,
    name: '',
    is_homepage: true,
    is_mobile_first: false,
    is_preserved: false,
    is_published: false,
    is_section_level: false,
    locked: false,
    overrides_visual_class: false,
    slug: '/',
    tag: 'div',
    url: ''
  }

  data.FormWidget[formId] = {
    _cls: 'FormWidget',
    id: formId,
    parent_container: sectionId,
    child_containers: []
  }

  $.each(params.form, function () {
    data.FormWidget[formId][this.name] = json[this.name]
  })

  data.FormItemWidget = {}
  $.each(json.fields, function () {
    var field = this
    var id = new ObjectId().toString()
    var item = {
      _cls: 'FormItemWidget',
      id: id,
      child_containers: [],
      parent_container: formId
    }

    $.each(params.item, function () {
      if (this.name !== 'controls') item[this.name] = field[this.name]
    })

    $.each(field.controls, function () {
      var control = this
      var cid = new ObjectId().toString()
      var controlData = {
        id: cid,
        parent_container: id
      }
      $.each(params[control.type].params, function () {
        if (this.name === 'type') {
          controlData._cls = control.type
        } else {
          controlData[this.name] = control[this.name]
        }
      })

      data[control.type][cid] = controlData
      item.child_containers.push(cid)
    })

    data.FormItemWidget[id] = item
    data.FormWidget[formId].child_containers.push(id)
  })

  return data
}

// 2016-5-16 更改为19位长的数字 9位当前时间秒数 3位浏览器特征转换为的机器码 3位随机数为伪进程码 4位为自增长码
var ObjectId = (function () {
  var hashCode = function (str) {
    var hash = 0
    var i = 0

    var len = str.length
    for (; i < len; i++) {
      hash = ((hash << 5) ^ (hash >> 27) ^ str.charCodeAt(i)) & 0xfffffff // 总是得到少于268435455的正数，
    }
    return hash
  }
  var increment = 0
  var pid = Math.floor(Math.random() * 1000)
  var machine = hashCode([navigator.userAgent, navigator.language, navigator.language, screen.height, screen.width].join('#')) % 1000
  if (typeof localStorage !== 'undefined') {
    var mongoMachineId = parseInt(localStorage['mongoMachineId'])
    if (mongoMachineId > 0 && mongoMachineId < 1000) {
      machine = Math.floor(localStorage['mongoMachineId'])
    }
    localStorage['mongoMachineId'] = machine
    document.cookie = 'mongoMachineId=' + machine + ';expires=Tue, 19 Jan 2038 05:00:00 GMT'
  } else {
    var cookieList = document.cookie.split('; ')
    for (var i in cookieList) {
      var cookie = cookieList[i].split('=')
      if (cookie[0] === 'mongoMachineId' && cookie[1] > 0 && cookie[1] < 1000) {
        machine = cookie[1]
        break
      }
    }
    document.cookie = 'mongoMachineId=' + machine + ';expires=Tue, 19 Jan 2038 05:00:00 GMT'
  }
  return function () {
    if (!(this instanceof ObjectId)) {
      return new ObjectId(arguments[0], arguments[1], arguments[2], arguments[3]).toString()
    }
    if (typeof arguments[0] === 'object') {
      this.timestamp = arguments[0].timestamp
      this.machine = arguments[0].machine
      this.pid = arguments[0].pid
      this.increment = arguments[0].increment
    } else if (typeof arguments[0] === 'string' && arguments[0].length === 24) {
      this.timestamp = Number(arguments[0].substr(0, 9))
      this.machine = Number(arguments[0].substr(9, 3))
      this.pid = Number(arguments[0].substr(12, 3))
      this.increment = Number(arguments[0].substr(15, 4))
    } else if (arguments.length === 4 && arguments[0] !== null) {
      this.timestamp = arguments[0]
      this.machine = arguments[1]
      this.pid = arguments[2]
      this.increment = arguments[3]
    } else {
      this.timestamp = Math.floor(new Date().valueOf() / 1000)
      if (this.timestamp > 900000000) {
        // 只取9位数
        this.timestamp = this.timestamp % 900000000
      }
      this.machine = machine
      this.pid = pid
      if (increment > 9999) {
        increment = 0
      }
      this.increment = increment++
    }
  }
})()

ObjectId.prototype.getDate = function () {
  if (+new Date() > 900000000 && this.timestamp <= 900000000) {
    this.timestamp += 900000000
  }
  return new Date(this.timestamp * 1000)
}

ObjectId.prototype.toString = function () {
  var timestamp = this.timestamp.toString()
  var machine = this.machine.toString()
  var pid = this.pid.toString()
  var increment = this.increment.toString()
  return (
    '000000000'.substr(0, 9 - timestamp.length) +
    timestamp +
    '000'.substr(0, 3 - machine.length) +
    machine +
    '000'.substr(0, 3 - pid.length) +
    pid +
    '0000'.substr(0, 4 - increment.length) +
    increment
  )
}

var htmlTemplateToolTask = function (temp, data, p) {
  $.each(data, function (k, v) {
    if (typeof v === 'object') {
      temp = htmlTemplateToolTask(temp, v, p ? p + '.' + k : k)
    } else {
      temp = temp.replace(new RegExp('\\{\\{' + (p ? p + '\\.' + k : k) + '\\}\\}', 'gm'), v || '')
    }
  })
  return temp
}

var htmlTemplateTool = function (temp, data) {
  if (typeof temp === 'string' && typeof data === 'object') {
    return htmlTemplateToolTask(temp, data, '')
  } else {
    console.warn('模板渲染,参数类型错误,请检查代码!')
    return ''
  }
}

module.exports = zForm
