<template>
  <div class="aos-form" ref="formContainer">
    <el-form
      class="aos-form clearfix"
      :model="copyData"
      ref="form"
      style="width: 100%"
      :rules="formRules"
      :edit="edit"
      :label-position="labelPosition"
      :label-width="labelWidth"
    >
      <el-form-item
        v-for="(item,index) in copyFormTemplate"
        :key="item.prop"
        class="aos-form-item"
        :class="{'aos-form-item-sm': formItemSm,'aos-form-item-md':formItemMd,'aos-form-item-xl':formItemXl,'aos-form-item-lg':formItemLg, 'aos-form-item-hlg': formItemHLg}"
        :title="item.label"
        :label="item.label"
        :rules="item.rules"
        :required="item.required || false"
        :style="'width:' + item.width"
        label-width="130px"
        :prop="item.prop"
      >
        <template v-if="item.type === 'input' || '' || undefined">
          <el-input
            :title="copyData[item.prop]"
            :ref="item.prop + '-ref'"
            v-if="edit"
            :style="{width: (item.attrs && item.attrs.width) || ''}"
            v-model.trim="copyData[item.prop]"
            :type="(item.attrs && item.attrs.type) || 'text'"
            :minlength="(item.attrs && item.attrs.minlength) || 0"
            :maxlength="(item.attrs && item.attrs.maxlength) || 10000"
            :placeholder="(item.attrs && item.attrs.placeholder) || '请在此输入'"
            :clearable="!item.attrs || (item.attrs && item.attrs.clearable !== false)"
            :size="(item.attrs && item.attrs.size) || 'small'"
            :disabled="(item.attrs && item.attrs.disabled) || false"
            :show-word-limit="(item.attrs && item.attrs.showWordLimit) || false"
            :show-password="(item.attrs && item.attrs.showPassword) || false"
            :readonly="(item.attrs && item.attrs.readonly)"
            :max="(item.attrs && item.attrs.max)"
            :min="(item.attrs && item.attrs.min)"
            :step="(item.attrs && item.attrs.step)"
            :resize="(item.attrs && item.attrs.resize)"
            :autofocus="(item.attrs && item.attrs.autofocus) || false"
            :validate-event="(item.attrs && item.attrs.validateEvent) || true"
            :text-align="(item.attrs && item.attrs.textAlign) || 'left'"
            :data-can-copy="(item.attrs && item.attrs.dataCanCopy)"
            @blur="formHandleEmit(item,'blur')"
            @change="formHandleEmit(item,'change')"
            @input="formHandleEmit(item,'input')"
            @focus="formHandleEmit(item,'focus')"
            @clear="formHandleEmit(item,'clear')"
          >
          <template v-if="item.attrs && (item.attrs.suffixString || item.attrs.buttonString || item.attrs.secondButtonString || item.attrs.countTime || item.attrs.icon || item.attrs.ocrType)">
            <div slot="append">
              <div class="aos-form-input-append" v-if="item.attrs.suffixString" @click="formHandleEmit(item,'suffix')">
                {{item.attrs.suffixString ? item.attrs.suffixString : ''}}
              </div>
              <span style="cursor: pointer;" :style="{'margin-left':item.attrs.suffixString ? '8px' : '0px', 'color': (item.attrs && item.attrs.iconActive) ? '#409EFF' : '#909399'}" type="primary" v-if="item.attrs.icon" :title="item.attrs.iconTitle" @click="formHandleEmit(item,'icon')">
                <i :class="'el-icon-' + item.attrs.icon"></i>
              </span>
              <span style="color:#409EFF;cursor: pointer;" :style="{'margin-left':item.attrs.icon ? '8px' : '0px'}" :title="item.attrs.buttonString" type="primary" v-if="item.attrs.buttonString" @click="formHandleEmit(item,'button')">
                {{item.attrs.buttonString ? item.attrs.buttonString : ''}}
              </span>
              <span style="color:#409EFF;border-left:1px solid #eee;cursor: pointer;" :title="item.attrs.secondButtonString" type="primary" v-if="item.attrs.secondButtonString" @click="formHandleEmit(item,'second-button')">
                {{item.attrs.secondButtonString ? item.attrs.secondButtonString : ''}}
              </span>
              <aos-count-time 
                v-if="item.attrs.countTime"
                :ref="item.prop + '-count-time-ref'"
                @click="formHandleEmit(item,'count-time')"
                :time="item.attrs.countTime.time" 
                :count-name="item.attrs.countTime.countName"
                :default-name="item.attrs.countTime.defaultName"
                :disabled="item.attrs.countTime.disabled"
                :auto-count="item.attrs.countTime.autoCount">
              </aos-count-time>
              <el-upload
                v-if="item.attrs && item.attrs.ocrType"
                :action="'/cmbiz/api/ocr/'+ocrObject[item.attrs.ocrType]"
                :data="data"
                :disabled="!edit"
                :show-file-list="false"
                :on-preview="(response, file, fileList) => {handleInlineOcr(item,'preview',response, file, fileList)}"
                :on-remove="(response, file, fileList) => {handleInlineOcr(item,'remove',response, file, fileList)}"
                :on-error="(response, file, fileList) => {handleInlineOcr(item,'error',response, file, fileList)}"
                :on-success="(response, file, fileList) => {handleInlineOcr(item,'success',response, file, fileList)}">
                <div slot="trigger">
                  <el-button v-if="item.attrs.ocrType" :disabled="!edit" icon="el-icon-camera"></el-button>
                </div>
              </el-upload>
            </div>
          </template>
          </el-input>
          <div class="el-form-item__content aos-form-input-text" v-else>
            <div :title="copyData[item.prop]">
              {{copyData[item.prop]}}
              <span style="margin-left: 8px;" v-if="item.attrs && item.attrs.suffixString">{{item.attrs.suffixString}}</span>
              <span style="margin-left: 8px;" v-if="item.viewSlot">
                <slot :name="item.prop+'-view-slot'" :scope="copyData"></slot>
              </span>
            </div>
          </div>
        </template>
        <template v-if="item.type == 'textarea'">
          <el-input
            :ref="item.prop + '-ref'"
            v-if="edit"
            :title="copyData[item.prop]"
            v-model="copyData[item.prop]"
            type="textarea"
            style="width: 100%"
            :style="{width: (item.attrs && item.attrs.width) || ''}"
            :size="(item.attrs && item.attrs.size) || 'small'"
            :minlength="(item.attrs && item.attrs.minlength) || 0"
            :maxlength="(item.attrs && item.attrs.maxlength) || 10000"
            :rows="(item.attrs && item.attrs.rows) || 4"
            :placeholder="(item.attrs && item.attrs.placeholder) || '请在此输入'"
            :disabled="(item.attrs && item.attrs.disabled) || false"
            :show-word-limit="(item.attrs && item.attrs.showWordLimit) || false"
            :autosize="(item.attrs && item.attrs.autosize) || false"
            :data-can-copy="(item.attrs && item.attrs.dataCanCopy)"
            @blur="formHandleEmit(item,'blur')"
            @change="formHandleEmit(item,'change')"
            @focus="formHandleEmit(item,'focus')"
            @clear="formHandleEmit(item,'clear')"
          ></el-input>
          <div class="el-form-item__content aos-form-input-text" v-else>
            <div :title="copyData[item.prop]">{{copyData[item.prop]}}</div>
          </div>
        </template>
        <template v-if="item.type == 'select'">
          <el-select 
            :ref="item.prop + '-ref'"
            v-if="edit"
            v-model="copyData[item.prop]"
            :title="copyData[item.prop]"
            :placeholder="(item.attrs && item.attrs.placeholder) || '请在此输入'"
            :disabled="(item.attrs && item.attrs.disabled) || false"
            :clearable="!item.attrs || (item.attrs && item.attrs.clearable !== false)"
            :multiple="(item.attrs && item.attrs.multiple) || false"
            :size="(item.attrs && item.attrs.size) || 'small'"
            :collapse-tags="(item.attrs && item.attrs['collapse-tags']) || false"
            :multiple-limit="(item.attrs && item.attrs['multiple-limit']) || 0"
            :filterable="(item.attrs && item.attrs.filterable) || false"
            :allow-create="(item.attrs && item.attrs['allow-create']) || false"
            :filter-method="(item.attrs && item.attrs['filter-method']) || function(){}"
            :remote="(item.attrs && item.attrs.remote) || false"
            :remote-method="(item.attrs && item.attrs['remote-method']) || function(){}"
            :loading="(item.attrs && item.attrs.loading) || false"
            :no-match-text="(item.attrs && item.attrs['no-match-text']) || '无匹配数据'"
            :no-data-text="(item.attrs && item.attrs['no-data-text']) || '无数据'"
            :reserve-keyword="(item.attrs && item.attrs['reserve-keyword']) || false"
            :default-first-option="(item.attrs && item.attrs['default-first-option']) || false"
            :popper-append-to-body="(item.attrs && item.attrs['popper-append-to-body']) || true"
            @change="formHandleEmit(item,'change')"
            @visible-change="formHandleEmit(item,'visible-change')"
            @remove-tag="formHandleEmit(item,'remove-tag')"
            @clear="formHandleEmit(item,'clear')"
            @blur="formHandleEmit(item,'blur')"
            @focus="formHandleEmit(item,'focus')">
            <el-option
              v-for="item in item.option"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            ></el-option>
          </el-select>
          <div class="el-form-item__content aos-form-input-text" v-else>
            <div>{{ selectNoEditLabelObject[item.prop]}}</div>
          </div>
        </template>
        <template v-if="item.type == 'time-picker'">
          <el-time-picker
            :ref="item.prop + '-ref'"
            v-model="copyData[item.prop]"
            :title="copyData[item.prop]"
            v-if="edit"
            :readonly="(item.attrs && item.attrs.readonly) || false"
            :disabled="(item.attrs && item.attrs.disabled) || false"
            :editable="(item.attrs && item.attrs.editable) || true"
            :clearable="!item.attrs || (item.attrs && item.attrs.clearable !== false)"
            :size="(item.attrs && item.attrs.size) || 'small'"
            :placeholder="(item.attrs && item.attrs.placeholder) || '请选择时间'"
            :is-range="(item.attrs && item.attrs['is-range']) || false"
            :arrow-control="(item.attrs && item.attrs['arrow-control']) || false"
            :start-placeholder="(item.attrs && item.attrs['start-placeholder']) || '开始时间'"
            :end-placeholder="(item.attrs && item.attrs['end-placeholder']) || '结束时间'"
            :align="(item.attrs && item.attrs.align) || 'left'"
            :picker-options="(item.attrs && item.attrs['picker-options']) || {format: 'HH:mm:ss'}"
            :range-separator="(item.attrs && item.attrs['range-separator']) || '-'"
            :value-format="(item.attrs && item.attrs['value-format']) || 'HH:mm:ss'"
            :prefix-icon="(item.attrs && item.attrs['prefix-icon']) || 'el-icon-time'"
            :clear-icon="(item.attrs && item.attrs['clear-icon']) || 'el-icon-circle-close'"
            @change="formHandleEmit(item,'change')"
            @blur="formHandleEmit(item,'blur')"
            @focus="formHandleEmit(item,'focus')"
            >
          </el-time-picker>
          <div class="el-form-item__content aos-form-input-text" v-else>
            <div :title="copyData[item.prop]">{{copyData[item.prop]}}</div>
          </div>
        </template>
        <template v-if="item.type == 'time-select'">
          <el-time-select
            :ref="item.prop + '-ref'"
            v-model="copyData[item.prop]"
            :title="copyData[item.prop]"
            v-if="edit"
            :readonly="(item.attrs && item.attrs.readonly) || false"
            :disabled="(item.attrs && item.attrs.disabled) || false"
            :editable="(item.attrs && item.attrs.editable) || true"
            :clearable="!item.attrs || (item.attrs && item.attrs.clearable !== false)"
            :size="(item.attrs && item.attrs.size) || 'small'"
            :placeholder="(item.attrs && item.attrs.placeholder) || '请选择时间'"
            :start-placeholder="(item.attrs && item.attrs['start-placeholder']) || '开始时间'"
            :end-placeholder="(item.attrs && item.attrs['end-placeholder']) || '结束时间'"
            :align="(item.attrs && item.attrs.align) || 'left'"
            :picker-options="(item.attrs && item.attrs['picker-options']) || {start: '08:00',step: '00:15',end: '18:30'}"
            :range-separator="(item.attrs && item.attrs['range-separator']) || '-'"
            :prefix-icon="(item.attrs && item.attrs['prefix-icon']) || 'el-icon-time'"
            :clear-icon="(item.attrs && item.attrs['clear-icon']) || 'el-icon-circle-close'"
            @change="formHandleEmit(item,'change')"
            @blur="formHandleEmit(item,'blur')"
            @focus="formHandleEmit(item,'focus')"
            >
          </el-time-select>
          <div class="el-form-item__content aos-form-input-text" v-else>
            <div :title="copyData[item.prop]">{{copyData[item.prop]}}</div>
          </div>
        </template>
        <template v-if="item.type == 'date-picker'">
          <el-date-picker
            :ref="item.prop + '-ref'"
            v-model="copyData[item.prop]"
            :title="copyData[item.prop]"
            v-if="edit"
            :readonly="(item.attrs && item.attrs.readonly) || false"
            :disabled="(item.attrs && item.attrs.disabled) || false"
            :editable="(item.attrs && item.attrs.editable) || true"
            :clearable="!item.attrs || (item.attrs && item.attrs.clearable !== false)"
            :size="(item.attrs && item.attrs.size) || 'small'"
            :placeholder="(item.attrs && item.attrs.placeholder) || '请选择日期'"
            :start-placeholder="(item.attrs && item.attrs['start-placeholder']) ||'开始日期'"
            :end-placeholder="(item.attrs && item.attrs['end-placeholder']) || '结束日期'"
            :type="(item.attrs && item.attrs.type) || 'date'"
            :format="(item.attrs && item.attrs.format) || 'yyyy-MM-dd'"
            :align="(item.attrs && item.attrs.align) || 'left'"
            :range-separator="(item.attrs && item.attrs['range-separator']) || '-'"
            :picker-options="(item.attrs && item.attrs['picker-options'])"
            :value-format="((item) => {
              var valueFormat = item.attrs && item.attrs['value-format']
              if (valueFormat) {
                if (valueFormat === 'date') {
                  return ''
                } else {
                  return valueFormat
                }
              } else {
                return 'yyyy-MM-dd'
              }
            })(item)"
            :unlink-panels="(item.attrs && item.attrs['unlink-panels']) || false"
            :validate-event="(item.attrs && item.attrs['validate-event']) || true"
            :prefix-icon="(item.attrs && item.attrs['prefix-icon']) || 'el-icon-date'"
            :clear-icon="(item.attrs && item.attrs['clear-icon']) || 'el-icon-circle-close'"
            @change="formHandleEmit(item,'change')"
            @blur="formHandleEmit(item,'blur')"
            @focus="formHandleEmit(item,'focus')"
            >
          </el-date-picker>
          <div class="el-form-item__content aos-form-input-text" v-else>
            <div :title="copyData[item.prop]">{{formatDatePickerValue(copyData[item.prop],item)}}</div>
          </div>
        </template>
        <template v-if="item.type == 'switch'">
          <el-switch
            :ref="item.prop + '-ref'"
            v-model="copyData[item.prop]"
            :title="copyData[item.prop]"
            v-if="edit"
            :disabled="(item.attrs && item.attrs.disabled) || false"
            :width="(item.attrs && item.attrs.width) || 40"
            :active-text="(item.attrs && item.attrs['active-text']) || ''"
            :inactive-text="(item.attrs && item.attrs['inactive-text']) || ''"
            :active-value="(item.attrs && item.attrs['active-value']) || true"
            :inactive-value="(item.attrs && (item.attrs['inactive-value'] || item.attrs['inactive-value'] === 0)) ? item.attrs['inactive-value'] : false"
            :active-color="(item.attrs && item.attrs['active-color']) || '#409EFF'"
            :inactive-color="(item.attrs && item.attrs['inactive-color']) || '#C0CCDA'"
            :name="(item.attrs && item.attrs.name) || item.prop"
            :validate-event	="(item.attrs && item.attrs['validate-event']) || true"
            @change="formHandleEmit(item,'change')"
            >
          </el-switch>
          <div class="el-form-item__content" v-else>
            <el-switch
            v-model="copyData[item.prop]"
            :title="copyData[item.prop]"
            :disabled="true"
            :width="(item.attrs && item.attrs.width) || 40"
            :active-text="(item.attrs && item.attrs['active-text']) || ''"
            :inactive-text="(item.attrs && item.attrs['inactive-text']) || ''"
            :active-value="(item.attrs && item.attrs['active-value']) || true"
            :inactive-value="(item.attrs && (item.attrs['inactive-value'] || item.attrs['inactive-value'] === 0)) ? item.attrs['inactive-value'] : false"
            :active-color="(item.attrs && item.attrs['active-color']) || '#409EFF'"
            :inactive-color="(item.attrs && item.attrs['inactive-color']) || '#C0CCDA'"
            :name="(item.attrs && item.attrs.name) || item.prop"
            >
          </el-switch>
          </div>
        </template>
        <template v-if="item.type == 'radio'">
          <el-radio-group
            :ref="item.prop + '-ref'"
            v-model="copyData[item.prop]"
            :title="copyData[item.prop]"
            v-if="edit"
            :disabled="(item.attrs && item.attrs.disabled) || false"
            @change="formHandleEmit(item,'change')"
            >
            <el-radio v-for="option in item.option" :key="option.label" :label="option.label">{{option.label}}</el-radio>
          </el-radio-group>
          <div class="el-form-item__content aos-form-input-text" v-else>
            <div :title="copyData[item.prop]">{{copyData[item.prop]}}</div>
          </div>
        </template>
        <template v-if="item.type == 'color-picker'">
          <el-color-picker
            :ref="item.prop + '-ref'"
            v-model="copyData[item.prop]"
            :title="copyData[item.prop]"
            v-if="edit"
            :disabled="(item.attrs && item.attrs.disabled) || false"
            :size="(item.attrs && item.attrs.size) || 'small'"
            :show-alpha="(item.attrs && item.attrs['show-alpha']) || false"
            :color-format="(item.attrs && item.attrs['color-format']) || 'hex'"
            :predefine="(item.attrs && item.attrs.predefine) || null"
            @change="formHandleEmit(item,'change')"
            @active-change="formHandleEmit(item,'active-change')"
            >
          </el-color-picker>
          <div class="el-form-item__content aos-form-input-text" v-else>
            <div :title="copyData[item.prop]" :style="'background-color:'+copyData[item.prop]">{{copyData[item.prop]}}</div>
          </div>
        </template>
        <template v-if="item.type == 'ref'">
          <aos-ref
            :ref="item.prop + '-ref'"
            :editable="edit"
            :value="copyData[item.prop] || ''"
            :refCode="item.attrs.refCode"
            :queryParams="item.attrs.queryParams"
            :filters="item.attrs.filters"
            :debounce="item.attrs.debounce || 300"
            :placeholder="item.attrs.placeholder || '请输入'"
            :disabled="item.attrs.disabled || false"
            :firstDefault="item.attrs.firstDefault || false"
            :multiple="item.attrs.multiple || false"
            :multipleLimit="item.attrs.multipleLimit || 0"
            :placement="item.attrs.placement || 'bottom-start'"
            :appendIcon="item.attrs.appendIcon || false"
            :show-type="item.attrs && item.attrs.showType"
            @options-empty="function(isEmpty) {handleRefEmit(isEmpty,item,'options-empty')}"
            @change="function(data, emitFullData){handleRefEmit(data,item,'change', emitFullData)}"
            @clear="function(data){handleRefEmit(data,item,'clear')}"
            @blur="function(data){handleRefEmit(data,item,'blur')}"
            @focus="function(data){handleRefEmit(data,item,'focus')}"
            @visible-change="function(data){handleRefEmit(data,item,'visible-change')}"
            @remove-tag="function(data){handleRefEmit(data,item,'remove-tag')}"
            @plus-click="function(data){handleRefEmit(data,item,'plus-click')}"
            >
          </aos-ref>
        </template>
        <template v-if="item.type == 'ref-lease'">
          <aos-ref-lease
            :value="copyData[item.prop]"
            :ref="item.prop + '-ref'"
            :editable="edit"
            :baseUrl="item.attrs.baseUrl"
            :refUrl="item.attrs.refUrl"
            :field="item.attrs.field"
            :multiple="item.attrs.multiple"
            :collapseTags="item.attrs.collapseTags"
            :debounce="item.attrs.debounce || 300"
            :placeholder="item.attrs.placeholder || '选择'"
            :disabled="item.attrs.disabled || false"
            :placement="item.attrs.placement || 'bottom-start'"
            :queryParams="item.attrs.queryParams"
            @select="function(data){handleRefLeaseEmit(data,item,'select',index)}"
            @visible-change="function (data) {handleRefLeaseEmit(data,item,'visible-change',index)}"
            @remove-tag="function (tag) {handleRefLeaseEmit(data,item,'remove-tag',index)}"
            @clear="function (data) {handleRefLeaseEmit(data,item,'clear',index)}"
            @blur="function (data) {handleRefLeaseEmit(data,item,'blur',index)}"
            @focus="function (data) {handleRefLeaseEmit(data,item,'focus',index)}"
            >
          </aos-ref-lease>
        </template>
        <template v-if="item.type == 'defdoc'">
          <aos-defdoc
            :ref="item.prop + '-ref'"
            :editable="edit"
            :value="copyData[item.prop] || ''"
            :defCode="item.attrs.defCode"
            :tag="item.attrs.tag || ''"
            :multiple="item.attrs.multiple || false"
            :debounce="item.attrs.debounce || 300"
            :firstDefault="item.attrs.firstDefault || false"
            :collapseTags="item.attrs.collapseTags || false"
            :placeholder="item.attrs.placeholder || '请选择'"
            :disabled="item.attrs.disabled || false"
            :orm-code="item.attrs.ormCode"
            :no-def-code="item.attrs.noDefCode"
            :orm-name="item.attrs.ormName"
            :orm-status="item.attrs.ormStatus"
            :orm-data="item.attrs.ormData"
            :customerUrl="item.attrs.customerUrl"
            :show-type="item.attrs && item.attrs.showType"
            :outer="item.attrs && item.attrs.outer"
            :outer-options="item.attrs && item.attrs.outerOptions"
            @change="function(data, emitFullData){handleDefdocEmit(data,item,'change',emitFullData)}"
            @visible-change="function(data){handleDefdocEmit(data,item,'visible-change')}"
            @remove-tag="function(data){handleDefdocEmit(data,item,'remove-tag')}"
            @clear="function(data){handleDefdocEmit(data,item,'clear')}"
            @blur="function(data){handleDefdocEmit(data,item,'blur')}"
            @focus="function(data){handleDefdocEmit(data,item,'focus')}"
            >
          </aos-defdoc>
        </template>
        <template v-if="item.type == 'remote-select'">
          <aos-select
            :ref="item.prop + '-ref'"
            :editable="edit"
            :value="copyData[item.prop] || ''"
            :url="item.attrs.url"
            :multiple="item.attrs.multiple || false"
            :debounce="item.attrs.debounce || 300"
            :firstDefault="item.attrs.firstDefault || false"
            :collapseTags="item.attrs.collapseTags || false"
            :placeholder="item.attrs.placeholder || '请选择'"
            :disabled="item.attrs.disabled || false"
            @change="function(data){handleDefdocEmit(data,item,'change')}"
            @visible-change="function(data){handleDefdocEmit(data,item,'visible-change')}"
            @remove-tag="function(data){handleDefdocEmit(data,item,'remove-tag')}"
            @clear="function(data){handleDefdocEmit(data,item,'clear')}"
            @blur="function(data){handleDefdocEmit(data,item,'blur')}"
            @focus="function(data){handleDefdocEmit(data,item,'focus')}"
            >
          </aos-select>
        </template>
         <template v-if="item.type == 'defdoc-lease'">
          <aos-defdoc-lease
            :value="copyData[item.prop]"
            :ref="item.prop + '-defdoc-lease'"
            :editable="edit"
            :field="item.prop"
            :baseUrl="item.attrs.baseUrl"
            :defCode="item.attrs.defCode"
            :debounce="item.attrs.debounce || 300"
            :placeholder="item.attrs.placeholder || '请选择'"
            :disabled="item.attrs.disabled || false"
            @change="function(data){handleDefdocEmit(data,item,'change')}"
            @visible-change="function(data){handleDefdocEmit(data,item,'visible-change')}"
            @remove-tag="function(data){handleDefdocEmit(data,item,'remove-tag')}"
            @clear="function(data){handleDefdocEmit(data,item,'clear')}"
            @blur="function(data){handleDefdocEmit(data,item,'blur')}"
            @focus="function(data){handleDefdocEmit(data,item,'focus')}"
            >
          </aos-defdoc-lease>
        </template>
        <template v-if="item.type == 'rule-defdoc'">
          <aos-rule-defdoc
            :ref="item.prop + '-rule-ref'"
            :editable="edit"
            :value="copyData[item.prop] || ''"
            :field="item.prop"
            :defCode="item.attrs.defCode"
            :multiple="item.attrs.multiple || false"
            :debounce="item.attrs.debounce || 300"
            :firstDefault="item.attrs.firstDefault || false"
            :collapseTags="item.attrs.collapseTags || false"
            :placeholder="item.attrs.placeholder || '请选择'"
            :disabled="item.attrs.disabled || false"
            @change="function(data){handleDefdocEmit(data,item,'change')}"
            @visible-change="function(data){handleDefdocEmit(data,item,'visible-change')}"
            @remove-tag="function(data){handleDefdocEmit(data,item,'remove-tag')}"
            @clear="function(data){handleDefdocEmit(data,item,'clear')}"
            @blur="function(data){handleDefdocEmit(data,item,'blur')}"
            @focus="function(data){handleDefdocEmit(data,item,'focus')}"
            >
          </aos-rule-defdoc>
        </template>
        <template v-if="item.type == 'money'">
          <aos-money
            :ref="item.prop + '-ref'"
            :editable="edit"
            :value="copyData[item.prop]"
            :minlength="(item.attrs && item.attrs.minlength) || 0"
            :maxlength="(item.attrs && item.attrs.maxlength) || 10000"
            :placeholder="(item.attrs && item.attrs.placeholder) || '请在此输入'"
            :clearable="!item.attrs || (item.attrs && item.attrs.clearable !== false)"
            :size="(item.attrs && item.attrs.size) || 'small'"
            :disabled="(item.attrs && item.attrs.disabled) || false"
            :debounce="(item.attrs && item.attrs.debounce) || 300"
            :suffixString="(item.attrs && item.attrs.suffixString) || ''"
            :icon="(item.attrs && item.attrs.icon) || ''"
            :icon-title="(item.attrs && item.attrs.iconTitle) || ''"
            :icon-active="(item.attrs && item.attrs.iconActive) || false"
            @change="function(data){handleMoneydocEmit(data,item,'change')}"
            @clear="function(data){handleMoneydocEmit(data,item,'clear')}"
            @blur="function(data){handleMoneydocEmit(data,item,'blur')}"
            @focus="function(data){handleMoneydocEmit(data,item,'focus')}"
            @icon-click="function(data, iconActive){handleMoneydocEmit(data,item,'icon-click', iconActive)}"
            >
          </aos-money>
        </template>
        <template v-if="item.type == 'markdown'">
          <aos-markdown
            :ref="item.prop + '-ref'"
            :edit="edit"
            :content="copyData[item.prop]"
            @blur="function($event,value){handleMarkdownEditorEmit($event,item,value,'blur')}"
            @focus="function($event,value){handleMarkdownEditorEmit($event,item,value,'focus')}"
            @change="function($event,value){handleMarkdownEditorEmit($event,item,value,'change')}"
            @ready="function($event,value){handleMarkdownEditorEmit($event,item,value,'ready')}">
          </aos-markdown>
        </template>
        <template v-if="item.type == 'city'">
          <aos-city
            :templateValue.sync="copyData"
            :edit="edit"
            :province="item.province" 
            :city="item.city" 
            :county="item.county"
            :separator="(item.attrs && item.attrs.separator) || '/'"
            :placehold="(item.attrs && item.attrs.placeholder) || '请选择省/市/县'"
            :disabled="(item.attrs && item.attrs.disabled) || false"
            :clearable="!item.attrs || (item.attrs && item.attrs.clearable !== false)"
            :customerUrl="item.attrs && item.attrs.customerUrl"
            :customerMethod="item.attrs && item.attrs.customerMethod"
            @change="function(value){handleCityEmit(item,value,'change')}">
          </aos-city>
        </template>
        <template v-if="item.type == 'uploader' || item.type == 'img-upload'">
          <el-upload
            :ref="item.prop + '-ref'"
            v-if="edit"
            class="aos-uploader"
            :action="item.attrs.action"
            :multiple="item.attrs.multiple || false"
            :data="item.attrs.data || {}"
            :name="item.attrs.name || 'file'"
            :limit="item.attrs.limit"
            :on-exceed="item.attrs.onExceed"
            :show-file-list="false"
            :auto-upload="item.attrs.autoUpload"
            :http-request="(typeof item.attrs.httpRequest !== 'function') ? undefined : item.attrs.httpRequest"
            drag
            :before-upload="item.attrs['before-upload']"
            :before-remove="item.attrs['before-remove']"
            :on-success="function(response,file,fileList){handleUploaderEmit(item,'on-success',response,file,fileList)}"
            :on-remove="function(file,fileList){handleUploaderEmit(item,'on-remove',file,fileList)}"
            :on-error="function(err,file,fileList){handleUploaderEmit(item,'on-error',err,file,fileList)}"
            :on-progress="function(err,file,fileList){handleUploaderEmit(item,'on-progress',err,file,fileList)}"
            :on-preview="function(file){handleUploaderEmit(item,'on-preview',file)}"
            :on-change="function(file,fileList){handleUploaderEmit(item,'on-change',file,fileList)}"
            :disabled="item.attrs.disabled || false">
            <img v-if="item.attrs.imageUrl || copyData[item.prop]" :src="item.attrs.imageUrl || copyData[item.prop]" :alt="item.attrs.imageName">
            <div v-else>
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            </div>
          </el-upload>
          <div class="aos-uploader-img" v-if="!edit">
            <img :src="item.attrs.imageUrl || copyData[item.prop]" :alt="item.attrs.imageName">
          </div>
        </template>
        <template v-if="item.type == 'upload'">
          <el-upload
            class="aos-upload"
            :ref="item.prop + '-ref'"
            :action="item.attrs.action"
            :multiple="item.attrs.multiple || false"
            :data="item.attrs.data || {}"
            :name="item.attrs.name || 'file'"
            :limit="item.attrs.limit"
            :on-exceed="item.attrs.onExceed"
            :show-file-list="item.attrs.showFileList"
            :file-list="Object.prototype.toString.call(item.attrs.fileList) !== '[object Array]' ? [] : item.attrs.fileList"
            :auto-upload="item.attrs.autoUpload"
            :http-request="(typeof item.attrs.httpRequest !== 'function') ? undefined : item.attrs.httpRequest"
            :before-upload="item.attrs['before-upload']"
            :before-remove="item.attrs['before-remove']"
            :on-success="function(response,file,fileList){handleUploaderEmit(item,'on-success',response,file,fileList)}"
            :on-remove="function(file,fileList){handleUploaderEmit(item,'on-remove',file,fileList)}"
            :on-error="function(err,file,fileList){handleUploaderEmit(item,'on-error',err,file,fileList)}"
            :on-progress="function(err,file,fileList){handleUploaderEmit(item,'on-progress',err,file,fileList)}"
            :on-preview="function(file){handleUploaderEmit(item,'on-preview',file)}"
            :on-change="function(file,fileList){handleUploaderEmit(item,'on-change',file,fileList)}"
            :disabled="!edit">
            <el-button size="small" type="primary" v-if="edit">点击上传</el-button>
          </el-upload>
        </template>
        <template v-if="item.type == 'upload-view'">
          <aos-upload
            :ref="item.prop + '-ref'"
            :action="item.attrs.action" 
            :data="item.attrs.data"
            :multiple="item.attrs.multiple || false" 
            :name="item.attrs.name || 'file'"
            :limit="item.attrs.limit" 
            :on-exceed="item.attrs.onExceed" 
            :show-file-list="true"
            :file-list="Object.prototype.toString.call(item.attrs.fileList) !== '[object Array]' ? [] : item.attrs.fileList"
            :edit="edit"
            :auto-upload="item.attrs.autoUpload"
            :http-request="(typeof item.attrs.httpRequest !== 'function') ? undefined : item.attrs.httpRequest"
            :before-upload="item.attrs['before-upload']"
            :before-remove="item.attrs['before-remove']"
            :on-success="function (response, file, fileViewList) { handleUploaderEmit(item, 'on-success', response, file, fileViewList) }"
            :on-remove="function (file, fileViewList) { handleUploaderEmit(item, 'on-remove', file, fileViewList) }"
            :on-error="function (err, file, fileViewList) { handleUploaderEmit(item, 'on-error', err, file, fileViewList) }"
            :on-progress="function (err, file, fileViewList) { handleUploaderEmit(item, 'on-progress', err, file, fileViewList) }"
            :on-change="function (file, fileViewList) { handleUploaderEmit(item, 'on-change', file, fileViewList) }"
            :disabled="item.attrs.disabled || false"
          >
          </aos-upload>
        </template>
        <template v-if="item.type == 'image'">
          <aos-image
            :imageId="item.prop + '_' + item.attrs.imageId"
            :src="copyData[item.prop]">
          </aos-image>
        </template>
        <template v-if="item.type == 'input-number'">
          <aos-input-number
            :ref="item.prop + '-ref'"
            :edit="edit"
            :title="copyData[item.prop]"
            :value="copyData[item.prop]"
            :min="(item.attrs && (item.attrs.min || item.attrs.min === 0)) ? item.attrs.min : -Infinity"
            :max="(item.attrs && (item.attrs.max || item.attrs.max === 0)) ? item.attrs.max : Infinity"
            :style="{width: (item.attrs && item.attrs.width) || ''}"
            :step="(item.attrs && (item.attrs.step)) || 1"
            :step-strictly="(item.attrs && item.attrs.stepStrictly) || false"
            :precision="(item.attrs && item.attrs.precision)"
            :controls="(item.attrs && item.attrs.controls) || true"
            :controls-position="(item.attrs && item.attrs.controlsPosition) || 'right'"
            :name="(item.attrs && item.attrs.name)"
            :placeholder="(item.attrs && item.attrs.placeholder) || '请在此输入'"
            :disabled="(item.attrs && item.attrs.disabled) || false"
            :autosize="(item.attrs && item.attrs.autosize) || false"
            @blur="function (event) { handleInputNumberEmit(item, 'blur', event) }"
            @change="function (currentValue, oldValue) { handleInputNumberEmit(item,'change',currentValue, oldValue,) }"
            @focus="function (event) { handleInputNumberEmit(item, 'focus', event) }"
          ></aos-input-number>
        </template>
        <template v-if="item.type == 'ocr'">
          <aos-ocr
            :ref="item.prop + '-ref'"
            :edit="edit"
            :value="copyData[item.prop]"
            :project-id="copyData[item.attrs.projectId]"
            :ocr-type="item.attrs && item.attrs.ocrType"
            :disabled="item.attrs && item.attrs.disabled"
            @success="function (data) { handleOcr(item, 'success', data) }"
            @change="function (data) { handleOcr(item,'change',data) }"
            @error="function (data) { handleOcr(item, 'error', data) }"
          ></aos-ocr>
        </template>
        <template v-if="edit && item.description" slot="extra">
          <el-popover
            class="aos-form-item__description"
            placement="top-start"
            :title="item.label + '说明'"
            width="200"
            trigger="hover"
            :content="item.description">
            <i class="el-icon-question" slot="reference"></i>
          </el-popover>
        </template>
        <template v-if="item.showSlot">
          <slot :name="item.prop + '-slot'"></slot>
        </template>
      </el-form-item>
    </el-form>
    <div :class="{'aos-form-footer':!footerCenter,'aos-form-footer-center':footerCenter}">
      <slot name="footer"></slot>
    </div>
  </div>
