<template>
  <a-form-item
    v-if="
      [
        'input',
        'textarea',
        'date',
        'time',
        'number',
        'radio',
        'checkbox',
        'select',
        'rate',
        'switch',
        'slider',
        'uploadImg',
        'uploadFile',
        'user',
        'dept',
        'page',
        'serialno',
        'treeSelect',
        'cascader',
        'editor',
        'icon',
	      'fivewhy',
	      'mind',
	      'fishbone',
        'signature'
      ].includes(record.type) || (record.type === 'custom' && record.options.isModel)
    "
    v-show="canvas || !record.options.hidden"
    :class="{custom_label_wrap: config.customLabelWrap, alignCenter: config.align == 'center'}"
    :label="$locale(record.name)"
    :label-align="config.align == 'center' ? 'right' : config.align"
    :label-col="config.layout === 'horizontal' ? (record.options.custom ? record.custom.labelCol : config.labelCol) : {}"
    :wrapper-col="config.layout === 'horizontal' ? (record.options.custom ? record.custom.wrapperCol : config.wrapperCol) : {}"
    :validate-status="validateStatus"
    :help="validateHelp"
    :style="record.options.customStyle + ';' + (record.options.toTop ? 'padding-top:' + record.options.toTop + 'px' : '')"
  >
    <!-- 单行文本 -->
    <a-input
      :style="`width:${record.options.width}`"
      v-if="record.type === 'input' && (!record.options.disabled || !record.options.displayByText && !record.options.displayByHtml)"
      :disabled="record.options.disabled"
      :placeholder="$locale(record.options.placeholder)"
      :type="record.options.type"
      :readOnly="record.options.readOnly"
      v-decorator="[
        record.model, // input 的 name
        {
          initialValue: record.options.defaultValue, // 默认值
          rules: getRules // 验证规则
        }
      ]"
      @change="changeValue"
      @blur="onblur"
      @pressEnter="pressEnter"
    >
      <template v-if="record.options.beforeIcon || record.options.prefixText" #addonBefore>
        <ych-icon v-if="record.options.beforeIcon" :type="record.options.beforeIcon"/>
        <span v-else>{{ record.options.prefixText }}</span>
      </template>
      <template v-if="record.options.afterIcon || record.options.suffixText" #addonAfter>
        <ych-icon v-if="record.options.afterIcon" :type="record.options.afterIcon" @click="afterIconClick"/>
        <span v-else>{{ record.options.suffixText }}</span>
      </template>
    </a-input>
    <ych-display-text-tag
      v-else-if="record.type === 'input' && record.options.displayByText && record.options.disabled"
      v-decorator="[
        record.model, // input 的 name
        {
          initialValue: record.options.defaultValue, // 默认值
        }
      ]">
    </ych-display-text-tag>
    <ych-display-html-tag
      v-else-if="record.type === 'input' && record.options.displayByHtml && record.options.disabled"
      v-decorator="[
        record.model, // input 的 name
        {
          initialValue: record.options.defaultValue, // 默认值
        }
      ]">
    </ych-display-html-tag>
    <!-- 多行文本 -->
    <a-textarea
      :style="`width:${record.options.width}`"
      v-else-if="record.type === 'textarea' && (!record.options.disabled || !record.options.displayByText && !record.options.displayByHtml)"
      :autoSize="{
        minRows: record.options.minRows,
        maxRows: record.options.maxRows
      }"
      :disabled="record.options.disabled"
      :readOnly="record.options.readOnly"
      :placeholder="$locale(record.options.placeholder)"
      :rows="4"
      v-decorator="[
        record.model, // input 的 name
        {
          initialValue: record.options.defaultValue, // 默认值
           rules: getRules // 验证规则
        }
      ]"
      @change="changeValue"
      @blur="onblur"
    />
    <ych-display-text-tag
      v-else-if="record.type === 'textarea' && record.options.displayByText && record.options.disabled"
      v-decorator="[
        record.model, // input 的 name
        {
          initialValue: record.options.defaultValue, // 默认值
        }
      ]">
    </ych-display-text-tag>
    <ych-display-html-tag
      v-else-if="record.type === 'textarea' && record.options.displayByHtml && record.options.disabled"
      v-decorator="[
        record.model, // input 的 name
        {
          initialValue: record.options.defaultValue, // 默认值
        }
      ]">
    </ych-display-html-tag>
    <!-- 日期 -->
    <KDatePicker
      ref="comp"
      v-else-if="record.type === 'date'"
      :record="record"
      :form="form"
      v-decorator="[
        record.model, // input 的 name
        {
          initialValue: record.options.range
            ? record.options.rangeDefaultValue
            : record.options.defaultValue, // 默认值
           rules: getRules // 验证规则
        }
      ]"
      @change="changeValue"
      @blur="onblur"
    />
    <!-- 时间 -->
    <KTimePicker
      ref="comp"
      v-else-if="record.type === 'time'"
      :record="record"
      v-decorator="[
        record.model, // input 的 name
        {
          initialValue: record.options.defaultValue, // 默认值
           rules: getRules // 验证规则
        }
      ]"
      @change="changeValue"
      @blur="onblur"
    />
    <!-- 数字 -->
    <a-input-number
      v-else-if="record.type === 'number' && (!record.options.disabled || !record.options.displayByText)"
      :style="`width:${record.options.width}`"
      :min="record.options.min"
      :max="record.options.max"
      :disabled="record.options.disabled"
      :step="record.options.step"
      :precision="record.options.precision"
      :placeholder="$locale(record.options.placeholder)"
      v-decorator="[
        record.model,
        {
          initialValue: record.options.defaultValue,

        }
      ]"
      @change="changeValue"
      @blur="onblur"
      @pressEnter="pressEnter"
    />
    <ych-display-text-tag
      v-else-if="record.type === 'number' && record.options.displayByText && record.options.disabled"
      v-decorator="[
        record.model, // input 的 name
        {
          initialValue: record.options.defaultValue, // 默认值
        }
      ]">
    </ych-display-text-tag>
    <!-- 下拉框 -->
    <dict-select-tag
      ref="comp"
      type="select"
      v-else-if="record.type === 'select'"
      :style="record.options.width?`width:${record.options.width}`:''"
      :dictCode="record.options.dictOption.dictCode"
      :sqlCode = "record.options.sqlConfig ? record.options.sqlConfig.sqlCode : null"
      :sqlParameterConfig = "record.options.sqlConfig ? record.options.sqlConfig.sqlParameterConfig : null"
      :form="form"
      :http-config="record.options.httpConfig"
      :formatExpr="record.options.formatExpr"
      :options="record.options.options"
      :placeholder="$locale(record.options.placeholder)"
      :disabled="record.options.disabled"
      :readOnly="record.options.readOnly"
      :linkage="record.options.enableLinkage ? record.options.linkage : null"
      :linkageMap="linkageMap"
      :allowClear="record.options.clearable"
      :showSearch="record.options.showSearch"
      :mode="record.options.multiple ? 'multiple' : ''"
      :dictMap="dictMap"
      :elValue="elValue"
      v-decorator="[
        record.model,
        {
          initialValue: record.options.defaultValue,

        }
      ]"
      @change="changeValue"
      @blur="onblur"
    />
    <!-- 单选框 -->
    <dict-select-tag
      ref="comp"
      type="radio"
      :placeholder="$locale(record.options.placeholder)"
      v-else-if="record.type === 'radio'"
      :dictCode="record.options.dictOption.dictCode"
      :sqlCode = "record.options.sqlConfig ? record.options.sqlConfig.sqlCode : null"
      :sqlParameterConfig = "record.options.sqlConfig ? record.options.sqlConfig.sqlParameterConfig : null"
      :form="form"
      :http-config="record.options.httpConfig"
      :formatExpr="record.options.formatExpr"
      :options="record.options.options"
      :disabled="record.options.disabled"
      :readOnly="record.options.readOnly"
      :dictMap="dictMap"
      :elValue="elValue"
      v-decorator="[
        record.model,
        {
          initialValue: record.options.defaultValue,

        }
      ]"
      @change="changeValue"
      @blur="onblur"
    />
    <!-- 复选框 -->
    <dict-select-tag
      ref="comp"
      type="checkbox"
      v-else-if="record.type === 'checkbox'"
      :placeholder="$locale(record.options.placeholder)"
      :dictCode="record.options.dictOption.dictCode"
      :sqlCode = "record.options.sqlConfig ? record.options.sqlConfig.sqlCode : null"
      :sqlParameterConfig = "record.options.sqlConfig ? record.options.sqlConfig.sqlParameterConfig : null"
      :form="form"
      :http-config="record.options.httpConfig"
      :formatExpr="record.options.formatExpr"
      :options="record.options.options"
      :disabled="record.options.disabled"
      :readOnly="record.options.readOnly"
      :dictMap="dictMap"
      :elValue="elValue"
      v-decorator="[
        record.model,
        {
          initialValue: record.options.defaultValue,

        }
      ]"
      @change="changeValue"
      @blur="onblur"
    />
    <!-- 树形选择-->
    <dict-select-tag
      ref="comp"
      type="treeSelect"
      v-else-if="record.type === 'treeSelect'"
      :placeholder="$locale(record.options.placeholder)"
      :style="record.options.width?`width:${record.options.width}`:''"
      :dictCode="record.options.dictOption.dictCode"
      :sqlCode = "record.options.sqlConfig ? record.options.sqlConfig.sqlCode : null"
      :sqlParameterConfig = "record.options.sqlConfig ? record.options.sqlConfig.sqlParameterConfig : null"
      :form="form"
      :http-config="record.options.httpConfig"
      :formatExpr="record.options.formatExpr"
      :options="record.options.options"

      :disabled="record.options.disabled"
      :readOnly="record.options.readOnly"
      :linkage="record.options.enableLinkage ? record.options.linkage : null"
      :linkageMap="linkageMap"
      :show-parent="record.options.showParent"
      :treeCheckable="record.options.treeCheckable"
      :allowClear="record.options.clearable"
      :showSearch="record.options.showSearch"
      :mode="record.options.multiple ? 'multiple' : ''"
      :dictMap="dictMap"
      :elValue="elValue"
      v-decorator="[
        record.model,
        {
          initialValue: record.options.defaultValue,

        }
      ]"
      @change="changeValue"
      @blur="onblur"
    />
    <!-- 级联选择-->
    <dict-select-tag
      ref="comp"
      type="cascader"
      v-else-if="record.type === 'cascader'"
      :placeholder="$locale(record.options.placeholder)"
      :style="record.options.width?`width:${record.options.width}`:''"
      :dictCode="record.options.dictOption.dictCode"
      :sqlCode = "record.options.sqlConfig ? record.options.sqlConfig.sqlCode : null"
      :sqlParameterConfig = "record.options.sqlConfig ? record.options.sqlConfig.sqlParameterConfig : null"
      :form="form"
      :http-config="record.options.httpConfig"
      :formatExpr="record.options.formatExpr"
      :options="record.options.options"

      :disabled="record.options.disabled"
      :readOnly="record.options.readOnly"
      :linkage="record.options.enableLinkage ? record.options.linkage : null"
      :linkageMap="linkageMap"
      :treeCheckable="record.options.treeCheckable"
      :allowClear="record.options.clearable"
      :showSearch="record.options.showSearch"
      :mode="'multiple'"
      :dictMap="dictMap"
      :elValue="elValue"
      v-decorator="[
        record.model,
        {
          initialValue: record.options.defaultValue,

        }
      ]"
      @change="changeValue"
      @blur="onblur"
    />
    <!-- 评分 -->
    <a-rate
      v-else-if="record.type === 'rate'"
      :count="record.options.max"
      :disabled="record.options.disabled"
      :allowHalf="record.options.allowHalf"
      v-decorator="[
        record.model,
        {
          initialValue: record.options.defaultValue,

        }
      ]"
      @change="changeValue"
      @blur="onblur"
    />
    <!-- 开关 -->
    <a-switch
      v-else-if="record.type === 'switch'"
      :disabled="record.options.disabled"
      v-decorator="[
        record.model,
        {
          valuePropName: 'checked',
          initialValue: record.options.defaultValue,

        }
      ]"
      @change="changeValue"
      @blur="onblur"
    />
    <!-- 滑动条 -->
    <div
      v-else-if="record.type === 'slider'"
      :style="`width:${record.options.width}`"
      class="slider-box"
    >
      <div class="slider">
        <a-slider
          :disabled="record.options.disabled"
          :min="record.options.min"
          :max="record.options.max"
          :step="record.options.step"
          v-decorator="[
            record.model,
            {
              initialValue: record.options.defaultValue,

            }
          ]"
          @change="changeValue"
          @blur="onblur"
        />
      </div>
    </div>
    <!-- 图片上传 -->
    <UploadImg
      ref="comp"
      v-else-if="record.type === 'uploadImg' && !record.options.enableOss"
      :style="`width:${record.options.width}`"
      :record="record"
      v-decorator="[
        record.model,
        {
          initialValue: record.options.defaultValue
        }
      ]"
      @change="changeValue"
      @blur="onblur"
    />
    <!-- 文件上传 -->
    <UploadFile
      ref="comp"
      v-else-if="record.type === 'uploadFile' && !record.options.enableOss"
      :style="`width:${record.options.width}`"
      :record="record"
      v-decorator="[
        record.model,
        {
          initialValue: record.options.defaultValue
        }
      ]"
      @change="changeValue"
      @blur="onblur"
    />
    <!-- 图片上传 -->
    <UploadImgNoModel
      ref="comp"
      v-else-if="record.type === 'uploadImg' && record.options.enableOss"
      :style="`width:${record.options.width}`"
      :record="record"
      :form-id="formId"
      :uploadTimestamp="uploadTimestamp"
      v-decorator="[
        record.dataId,
      ]"
      @change="changeValue"
      @blur="onblur"
    />
    <!-- 文件上传 -->
    <UploadFileNoModel
      ref="comp"
      v-else-if="record.type === 'uploadFile' && record.options.enableOss"
      :style="`width:${record.options.width}`"
      :record="record"
      :form-id="formId"
      :uploadTimestamp="uploadTimestamp"
      v-decorator="[
        record.dataId
      ]"
      @change="changeValue"
      @blur="onblur"
    />
    <!-- 用户选择 -->
    <ych-select-user
      ref="comp"
      v-else-if="record.type === 'user'"
      :disabled="record.options.disabled"
      :readOnly="record.options.readOnly"
      :placeholder="$locale(record.options.placeholder)"
      :multi="record.options.multiple"
      :customReturnField="record.options.useCode ? 'username' : 'id'"
      :customOrgOrderSql="record.options.customOrgOrderSql"
      :customOrgFilterSql="record.options.customOrgFilterSql"
      :currentOrgAsRoot="record.options.currentOrgAsRoot"
      :filterAuth="record.options.filterAuth"
      :linkage="record.options.enableLinkage ? record.options.linkage : null"
      :linkageMap="linkageMap"
      v-decorator="[
        record.model, // input 的 name
        {
          initialValue: record.options.defaultValue, // 默认值
          rules: getRules // 验证规则
        }
      ]"
      @change="changeValue"
      @blur="onblur"
    />
    <!-- 部门选择 -->
    <ych-select-depart
      ref="comp"
      v-else-if="record.type === 'dept'"
      :disabled="record.options.disabled"
      :readOnly="record.options.readOnly"
      :placeholder="$locale(record.options.placeholder)"
      :multi="record.options.multiple"
      :customReturnField="record.options.useCode ? 'orgCode' : 'id'"
      :customOrgOrderSql="record.options.customOrgOrderSql"
      :customOrgFilterSql="record.options.customOrgFilterSql"
      :currentOrgAsRoot="record.options.currentOrgAsRoot"
      :filterAuth="record.options.filterAuth"
      :checkableLinkage="record.options.checkableLinkage"
      :onlyCheckDept="record.options.onlyCheckDept"
      v-decorator="[
        record.model, // input 的 name
        {
          initialValue: record.options.defaultValue, // 默认值
          rules: getRules // 验证规则
        }
      ]"
      @change="changeValue"
      @blur="onblur"
    />
    <!-- 弹框选择 -->
    <view-select-tag
      ref="comp"
      v-else-if="record.type === 'page'"
      :disabled="record.options.disabled"
      :placeholder="$locale(record.options.placeholder)"
      :multi="record.options.multiple"
      :viewCode="record.options.viewCode"
      :keyField="record.options.keyField"
      :labelField="record.options.labelField"
      :fields="record.options.fields"
      :parameterConfig="record.options.parameterConfig"
      @setFieldValue="setFieldValue"
      @getFieldValue="getFieldValue"
      :form="form"
      v-decorator="[
        record.model, // input 的 name
        {
          initialValue: record.options.defaultValue, // 默认值
          rules: getRules // 验证规则
        }
      ]"
      @change="changeValue"
      @blur="onblur"
      :stores="stores"
    />
    <!-- 签名 -->
    <Signature
      ref="comp"
      v-else-if="record.type === 'signature'"
      :style="`width:${record.options.width}`"
      :disabled="record.options.disabled"
      :multiple="record.options.multiple"
      :bizPath="record.options.bizPath"
      v-decorator="[
        record.model,
        {
          initialValue: record.options.defaultValue
        }
      ]"
      @change="changeValue"
      @blur="onblur"
    />
    <!--富文本-->