</template>
<script>
import ElForm from "aos-element/packages/form";
import {addResizeListener,removeResizeListener} from 'aos-element/src/utils/resize-event.js';
import { cloneDeep, isArray } from 'lodash';
//import AosUpload from "../../aos-upload";
export default {
  name: "AosForm",
  components: { ElForm },
  props: {
    // 组件数据
    formTemplate: {
      type: Array,
      required: true
    },
    // 校验规则
    rules: {
      type: Object,
      default: function () {
        return {}
      }
    },
    // form model
    data: {
      type: Object,
      required: true
    },
    // 编辑状态
    edit: {
      type: Boolean,
      default: false
    },
    // 表单对齐方式，默认左对齐
    labelPosition: {
      type: String,
      default: "right"
    },
    labelWidth: {
      type: String,
      default: ''
    },
    express: {
      type: String
    },
    footerCenter: {
      type: Boolean,
      default: false
    },
  },
  watch: {
    data: {
      handler: function(val){
        if(!val){
          this.copyData = {};
        } else {
          this.copyData = val;
          this.initSelectNoEditLabel()
        }
      },
      immediate: true,
      deep: true
    } ,
    formTemplate: {
      handler: function(val, oldVal){
        if (val && !this.$_.isEqual(val, oldVal)) {
          this.currentFormTemplate = cloneDeep(val);
          this.copyFormTemplate = this.getCopyFormTemplate(val);
        }
      },
      immediate: true,
      deep: true
    },
    documentWidth(){
      this.resizeFormItem()
    }
    // ,
    // rules: {
    //   handler: function (val) {
    //     if (val && Object.prototype.toString.call(val) === "[object Object]") {
    //       // const copyRules = cloneDeep(val)
    //       const keys = Object.keys(val)
    //       if (keys.length > 0) {
    //         keys.forEach(item => {
    //           if (!this.formRules[item]) {
    //             this.$set(this.formRules, item, [])
    //           }
    //           if (val[item].length > 0) {
    //             val[item].forEach(ruleItem => {
    //               if (!this.$_.find(this.formRules[item], val[item][ruleItem])) {
    //                 this.formRules[item].push(val[item][ruleItem])
    //               }
    //             })
    //           } else {
    //             if (!this.$_.find(this.formRules[item], val[item])) {
    //               this.formRules[item].push(val[item])
    //             }
    //           }
    //         })
    //       }
    //     }
    //   },
    //   deep: true
    // }
  },
  data() {
    let idCard = (rule,value,callback) => {
      let cityCodeList = ["11", "12", "13", "14", "15", "21", "22","23", "31", "32", "33", "34", "35", "36", "37", "41", "42", "43","44", "45", "46", "50", "51", "52", "53", "54", "61", "62", "63","64", "65", "71", "81", "82", "91" ];
      let reg = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9X]$/;
      let idCardLength = 0;
      if(!value){
        callback();
      } else {
        idCardLength = value.length;
      }
      if(idCardLength === 15){
        if(!firstIdCard(value)){
          callback(new Error("身份证校验错误"));
        }
      } else if(idCardLength === 18){
        if(!secondIdCard(value)){
          callback(new Error("身份证校验错误"));
        }
      }else {
        callback(new Error("身份证位数错误"));
      }
      function firstIdCard(idCard){
        let reg = /^[1-9]\d{7}((0[1-9])|(1[0-2]))((0[1-9])|([1-2][0-9])|(3[0-1]))\d{3}$/;
        if(reg.test(idCard)){
          return true;
        }
        return false;
      };
      function secondIdCard(idCard){
        let cityCode = idCard.substring(0,2);
        let birthDate = idCard.substring(6,14);
        if(!reg.test(value)){
          // callback(new Error("身份证校验错误"));
          return false;
        }
        if(!(cityCodeList.indexOf(cityCode) >= 0)){
          // callback(new Error("身份证校验错误"));
          return false;
        }
        if(!checkDate(birthDate)){
          // callback(new Error("身份证校验错误"));
          return false;
        }
        if(!checkCode(idCard)){
          // callback(new Error("身份证校验错误"));
          return false;
        }
        return true;
      };
      function checkDate(value) {
        let reg = /^(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)$/;
        if(reg.test(value)){
          let year = value.substring(0, 4);
          let month = value.substring(4, 6);
          let date = value.substring(6, 8);
          let date2 = new Date(year + '-' + month + '-' + date);
          if (date2 && date2.getMonth() === (parseInt(month, 0) - 1)) {
            return true;
          }
        }
        return false;
      };
      function checkCode(idCard){
        let factor = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ];
        let parity = [ 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 ];
        let code = idCard.substring(17);
        let sum = 0;
        for(let i=0;i<17;i++) {
            sum += idCard[i]*factor[i];
        }
        /*eslint-disable*/
        if (parity[sum % 11] == code.toUpperCase()) {
          return true;
        }
        return false;
      }
      callback();
    };
    let email = (rule,value,callback) => {
      let reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+(\.([a-zA-Z]{2,6}))+$/;
      if(!value){
        callback();
      } else if(!reg.test(value)){
        callback(new Error('邮箱格式错误'))
      } else {
        callback()
      }
    };
    let cellPhone = (rule,value,callback) => {
      let reg = /^[1][3456789][0-9]{9}$/;
      if(!value){
        callback();
      } else if(!reg.test(value)){
        callback(new Error('手机格式错误'))
      } else {
        callback()
      }
    };
    let phoneNoRequired = (rule,value,callback) => {
      let phone = /^(([0\+]\d{2,3}-)?(0\d{2,3})-)?(\d{7,8})(-(\d{3,}))?$/;
      let cellPhone = /^[1][3456789][0-9]{9}$/;
      if(!value){
        callback();
      } else if(!phone.test(value) && !cellPhone.test(value)){
        callback(new Error('电话或手机格式错误'))
      } else {
        callback();
      }
    };
    let phone = (rule,value,callback) => {
      let phone = /^(([0\+]\d{2,3}-)?(0\d{2,3})-)?(\d{7,8})(-(\d{3,}))?$/;
      let cellPhone = /^[1][3456789][0-9]{9}$/;
      if(!value) {
        callback();
      } else if(!phone.test(value) && !cellPhone.test(value)){
        callback(new Error('电话或手机格式错误'))
      } else {
        callback();
      }
    };
    let numberType = (rule,value,callback) => {
      let numberReg = /^\-?[0-9]*$/;
      if(!value) {
        callback();
      } else if(!numberReg.test(value)){
        callback(new Error('请输入数字类型'));
      } else {
        callback();
      }
    };
    let notNumber = (rule,value,callback) => {
      let numberReg = /^[0-9]*$/;
      if(!value && value !== 0) {
        callback();
      } else if(numberReg.test(value)){
        callback(new Error('请输入非数字类型'));
      } else {
        callback();
      }
    };
    let notZero = (rule,value,callback) => {
      const numberValue = parseFloat(value)
      if(numberValue === 0){
        callback(new Error('值不能为0'));
      } else {
        callback();
      }
    }
    let numberDecimalType = (rule,value,callback) => {
      let numberReg = /^\-?[0-9\.]*$/;
      if(value){
        if(typeof value === 'number'){
          value += ''
        }
        if(!numberReg.test(value)){
          callback(new Error('请输入正确的数字类型'));
        } else if(value.indexOf('.') === 0){
          callback(new Error('请输入正确的数字类型'));
        } else if(value.split('.').length > 2){
          callback(new Error('请输入正确的数字类型'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    let nameType = (rule,value,callback) => {
      let numberReg = /^[\u4e00-\u9fa5\·]+$/;
      if(!numberReg.test(value)){
        callback(new Error('请输入正确的姓名'));
      }else if(value.substring(0,1) === '·' || value.substring(value.length - 1) === '·'){
        callback(new Error('请输入正确的姓名'));
      } else if(value.length > 20){
        callback(new Error('姓名长度不能大于20个字符'));
      } else {
        callback();
      }
    };
    let vinType = (rule,value,callback) => {
      if(value.length !== 17){
        callback(new Error("车架号位数错误"))
      } else if(value.indexOf('I') > -1 || value.indexOf('O') > -1 || value.indexOf('Q') > -1){
        callback(new Error("车架号校验错误"))
      } else if(!checkCode(value)){
        callback(new Error("车架号校验错误"))
      } else {
        callback()
      }
      function checkCode(value){
        let factor = ['8','7','6','5','4','3','2','10','0','9','8','7','6','5','4','3','2'];
        let vinMap = {
          '0': 0,
          '1': 1,
          '2': 2,
          '3': 3,
          '4': 4,
          '5': 5,
          '6': 6,
          '7': 7,
          '8': 8,
          '9': 9,
          'A': 1,
          'B': 2,
          'C': 3,
          'D': 4,
          'E': 5,
          'F': 6,
          'G': 7,
          'H': 8,
          'J': 1,
          'K': 2,
          'L': 3,
          'M': 4,
          'N': 5,
          'P': 7,
          'R': 9,
          'S': 2,
          'T': 3,
          'U': 4,
          'V': 5,
          'W': 6,
          'X': 7,
          'Y': 8,
          'Z': 9
        };
        let valueList = [];
        let totalNumber = 0;
        let checkCode;
        if(value){
          valueList = value.split('');
        }
        valueList.forEach((item,index) => {
          totalNumber += vinMap[item] * factor[index]
        });
        checkCode = totalNumber%11;
        if(checkCode === 10){
          checkCode = 'X'
        } else {
          checkCode += '';
        }
        if(checkCode === valueList[8]){
          return true;
        } else {
          return false;
        }
      }
    };
    let businessLicence = (rule,value,callback) => {
      let reg = /[IOZSV]/;
      if(typeof value === 'number'){
        value += '';
      }
      if(value.length !== 15 && value.length !== 18){
        callback(new Error('营业执照号码位数错误'))
      } else if(reg.test(value)){
        callback(new Error('营业执照号码错误'))
      } else {
        if(value.length === 15){
          let regNum = /^[0-9A-Z]{15}$/;
          if(!regNum.test(value)){
            callback(new Error('营业执照号码错误'))
          } else if(!check15(value)){
            callback(new Error('营业执照号码错误'))
          } else {
            callback();
          }
        } else if(value.length === 18){
          let regNum = /^[0-9A-Z]{18}$/;
          if(!regNum.test(value)){
            callback(new Error('营业执照号码错误'))
          } else if(!check18(value)){
            callback(new Error('营业执照号码错误'))
          } else {
            callback();
          }
        }
      }
      function check15(value){
       let valList = value.substring(0,14).split('');
       let result = 10;
       let tmp = void 0;
       valList.forEach((item,index) => {

          item = parseInt(item, 0);
          tmp = (item + result) % 10;
          if (tmp === 0) {
            tmp = 10;
          }
          result = (tmp * 2) % 11;
        });
        if (!((result + parseInt(value.substring(14), 0)) % 10 === 1)) {
          return false;
        } else {
          return true;
        }
      };
      function check18(value){
    let parity = [1,3,9,27,19,26,16,17,20,29,25,13,8,24,10,30,28];
    let resultList = [0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','T','U','W','X','Y'];
    var keyMap = {
      A: 10,
      B: 11,
      C: 12,
      D: 13,
      E: 14,
      F: 15,
      G: 16,
      H: 17,
      J: 18,
      K: 19,
      L: 20,
      M: 21,
      N: 22,
      P: 23,
      Q: 24,
      R: 25,
      T: 26,
      U: 27,
      W: 28,
      X: 29,
      Y: 30
    }
    if(typeof value === 'string'){
      let valList = value.substring(0,17).split('');
      let total = 0;
      let result = 0;
      valList.forEach((item,index) => {
        if (!/[A-Z]/.test(item)) {
          total += item*parity[index];
        } else {
          total += keyMap[item]*parity[index];
        }
      });
      result = 31 - total % 31;
      if (result === 31) {
        result = 0
      }
      /*eslint-disable*/
      if (value.substring(17) == resultList[result]) {
        return true;
      } else {
        return false;
      }
    } else {
      return false
    }
  };
    };
    let version = (rule, value, callback) => {
      const reg =  /^\d{1,3}(\.\d{1,3}){3}$/
      if (!reg.test(value)) {
        callback(new Error('请输入正确的版本号码'));
      } else {
        callback()
      }
    }
    let postcode = (rule, value, callback) => {
      const reg =  /^\[0-9]{6}$/
      if (!reg.test(value)) {
        callback(new Error('请输入正确的邮政编码'));
      } else {
        callback()
      }
    }
    return {
      formRules: {},
      expressList: [],
      idCard: idCard,
      postcode: postcode,
      email: email,
      cellPhone: cellPhone,
      phone: phone,
      numberType: numberType,
      nameType: nameType,
      phoneNoRequired: phoneNoRequired,
      vinType: vinType,
      numberDecimalType: numberDecimalType,
      notZero,
      notNumber,
      businessLicence: businessLicence,
      version: version,
      copyFormTemplate: '',
      copyData: '',
      currentFormTemplate:'',
      formItemSm: false,
      formItemMd: false,
      formItemXl: false,
      formItemLg: false,
      formItemHLg: false,
      documentWidth: document.body.clientWidth,
      currentData: '',
      ocrObject: {
        'idCardFront': 'id-card-front',
        'idCardBack': 'id-card-back',
        'bank': 'bank-card',
        'businessLicense': 'business-license',
        'invoice': 'vatInvoice',
        'drivingLicenseLeft': 'vehicleLicense-front',
        'drivingLicenseRight': 'vehicleLicense-back',
        vehicleCertification: 'vehicleCertification'
      },
      selectObject: {},
      selectNoEditLabelObject: {}
    };
  },
  mounted() {
    if(Object.prototype.toString.call(this.data) === '[object object]'){
      this.currentData = cloneDeep(this.data);
    }
    this.resizeFormItem();
    addResizeListener(this.$refs.formContainer,this.resizeFormItem);
  },
  beforeDestroy(){
    removeResizeListener(this.$refs.formContainer,this.resizeFormItem);
  },
  methods: {
    initSelectNoEditLabel () {
      this.getSelectObjectFromTemplate()
      const keyList = Object.keys(this.selectObject)
      if (keyList.length > 0 && this.copyData && Object.keys(this.copyData).length > 0) {
        keyList.forEach(key => {
          if (![NaN, null, undefined, ''].includes(this.copyData[key])) {
            const value = this.copyData[key]
            if (Array.isArray(value) && value.length > 0) {
              const labelList = []
              value.forEach(valueItem => {
                labelList.push(this.selectObject[key][valueItem])
              })
              this.$set(this.selectNoEditLabelObject, key, labelList.join(','))
            } else {
              if (typeof value === 'string' && value.includes(',')) {
                const valueList = value.split(',')
                const labelList = []
                valueList.forEach(valueItem => {
                  labelList.push(this.selectObject[key][valueItem])
                })
                this.$set(this.selectNoEditLabelObject, key, labelList.join(','))
              } else {
                this.$set(this.selectNoEditLabelObject, key, this.selectObject[key][value])
              }
            }
          }
        })
      }
    },
    getSelectObjectFromTemplate () {
      if (this.formTemplate && this.formTemplate.length > 0) {
        this.formTemplate.forEach(item => {
          if (item.type === 'select' && Array.isArray(item.option) && item.option.length > 0) {
            this.selectObject[item.prop] = {}
            item.option.forEach(optionItem => {
              this.selectObject[item.prop][optionItem.value] = optionItem.label
            })
          }
        })
      }
    },
    formatDatePickerValue (value, item) {
      if (!value) return ''
      let valueFormat = item.attrs && item.attrs['value-format']
      if (!valueFormat) {
        valueFormat = 'yyyy-MM-dd hh:mm:ss'
      }
      if (item.attrs && item.attrs.type === 'date') {
        valueFormat = 'yyyy-MM-dd'
      }
      return this.$time.formatTime(value, valueFormat)
    },
    formatDate (date) {
      let formatDate = date
      if (date === '长期' || date === '无' || date === '长期') {
        formatDate = '2099-12-31'
      } else {
        formatDate = date.substring(0,4) + '-' + date.substring(4,6) + '-' + date.substring(6)
      }
      return formatDate
    },
    formatBusinessLicenseDate (date) {
      let formatDate = date
      if (date === '长期' || date === '无' || date === '长期') {
        formatDate = '2099-12-31'
      } else {
        formatDate = date.substring(0,4) + '-' + date.substring(5,7) + '-' + date.substring(8,10)
      }
      return formatDate
    },
    handleInlineOcr (item, type, response, file, fileList) {
      const data = response.data
      if (!response) {
        this.$message({
          type: 'error',
          message: this.ocrObject[item.attrs.ocrType]+'OCR识别出错'
        })
      }
      if (item.attrs.ocrType === 'idCardFront') {
        data.birth = this.formatDate(data.birth)
      }
      if (item.attrs.ocrType === 'idCardBack') {
        data.expiryDate = this.formatDate(data.expiryDate)
        data.issuingDate = this.formatDate(data.issuingDate)
      }
      if (item.attrs.ocrType === 'bank') {
        data.bankCardNumber = data.bankCardNumber.split(' ').join('')
      }
      if (item.attrs.ocrType === 'businessLicense') {
        data.approvalDate = this.formatBusinessLicenseDate(data.approvalDate)
        data.dateOfEstablishment = this.formatBusinessLicenseDate(data.dateOfEstablishment)
        data.inDate = this.formatBusinessLicenseDate(data.inDate)
        data.registeredCapital = data.registeredCapital.slice(0, -2)
      }
      if (item.methods && item.methods[type]) {
        this.$emit(
          "form-" + item.prop + "-ocr-" + item.methods[type],response,
          cloneDeep(this.copyData),
          item.prop,
          file,
          fileList
        );
      }
    },
    formHandleEmit(item, type) {
      if (item.methods && item.methods[type]) {
        this.$emit(
          "form-" + item.prop + "-" + item.methods[type],
          cloneDeep(this.copyData),
          item.prop
        );
      } else {
        }
      if (item.type === 'select' && ['change', 'remove-tag', 'clear'].includes(type)) {
        this.initSelectNoEditLabel()
      }
      this.$emit(type, cloneDeep(this.copyData), item.prop)
    },
    /**
     * @description: 设置表单对应项的属性值
     * @param {type} prop prop属性, attes 属性, value 属性值, type 是否是列item为列,默认为attrs属性值attrsItem为attrs里面的对象属性
     * @return: 
     */
    setFormItemProp(prop,attrs,value,type){
      let length = this.copyFormTemplate.length;
      for(let i = 0;i<length;i++){
        if(this.copyFormTemplate[i].prop === prop){
          if(!type || type === 'attrs'){
            if(!this.copyFormTemplate[i].attrs){
              this.$set(this.copyFormTemplate[i],'attrs',{});
            }
            this.$set(this.copyFormTemplate[i].attrs,attrs,value);
          } else if(type === 'item'){
            this.$set(this.copyFormTemplate[i],attrs,value);
          } else if(type === 'attrsItem'){
            let key = value.key;
            let values = value.value;
            let attrsItem = value.attrsItem;
            if (this.copyFormTemplate[i].attrs && this.copyFormTemplate[i].attrs[attrsItem] && this.copyFormTemplate[i].attrs[attrsItem][key]) {
              this.copyFormTemplate[i].attrs[attrsItem][key] = values
            } else {
              this.$set(this.copyFormTemplate[i].attrs[attrsItem],key,values);
            }
          }
          break;
        }
      }
    },
    // 设置form规则
    setFormItemRules(prop,rule,type){
      let length = this.currentFormTemplate.length;
      for(let i = 0;i<length;i++){
        if(this.currentFormTemplate[i].prop === prop){
          if(type){
            if(!this.currentFormTemplate[i].rules){
              this.$set(this.currentFormTemplate[i],'rules',[]);
            }
            if(Object.prototype.toString.call(rule) === '[object Array]'){
              let addRulesIdList = [];
              let rules = this.currentFormTemplate[i].rules;
              let ruleLength = rules.length;
              rule.forEach((item) => {
                addRulesIdList.push(item.id);
              });
              if(addRulesIdList.length > 0){
                for(let j = 0;j<ruleLength;j++){
                  if(addRulesIdList.indexOf(rules.id)> -1){
                    rules.splice(j,1);
                  }
                }
              }
              this.currentFormTemplate[i].rules = this.currentFormTemplate[i].rules.concat(rule);
            } else if(Object.prototype.toString.call(rule) === '[object Object]'){
              const copyRules = cloneDeep(this.currentFormTemplate[i].rules)
              this.currentFormTemplate[i].rules = copyRules.filter(item => {
                return item.id !== rule.id
              })
              // let rules = this.currentFormTemplate[i].rules;
              // let ruleLength = rules.length;
              // for(let j = 0;j<ruleLength;j++){
              //   if(rules[j].id && rules[j].id === rule.id){
              //     rules.splice(j,1);
              //     break;
              //   }
              // }
              this.currentFormTemplate[i].rules.push(rule);
            }
          } else {
            if(this.currentFormTemplate[i].rules && this.currentFormTemplate[i].rules.length > 0){
              if(Object.prototype.toString.call(rule) === '[object Array]'){
                let removeRulesIdList = [];
                let rules = this.currentFormTemplate[i].rules;
                let ruleLength = rules.length;
                rule.forEach((item) => {
                  removeRulesIdList.push(item.id);
                });
                if(removeRulesIdList.length > 0){
                  for(let j = 0;j<ruleLength;j++){
                    if(removeRulesIdList.indexOf(rules.id)> -1){
                      rules.splice(j,1);
                    }
                  }
                }
              } else if(Object.prototype.toString.call(rule) === '[object Object]'){
                let rules = this.currentFormTemplate[i].rules;
                let ruleLength = rules.length;
                for(let j = 0;j<ruleLength;j++){
                  if(rules[j].id && rules[j].id === rule.id){
                    rules.splice(j,1);
                    break;
                  }
                }
              }
            }
          }
          break;
        }
      }
      const sourceTemplate = cloneDeep(this.copyFormTemplate)
      for (let index = 0; index < sourceTemplate.length; index++) {
        const element = sourceTemplate[index];
        if (element.prop === prop) {
          const sourceRules = element.rules ? element.rules : []
          let newSourceRules = []
          if (Array.isArray(rule)) {
            if (type) {
              newSourceRules = sourceRules.filter(sourceItem => {
                let flag = true
                if (sourceItem.id) {
                  rule.forEach(targetItem => {
                    if (targetItem.id === sourceItem.id) {}
                    flag = false
                  })
                }
                return flag
              })
              const targetRules = newSourceRules.concat(rule)
              this.$set(element, 'rules', targetRules)
            } else {
              const newRules = sourceRules.filter(sourceItem => {
                let flag = true
                if (sourceItem.id) {
                  rule.forEach(targetItem => {
                    if (targetItem.id === sourceItem.id) {}
                    flag = false
                  })
                }
                return flag
              })
              this.$set(element, 'rules', newRules)
            }
          } else if (typeof rule === 'object') {
            if (type) {
              const newSourceRules = sourceRules.filter(item => {
                return !item.id || (item.id && item.id !== rule.id)
              })
              newSourceRules.push(rule)
              this.$set(element, 'rules', newSourceRules)
            } else {
               const newRules = sourceRules.filter(item => {
                return !item.id || item.id !== rule.id
              })
              this.$set(element, 'rules', newRules)
            }
          }
          break;
        }
      }
      this.copyFormTemplate = this.getCopyFormTemplate(sourceTemplate);
    },
    /**
     * 设置字段显示隐藏
     * prop: 字段
     * value: 值
     */
    setFormItemShow(prop,value){
      if(prop && value !== null && value !== undefined && value !== ''){
        let flag = false;
        if(!value){
          let length = this.copyFormTemplate.length;
          for(let i = 0;i<length;i++){
            if(this.copyFormTemplate[i].prop === prop){
              this.copyFormTemplate[i].showItem = false
              this.copyFormTemplate.splice(i,1);
              flag = true;
              break;
            }
          }
        } else {
          const currentTemplatelength = this.currentFormTemplate.length;
          const copyTemplatelength = this.copyFormTemplate.length;
          let hasProp = false;
          for(let i = 0;i<copyTemplatelength;i++){
            if(this.copyFormTemplate[i].prop === prop){
              hasProp = true;
              flag = true
              break;
            }
          }
          if (!hasProp) {
            for(let i = 0;i<currentTemplatelength;i++){
              if(this.currentFormTemplate[i].prop === prop){
                const item = cloneDeep(this.currentFormTemplate[i])
                item.showItem = true
                this.copyFormTemplate.splice(i,0,item);
                flag = true;
                break;
              }
            }
          }
        }
        if(!flag){
          console.log("setFormItemShow方法,当前Form表单没有传入的属性:",prop)
        }
      } else {
        console.log("setFormItemShow方法,请传入prop和value")
      }
    },
    handleInputNumberEmit (item, type, data, oldValue) {
      if(type === 'change'){
        this.copyData[item.prop] = data;
      }
      if(item.methods && item.methods[type]){
        this.$emit('form-' + item.prop + '-' + item.methods[type],cloneDeep(this.copyData), item.prop, data, oldValue);
      }
      this.$emit(type, cloneDeep(this.copyData), item.prop)
    },
    /**
     * 参照选择之后触发
     * refData: 获取到的参照的数据
     * item: 当前组件数据
     * type: 当前方法
     * 返回事件: 
     */
    handleRefEmit(data,item,type,emitFullData){
      if(type === 'change'){
        this.copyData[item.prop] = data;
      }
      if(item.methods && item.methods[type]){
        this.$emit('form-' + item.prop + '-' + item.methods[type],cloneDeep(this.copyData),item.prop,data,emitFullData);
      }
        this.$emit(type, cloneDeep(this.copyData), item.prop,emitFullData)
    },

    handleRefLeaseEmit (data, item, type) {
      if(type === 'change'){
        this.copyData[item.prop] = data;
      }
      if(item.methods && item.methods[type]){
        this.$emit('form-' + item.prop + '-' + item.methods[type],cloneDeep(this.copyData),item.prop,data);
      }
    },
    // 设置倒计时停止
    handleStopCountTime(prop){
      this.$refs[prop + '-count-time-ref'][0].stopCount();
    },
    // 设置倒计时开始
    handleStartCountTime(prop){
      this.$refs[prop + '-count-time-ref'][0].startCount();
    },
    handleOcr (item, type, data) {
      if (type === 'success') {
        this.$set(this.copyData, [item.prop],data.fileId)
      }
      if(item.methods && item.methods[type]){
        this.$emit('form-' + item.prop + '-' + item.methods[type], cloneDeep(this.copyData),item.prop, data);
      }
      this.$emit(type, cloneDeep(this.copyData), item.prop, data)
    },
    /**
     * 字典事件
     */
    handleDefdocEmit(data,item,type,emitFullData){
      if(type === 'change'){
        this.copyData[item.prop] = data;
      }
      if(item.methods && item.methods[type]){
        this.$emit('form-' + item.prop + '-' + item.methods[type],cloneDeep(this.copyData),item.prop,data,emitFullData);
      }
      this.$emit(type, cloneDeep(this.copyData), item.prop,emitFullData)
    },
    // money事件
    handleMoneydocEmit(data,item,type, iconActive){
      if(type === 'change' || type === 'blur'){
        this.copyData[item.prop] = data;
      }
      if(item.methods && item.methods[type]){
        this.$emit('form-' + item.prop + '-' + item.methods[type],cloneDeep(this.copyData),item.prop,data, iconActive);
      }
      this.$emit(type, cloneDeep(this.copyData), item.prop, data, iconActive)
    },
    // markdown事件
    handleMarkdownEditorEmit(event,item,value,type){
      if(type === 'change'){
        this.copyData[item.prop] = value;
      }
      if(item.methods && item.methods[type]){
        this.$emit('form-' + item.prop + '-' + item.methods[type],cloneDeep(this.copyData),item.prop,value);
      }
      this.$emit(type, cloneDeep(this.copyData), item.prop)
    },
    handleCityEmit(item,value,type){
      if(item.methods && item.methods[type]){
        this.$emit('form-' + item.prop + '-' + item.methods[type],cloneDeep(this.copyData),item.prop,value);
      }
    },
    // 上传事件
    handleUploaderEmit(item,type,response,file,fileList){
      if(item.methods && item.methods[type]){
        if (type === 'before-upload' || type === 'on-preview') {
          this.$emit('form-' + item.prop + '-' + item.methods[type],response,cloneDeep(this.copyData))
        } else if (type === 'on-remove' || type === 'on-change' || type === 'before-remove') {
          this.$emit('form-' + item.prop + '-' + item.methods[type],response,file,cloneDeep(this.copyData))
        } else {
          this.$emit('form-' + item.prop + '-' + item.methods[type],response,file,fileList,cloneDeep(this.copyData))
        }
      }
    },
    // 解析表达式
    handleExpress(){
      if(this.expressList.length > 0){
        let newData = cloneDeep(this.copyData);
        let reg = /[A-Za-z0-9]+/;
        let expressListLength = this.expressList.length;
        let trueExpress = cloneDeep(this.expressList);
        for(let i = 0;i < expressListLength; i++){
          let codeList = this.expressList[i].split('=')[1].match(reg);
          let codeListLength = codeList.length;
          if(codeListLength > 0){
            for(let i = 0;i < expressListLength; i++){
              if(newData[codeList[i]] === '' || null || undefined){
                console.log(codeList[i]+'的值不能为：'+newData[codeList[i]]);
                trueExpress.splice(i,1);
                break;
              }
            }
          }
        }
        let trueExpressLength = trueExpress.length;
        if(trueExpressLength > 0){
          for(let i = 0;i < trueExpressLength; i++){
            let expressValue = this.trueExpress[i].split('=')[0];
            let expressPropList = this.trueExpress[i].split('=')[1].match(reg);
            let newExpress = this.trueExpress[i].split('=')[1];
            expressPropList.forEach((item) => {
              let reg = new RegExp("\b"+item+"\b","gi");
              newExpress = newExpress.replace(reg,newData[item]);
            });
            newData[expressValue] = this.$math(newExpress);
          }
        }
        this.copyData = cloneDeep(newData);
      }
    },
    getCopyFormTemplate(template){
      const copyFormTemplate = cloneDeep(template)
      this.selectObject = {}
      return copyFormTemplate.filter(item => {
        if (item.rules && item.rules instanceof Array) {
          item.rules.forEach((item) => {
            switch(item.validator){
              case 'idCard':
                item.validator = this.idCard;
                break;
              case 'postcode':
                item.validator = this.postcode;
                break;
              case 'email':
                item.validator = this.email;
                break;
              case 'phone':
                item.validator = this.phone;
                break;
              case 'cellPhone':
                item.validator = this.cellPhone;
                break;
              case 'phoneNoRequired':
                item.validator = this.phoneNoRequired;
                break;
              case 'number':
                item.validator = this.numberType;
                break;
              case 'name':
                item.validator = this.nameType;
                break;
              case 'vin':
                item.validator = this.vinType;
                break;
              case 'numberDecimalType':
                item.validator = this.numberDecimalType;
                break;
              case 'notZero':
                item.validator = this.notZero;
                break;
              case 'notNumber':
                item.validator = this.notNumber;
                break;
              case 'businessLicence':
                item.validator = this.businessLicence;
                break;
              case 'version':
                item.validator = this.version;
                break;
              default:
                break;
            }
          })
          this.formRules[item.prop] = item.rules;
        }
        if(item.expression){
          this.expressList.push(item.express);
        }
        if (item.type === 'select' && Array.isArray(item.option) && item.option.length > 0) {
          this.selectObject[item.prop] = {}
          item.option.forEach(optionItem => {
            this.selectObject[item.prop][optionItem.value] = optionItem.label
          })
          console.log('---- getCopyFormTemplate ----', this.selectObject)
        }
        return item.showItem !== false
      })
    },
    resizeFormItem(){
      let parentWidth;
      let aosMainBox = document.querySelector('.aos-main-box')
      let mainBoxOffsetWidth = aosMainBox ? aosMainBox.offsetWidth : 0;
      if(!!this.$refs.formContainer.offsetWidth){
        parentWidth = this.$refs.formContainer.offsetWidth;
      } else if (mainBoxOffsetWidth) {
        parentWidth = document.querySelector('.aos-main-box').offsetWidth;
      }
      if(parentWidth <= 760){
        this.formItemSm = true;
        this.formItemMd = false;
        this.formItemXl = false;
        this.formItemLg = false;
        this.formItemHLg = false;
      } else if(parentWidth > 760 && parentWidth <= 1200){
        this.formItemSm = false;　
        this.formItemMd = true;
        this.formItemXl = false;
        this.formItemLg = false;
        this.formItemHLg = false;
      } else if(parentWidth > 1200 && parentWidth <=1610){
        this.formItemSm = false;
        this.formItemMd = false;
        this.formItemXl = true;
        this.formItemLg = false;
        this.formItemHLg = false;
      } else if(parentWidth > 1610 && parentWidth <= 2010){
        this.formItemSm = false;
        this.formItemMd = false;
        this.formItemXl = false;
        this.formItemLg = true;
        this.formItemHLg = false;
      } else if (parentWidth > 2010) {
        this.formItemSm = false;
        this.formItemMd = false;
        this.formItemXl = false;
        this.formItemLg = false;
        this.formItemHLg = true;
      }
    }
  },
}
</script>