<!--    <ych-editor-->
<!--      ref="comp"-->
<!--      v-else-if="record.type === 'editor'"-->
<!--      :disabled="record.options.disabled"-->
<!--      :placeholder="$locale(record.options.placeholder)"-->
<!--      v-decorator="[-->
<!--        record.model, // input 的 name-->
<!--        {-->
<!--          initialValue: record.options.defaultValue, // 默认值-->
<!--           rules: getRules // 验证规则-->
<!--        }-->
<!--      ]"-->
<!--      @change="changeValue"-->
<!--      @blur="onblur"-->
<!--    ></ych-editor>-->
    <!-- 流水号 -->
    <ych-serialno
      ref="comp"
      v-else-if="record.type === 'serialno'"
      :disabled="record.options.disabled"
      :placeholder="$locale(record.options.placeholder)"
      :readOnly="record.options.readOnly"
      :ruleCode="record.options.ruleCode"
      v-decorator="[
        record.model, // input 的 name
        {
          initialValue: record.options.defaultValue, // 默认值
           rules: getRules // 验证规则
        }
      ]"
      @change="changeValue"
      @blur="onblur"
      :form="form"
    />
    <!-- 图标选择 -->
    <ych-icon-select
      ref="comp"
      v-else-if="record.type === 'icon'"
      :disabled="record.options.disabled"
      :placeholder="$locale(record.options.placeholder)"
      write
      :iconfont="true"
      v-decorator="[
        record.model, // input 的 name
        {
          initialValue: record.options.defaultValue, // 默认值
           rules: getRules // 验证规则
        }
      ]"
      @change="changeValue"
      @blur="onblur"
    />

    <!--    辅助显示-->
    <div v-if="record.helpShowText">
      <el-tooltip class="item" effect="light" placement="top">
        <i class="el-icon-question" style="z-index: 9999; position: absolute; right: -13px; top: 25%;"></i>
        <div style="width: 300px;" slot="content" v-html="getFormatCode(record.helpShowText)"></div>
      </el-tooltip>
    </div>
    <div v-else-if="canvas && record.type === 'custom' && record.options.isModel">
      自定义组件，运行时渲染
    </div>
  </a-form-item>
  <!--子表-->
  <ych-vxe-table
    ref="comp"
    v-else-if="record.type === 'editableTable'"
    v-show="canvas || !record.options.hidden"
    :style="record.options.tableTop ? 'padding-top:' + record.options.tableTop + 'px' : ''"
    :ref="record.tableName"
    :dataSource="dataSourceEditableTable"
    :columns="getColumns"
    :reloadDataFlg.sync="reloadDataFlg"
    :recordConfig="record"
    :rowNumber="record.options.rowNumber"
    :rowSelection="record.options.rowSelection"
    :actionButton="record.options.actionButton"
    :actionButtonConfig="record.options.buttonConfig"
    :disabled="record.options.disabled"
    :treeEnable="record.options.treeEnable"
    :parentField="record.options.parentField"
    :treeNodeField="record.options.treeNodeField"
    :height="record.options.height || 400"
    :dragSort="record.options.dragSortEnable"
    :dragSortKey="record.options.dragSortField"
    :insertIndex="typeof record.options.insertIndex === 'undefined' ? -1 : record.options.insertIndex"
    :isPage="record.options.isPage === 'Y'"
    :form="form"
    :allDataSource="allDataSource"
    :parentLinkageMap="linkageMap"
    @setDataSource="setDataSourceEditableTable"
    @added="subTableAdded"
    @deleted="subTableDeleted"
    @valueChange="subTableValueChange"
    @refreshAllData="$emit('refreshAllData')"
    :fks="fks"
    :stores="stores"
  >
  </ych-vxe-table>
  <!-- button按钮 -->
  <a-form-item
    v-else-if="record.type === 'button' && record.options.layout !== 'inline'"
    v-show="canvas || !record.options.hidden"
    :wrapper-col="
      config.layout === 'horizontal'
        ? { ...(record.options.custom ? record.custom.wrapperCol : config.wrapperCol), offset: record.options.custom ? record.custom.labelCol.span : config.labelCol.span }
        : {}
    "
  >
    <a-button
      v-if="record.options.handle === 'submit'"
      :disabled="record.options.disabled"
      :type="record.options.type"
      html-type="submit"
      v-text="$locale(record.name)"
    ></a-button>
    <a-button
      v-else-if="record.options.handle === 'reset'"
      :disabled="record.options.disabled"
      :type="record.options.type"
      @click="$emit('handleReset')"
      v-text="$locale(record.name)"
    ></a-button>
    <page-button
      v-else-if="record.options.handle === 'page'"
      :record="record"
      @setFieldValue="setFieldValue"
      @getFieldValue="getFieldValue"
      :form="form"
    ></page-button>
    <a-button
      v-else-if="record.options.handle === 'action'"
      :disabled="record.options.disabled"
      :type="record.options.type"
      @click="$emit('doButtonAction', record.options.action)"
      v-text="$locale(record.name)"
    ></a-button>
  </a-form-item>
  <a-button
    v-else-if="record.type === 'button' && record.options.layout === 'inline' && record.options.handle === 'submit'"
    v-show="canvas || !record.options.hidden"
    :disabled="record.options.disabled"
    :type="record.options.type"
    html-type="submit"
    :style="{marginRight: (record.options.spacing || 8) + 'px'}"
    v-text="$locale(record.name)"
  ></a-button>
  <a-button
    v-else-if="record.type === 'button' && record.options.layout === 'inline' && record.options.handle === 'reset'"
    v-show="canvas || !record.options.hidden"
    :disabled="record.options.disabled"
    :type="record.options.type"
    @click="$emit('handleReset')"
    :style="{marginRight: (record.options.spacing || 8) + 'px'}"
    v-text="$locale(record.name)"
  ></a-button>
  <page-button
    v-else-if="record.type === 'button' && record.options.layout === 'inline' && record.options.handle === 'page'"
    v-show="canvas || !record.options.hidden"
    :record="record"
    @setFieldValue="setFieldValue"
    @getFieldValue="getFieldValue"
    :style="{marginRight: (record.options.spacing || 8) + 'px'}"
    :form="form"
  ></page-button>
  <a-button
    v-else-if="record.type === 'button' && record.options.layout === 'inline' && record.options.handle === 'action'"
    v-show="canvas || !record.options.hidden"
    :disabled="record.options.disabled"
    :type="record.options.type"
    @click="$emit('doButtonAction', record.options.action)"
    :style="{marginRight: (record.options.spacing || 8) + 'px'}"
    v-text="$locale(record.name)"
  ></a-button>

  <!-- alert提示 -->
  <a-form-item v-else-if="record.type === 'alert'" v-show="canvas || !record.options.hidden">
    <a-alert
      :message="$locale(record.name)"
      :description="record.options.description"
      :type="record.options.type"
      :showIcon="record.options.showIcon"
      :closable="record.options.closable"
      :banner="record.options.banner"
    />
  </a-form-item>
  <!-- 文本 -->
  <a-form-item v-else-if="record.type === 'text'" v-show="canvas || !record.options.hidden" :style="record.options.customStyle">
    <template v-if="record.options.isModel">
      <TextTag :textStyleLabel="textStyleLabel" :textStyleDiv="textStyleDiv" :record="record" :value="record.options.defaultValue" :canvas="canvas" @click="textClick"></TextTag>
    </template>
    <template v-else>
      <div v-if="record.options.showHtml" v-html="$locale(record.name)" @click="textClick"></div>
      <div :style="textStyleDiv" v-else>
        <label :style="textStyleLabel"
               :class="{ 'ant-form-item-required': record.options.showRequiredMark }"
               v-text="$locale(record.name)" @click="textClick">
        </label>
      </div>
    </template>
  </a-form-item>
  <!-- html -->
  <div v-show="canvas || !record.options.hidden"
       v-else-if="record.type === 'html'" @click="htmlClick()"
       v-html="record.options.defaultValue"
  ></div>
  <div v-else-if="canvas && record.type === 'custom' && !record.options.isModel">
    自定义组件，运行时渲染
  </div>
  <div class="divider-blocks" v-else>
    <!-- 分割线 -->
    <a-divider v-if="record.type === 'divider' &&record.name !== '' &&record.options.orientation"
               :orientation="record.options.orientation">{{ $locale(record.name) }}
    </a-divider>
    <a-divider v-else-if="record.type === 'divider' && record.name !== ''">{{ $locale(record.name) }}</a-divider>
    <a-divider v-else-if="record.type === 'divider' && record.name === ''"/>
  </div>
</template>
<script>
// import moment from "moment";
// import customComponent from './customComponent'
import UploadFile from '../UploadFile'
import UploadImg from '../UploadImg'
import UploadFileNoModel from '../UploadFile/uploadFileNoModel'
import UploadImgNoModel from '../UploadImg/uploadImgNoModel'
import KDatePicker from '../KDatePicker'
import KTimePicker from '../KTimePicker'
import DictSelectTag from '../../packages/components/Common/DictSelectTag.vue'
import { EFormConstant } from '../utils/EFormConstant'
import { ajaxGetDictItems, ajaxGetSqlConfigItems, ajaxGetHttpConfigItems} from '../utils/api/api'
import YchSelectDepart from '../../packages/components/Common/ych-org/YchSelectDepart'
import YchSelectUser from '../../packages/components/Common/ych-user/YchSelectUser'
import ViewSelectTag from '../../packages/components/viewSelect/ViewSelectTag'
import { currentUser, currentDept, currentOrg, currentDate, currentTime, elValue } from '../utils/ElValue'
import PageButton from '../PageButton'
import { duplicateCheck } from '../utils/api/api'
import { handleCreateFunc, handleExecFunc } from '../utils/actions'
import YchSerialno from '../../packages/components/Common/YchSerialno'
import { getAction, deleteAction, putAction, postAction, httpAction } from '../utils/manage'
import {YchIconSelect} from '@yuncheng/ych-components'
import TextTag from '../../packages/components/tag/TextTag.vue'
import YchVxeTable from '../../packages/components/Common/YchVxeTable.vue'
import Signature from '../Signature/signature'
import YchDisplayTextTag from './YchDisplayTextTag'
import YchDisplayHtmlTag from './YchDisplayHtmlTag'
import moment from "moment";
import error from "../../packages/components/Common/exception/404";
import LocleUtil from "../utils/LocleUtil";
import common from "../utils/common";
import locleUtil from "../utils/LocleUtil";
// import KFiveWhy from "../KFiveWhy";
// import FiveWhyButton from "../FiveWhyButton/FiveWhyButton";
// import MindButton from "../MindButton/MindButton";
// import ProcessDetail from "../ProcessDetail/ProcessDetail";
// import FishBone from "../FishBone/FishBone";
export default {
  name: 'KFormItem',
  props: {
    form: {
      type: Object,
      default: () => {
      }
    },
    linkageMap: {
      type: Object,
      default: () => {
      }
    },
    // 表单数组
    record: {
      type: Object,
      default: () => {
      }
    },
    // form-item 宽度配置
    config: {
      type: Object,
      required: true
    },
    allDataSource: {
      type: Object,
      default: () => {
      }
    },
    dictMap: {
      type: Object,
      default: () => {
      }
    },
    elValue: {
      type: Object,
      default: () => {
      }
    },
    dsCode: {
      type: Object,
      default: () => {
      }
    },
    canvas: {
      type: Boolean,
      required: false,
      default: false
    },
    formId: {
      type: String
    },
    fks: {
      type: Array,
      default: () => []
    },
    stores: {
      type: Object,
      default: () => {
        return {}
      }
    },
    uploadTimestamp: {
      type: String
    }
  },
  components: {
    // FishBone,
    // ProcessDetail,
    // MindButton,
    // FiveWhyButton,
    // KFiveWhy,
    UploadImg,
    UploadFile,
    UploadImgNoModel,
    UploadFileNoModel,
    KDatePicker,
    KTimePicker,
    // customComponent,
    DictSelectTag,
    YchSelectDepart,
    YchSelectUser,
    ViewSelectTag,
    PageButton,
    YchSerialno,
    // YchEditor: () => import("@/components/ych/YchEditor"),
    YchIconSelect,
    TextTag,
    YchVxeTable,
    Signature,
    YchDisplayTextTag,
    YchDisplayHtmlTag,
  },
  computed: {
    customList() {
      if (window.$customComponentList) {
        return window.$customComponentList.map(item => item.type)
      } else {
        return []
      }
    },
    getRules() {
      return common.getRules(this.record, EFormConstant.validRule, this.validatorPk,this.validatorUnionCheck)
    },
    //子表字段控制
    getColumns() {
      const that = this;
      return common.getColumns(this.record, this.dictMap, ajaxGetDictItems, ajaxGetSqlConfigItems, ajaxGetHttpConfigItems, this.form, () => {
        that.reloadDataFlg = true
      })
    },
    textStyleDiv() {
      return common.textStyleDiv(this.record)
    },
    textStyleLabel() {
      return common.textStyleLabel(this.record)
    }
  },
  data() {
    return {
      dataSourceEditableTable: [],
      validateStatus: undefined,
      validateHelp: undefined,
      componentFile: null,
      componentObj: {},
      createI: null,
      fiveWhyFlag: false,
      reloadDataFlg: false, // 解决子表下拉框选项异步加载时不能回显的问题
    }
  },
  methods: {
    $locale(params) {
      return locleUtil.getLocale(params)
    },
    //保存textarea的空格
    getFormatCode(strValue) {
      return strValue.replace(/\r\n/g, '<br/>').replace(/\n/g, '<br/>').replace(/\s*/g, '');
    },
    setDataSourceEditableTable(dataSource, event) {
      // 自定义子表数据处理
      if (this.record.options && this.record.options.dealDataSource) {
        const func = handleCreateFunc(this.record.options.dealDataSource, this)
        const func_result = handleExecFunc(func, {dataSource})
        if (func_result) {
          dataSource = func_result
          if (event) {
            // 只有触发事件才会更新
            this.dataSourceEditableTable = dataSource
          }
        }
      }
      if (!event) {
        // 无论如何都会更新
        this.dataSourceEditableTable = dataSource
      }
    },
    setHidden(tableName,modelName,isHidden){
      this.$emit('setHidden',tableName,modelName,isHidden)
    },
    setTabHidden(key, isHidden) {
      this.$emit("setTabHidden", key, isHidden);
    },
    validatorPk(rule, value, callback) {
      if (!value) {
        callback()
        return
      }
      const params = {
        tableName: this.record.tableName,
        fieldName: this.record.model,
        fieldVal: value,
        dataId: this.formId,
        hump: true,
        dsCode: this.dsCode[this.record.tableName] || ''
      }
      duplicateCheck(params).then((res) => {
        if (res.success) {
          callback()
        } else {
          callback(res.message)
        }
      })
    },
    validatorUnionCheckClean(unionCheckNameArr) {
      const that = this;
      const fieldsInfo = {}
      unionCheckNameArr.forEach(field => {
        let error = that.form.getFieldError(field)
        if (error && error.length > 0 && error[0] === that.$t('m.common.tip.code_already_exists')) {
          let fieldValue = that.form.getFieldValue(field)
          fieldsInfo[field] = {
            value: fieldValue
          }
        }
      })
      that.form.setFields(fieldsInfo)
    },
    validatorUnionCheck(rule, value, callback) {
      let unionCheckNameArr = rule.unionCheck.filter(item => item !== this.record.model)
      if (!value) {
        callback()
        this.validatorUnionCheckClean(unionCheckNameArr)
        return
      }

      let unionCheckNames = unionCheckNameArr.join("@#@")
      let unionCheckValueArr = []

      for (let i = 0; i < unionCheckNameArr.length; i++) {
        const field = unionCheckNameArr[i]
        let fieldValue = this.form.getFieldValue(field)
        if (fieldValue === '' || fieldValue === undefined) {
          callback()
          this.validatorUnionCheckClean(unionCheckNameArr)
          return
        }
        unionCheckValueArr.push(fieldValue)
      }

      let unionCheckValues = unionCheckValueArr.join("@#@")
      const params = {
        tableName: this.record.tableName,
        fieldName: this.record.model,
        fieldVal: value,
        dataId: this.formId,
        unionCheckNames: unionCheckNames,
        unionCheckValues: unionCheckValues,
        hump: true,
        dsCode: this.dsCode[this.record.tableName] || ''
      }

      const that = this;
      duplicateCheck(params).then((res) => {
        if (res.success) {
          callback()
          that.validatorUnionCheckClean(unionCheckNameArr)
        } else {
          callback(that.$t('m.common.tip.code_already_exists'))

          const fieldsInfo = {}
          unionCheckNameArr.forEach(field => {
            let error = that.form.getFieldError(field)
            if (!error || error.length === 0) {
              let fieldValue = that.form.getFieldValue(field)
              fieldsInfo[field] = {
                value: fieldValue,
                errors: [new Error(that.$t('m.common.tip.code_already_exists'))]
              }
            }
          })
          that.form.setFields(fieldsInfo)

        }
      })
    },
    setFieldValue(key, value) {
      this.$emit('setFieldValue', key, value)
    },
    getFieldValue(key, func) {
      this.$emit('getFieldValue', key, func)
    },
    isDbModel() {
      if (!this.allDataSource || !this.record.tableName || !this.record.model) {
        return false
      }
      let modelKey = this.record.tableName + '-' + this.record.model
      if (!this.allDataSource.hasOwnProperty(modelKey)) {
        modelKey = this.record.model
        if (!this.allDataSource.hasOwnProperty(modelKey)) {
          return false
        }
      }
      return true
    },
    getValueFromData() {
      if (!this.allDataSource || !this.record.tableName || !this.record.model) {
        return
      }
      let modelKey = this.record.tableName + '-' + this.record.model
      if (!this.allDataSource.hasOwnProperty(modelKey)) {
        modelKey = this.record.model
        if (!this.allDataSource.hasOwnProperty(modelKey)) {
          return
        }
      }
      this.$emit('addModelKey', modelKey)
      const value = this.allDataSource[modelKey]
      if (typeof value === 'undefined' || value === null) {
        return
      }
      if (this.record.type === 'switch') {
        return value === 'true'
      } else {
        return value
      }
    },
    // 数据监控
    changeValue(arg1, arg2) {
      if (this.record.watch) {
        let value = arg1
        if (this.record.type === 'input' || this.record.type === 'textarea') {
          value = arg1.target.value
        }
        const func = handleCreateFunc(this.record.watch, this)
        handleExecFunc(func, { arg1, arg2, value })
      }

      this.validBusiness(arg1)

      // 联动 input等类型 改到 onblur，有几个控件一般不会用于联动
      // TODO 如果后续表单和子表的文本框增加了清空功能，需要联动的调用
      if (this.record.type && this.record.model && !(this.record.type === 'input' ||
        this.record.type === 'textarea' ||
        this.record.type === 'number' ||
        this.record.type === 'slider' ||
        this.record.type === 'rate' ||
        this.record.type === 'uploadFile' ||
        this.record.type === 'uploadImg' ||
        this.record.type === 'editor' ||
        this.record.type === 'signature')) {
        let value = arg1

        this.$emit("setLinkageMap", this.record.model, value)
      }
    },
    /*暂时未处理两点
    1、没有严格校验，有的控件不需要该事件
    2、有的组件是嵌套组件，没有将事件传递到底层*/
    onblur(event){
      if (this.record.onblur) {
        const value = (this.form && this.record.model) ? this.form.getFieldValue(this.record.model) : null
        const func = handleCreateFunc(this.record.onblur, this)
        handleExecFunc(func, {event, value})
      }
      // 联动
      if (this.form && this.record.model && (this.record.type === 'input' || this.record.type === 'textarea' || this.record.type === 'number')) {
        const value = this.form.getFieldValue(this.record.model)
        this.$emit("setLinkageMap", this.record.model, value)
      }
    },
    //回车事件
    pressEnter(event){
      event.preventDefault();
      if (this.record.options.enter) {
        const value = (this.form && this.record.model) ? this.form.getFieldValue(this.record.model) : null
        const func = handleCreateFunc(this.record.options.enter, this)
        handleExecFunc(func, {event, value})
      }
    },
    //后图标点击事件
    afterIconClick(event){
      if (this.record.options.afterIconClick && !this.record.options.disabled) {
        const value = (this.form && this.record.model) ? this.form.getFieldValue(this.record.model) : null
        const func = handleCreateFunc(this.record.options.afterIconClick, this)
        handleExecFunc(func, {event, value})
      }
    },
    //文本控件点击事件
    textClick(){
      let value = this.record.options.defaultValue
      let name = this.record.name
      if (this.record.options.click) {
        const func = handleCreateFunc(this.record.options.click, this)
        handleExecFunc(func, {name,value})
      }
    },
    //html控件点击事件
    htmlClick(){
      let value = this.record.options.defaultValue
      if (this.record.options.click) {
        const func = handleCreateFunc(this.record.options.click, this)
        handleExecFunc(func, {value})
      }
    },
    validBusiness(arg1) {
      if (!this.record.businessRules || !this.record.businessRules.enable) {
        return
      }

      this.validateStatus = undefined
      this.validateHelp = undefined
      const that = this
      this.$nextTick(() => {
        that.form.validateFields([that.record.model], (error) => {
          if (!error) {
            that.afterValid(arg1)
          }
        })
      })
    },
    afterValid(arg1) {
      this.validateStatus = 'validating'
      this.validateHelp = this.$t('m.eform.formDesign.label.xiao-yan-zhong')
      //TODO 目前仅支持数字框的业务提示功能
      const value = arg1
      const max = this.record.businessRules.max
      const min = this.record.businessRules.min
      if (typeof value == 'number' && ((typeof max == 'number' && value > max) || (typeof min == 'number' && value < min))) {
        this.validateStatus = 'error'
        this.validateHelp = this.record.businessRules.message || this.$t('m.eform.formDesign.label.shu-ru-xiang-bu-fu-he-yao-qiu')
      } else {
        this.validateStatus = undefined
        this.validateHelp = undefined
      }
    },
    // 子表
    subTableAdded(obj, dataSource) {
      if (this.record.options.added) {
        const func = handleCreateFunc(this.record.options.added, this)
        handleExecFunc(func, {obj})
      }
      if (typeof dataSource !== "undefined") {
        this.setDataSourceEditableTable(dataSource, true);
      }
    },
    subTableDeleted(ids, dataSource) {
      if (this.record.options.deleted) {
        const func = handleCreateFunc(this.record.options.deleted, this)
        handleExecFunc(func, {ids, dataSource})
      }
      if (typeof dataSource !== "undefined") {
        this.setDataSourceEditableTable(dataSource, true);
      }
    },
    subTableValueChange(e, dataSource) {
      if (this.record.options.valueChange) {
        const func = handleCreateFunc(this.record.options.valueChange, this)
        handleExecFunc(func, {e})
      }
      if (typeof dataSource !== "undefined") {
        this.setDataSourceEditableTable(dataSource, true);
      }
    },
  },
  mounted() {
    const that = this;
    this.$nextTick(() => {
      //记录子表控件和对应key
      if (this.record.type === 'editableTable') {
        this.$emit('addEditableTableVm', this.record.tableName, this)
        let dataSourceEditableTable = this.allDataSource ? this.allDataSource[this.record.tableName + 'List'] : []
        dataSourceEditableTable = dataSourceEditableTable || []

        // 排序
        if (this.record.options.dragSortField) {
          const compare = function (obj1, obj2) {
            let val1 = obj1[that.record.options.dragSortField];
            let val2 = obj2[that.record.options.dragSortField];
            val1 = Number(val1)
            if (isNaN(val1)) {
              val1 = 9999
            }
            val2 = Number(val2)
            if (isNaN(val2)) {
              val2 = 9999
            }
            return val1 - val2
          }
          dataSourceEditableTable = dataSourceEditableTable.sort(compare);
        }

        this.setDataSourceEditableTable(dataSourceEditableTable, false);
      }
    })
  },
  created() {
    if(this.canvas){
      // 如果是在画布上渲染
      return;
    }
    this.record.$vm = this
    if (this.record.type === 'custom' && this.record.options.componentUrl) {
      this.componentObj = this.record.options.parameters ? JSON.parse(this.record.options.parameters) : {}
      // this.componentFile = (resolve) => ({
      //   component: require([`@/views/${this.record.options.componentUrl}.vue`], resolve),
      //   //component: import(`@/views/` + this.record.options.componentUrl + '.vue'),
      //   error: error,
      //   delay: 200,
      //   timeout: 10000
      // })
    }
    const defaultValue = this.getValueFromData()
    const isDbModel = this.isDbModel()
    if (typeof defaultValue == 'undefined' && (!this.record.options.disabled || !isDbModel)) {
      if (this.record.options.currentUser) {
        this.record.options.defaultValue = currentUser(this.elValue)
      } else if (this.record.options.currentDept) {
        this.record.options.defaultValue = currentDept(this.elValue)
      } else if (this.record.options.currentOrg) {
        this.record.options.defaultValue = currentOrg(this.elValue)
      } else if (this.record.options.currentDate) {
        let currentDateValue = currentDate(this.elValue)
        if (this.record.options.format && !this.record.options.range) {
          currentDateValue = moment(currentDateValue, this.record.options.format).format("YYYY-MM-DD HH:mm:ss");
        }
        this.record.options.defaultValue = currentDateValue
      } else if (this.record.options.currentTime) {
        this.record.options.defaultValue = currentTime(this.elValue)
      } else {
        if (typeof this.record.options.defaultValue == 'string') {
          this.record.options.defaultValue = elValue(this.elValue, this.record.options.defaultValue)
        }
      }
    } else {
      this.record.options.defaultValue = typeof defaultValue == 'undefined' ? null : defaultValue
    }
    // 联动
    if (this.record.type && this.record.model) {
      this.$emit('setLinkageMap', this.record.model, this.record.options.defaultValue, true)
    }
  }
}
</script>
<style lang="less">
.custom-context-item {
  position: fixed;
  border: 1px solid #ccc;
  list-style: none;
  padding: 4px 0;
  border-radius: 4px;
  z-index: 9999999999;
  width: auto;
  background: #fafafa;

  li {
    padding: 8px 12px;
    border-bottom: 1px solid #f0f2f5;
    user-select: none;
    transition: all 0.1s;
  }
}

.hiddenEle {
  display: none;
}
</style>
<style lang="less" scoped>
.ant-row /deep/ .ant-form-item {
  display: flex;
  align-items: center;
  position: relative;
}

.slider-box {
  display: flex;

  > .slider {
    flex: 1;
    margin-right: 16px;
  }

  > .number {
    width: 70px;
  }
}

.alignCenter /deep/ .ant-form-item-label {
  text-align: center;
}
</style>
