<template>
  <!-- 单行文本、 多行文本、 数字-->
  <van-field
    v-if="fieldType==='text'||fieldType==='textarea'||fieldType==='number'"
    v-model="dataModel"
    :name="field.name"
    :label="label"
    :placeholder="placeholder"
    :input-align="inputAlign"

    :type="fieldType"

    :required="required"
    :readonly="readonly"
    :rules="rules"

    :autosize="autosize"
    :rows="fieldOptions.rows||2"
    :desc="field.desc"
    autocomplete="off"
    border
    clearable
    v-on="$listeners"
  >
    <template #label>
      {{ label }}<van-icon v-if="field.desc && descPosition==='lableIcon'" name="warning" class="ibps-dialog-icon" @click="showDesc(label,field.desc)" />
    </template>
  </van-field>

  <ibps-stepper
    v-else-if="fieldType==='inputNumber'"
    v-model="dataModel"
    :max="fieldOptions.max"
    :min="fieldOptions.min"
    :step="fieldOptions.step"
    :placeholder="fieldOptions.placeholder"
    :desc="field.desc"
    :desc-position="descPosition"
    :input-align="inputAlign"

    :label="label"
    :required="required"
    :readonly="readonly"
    :rules="rules"

    v-on="$listeners"
  />

  <!-- 单项选择 -->
  <ibps-radio
    v-else-if="fieldType==='radio'"
    v-model="dataModel"
    :name="field.name"
    :label="label"
    :placeholder="placeholder"
    :input-align="inputAlign"

    :options="dataOptions"
    value-key="val"
    :other-option-value.sync="otherOptionValue"

    :required="required"
    :readonly="readonly"
    :rules="rules"
    :desc-position="descPosition"
    :desc="field.desc"
    border
    clearable

    v-on="$listeners"
  />

  <!-- 多项选择 -->
  <ibps-checkbox
    v-else-if="fieldType==='checkbox'"
    v-model="dataModel"
    :name="field.name"
    :label="label"
    :placeholder="placeholder"
    :input-align="inputAlign"

    :options="dataOptions"
    value-key="val"
    :other-option-value.sync="otherOptionValue"

    :required="required"
    :readonly="readonly"
    :rules="rules"
    :desc-position="descPosition"
    :desc="field.desc"
    border
    clearable
    v-on="$listeners"
  />
  <!-- 下拉选择 -->
  <ibps-select
    v-else-if="fieldType==='select'"
    v-model="dataModel"
    :name="field.name"
    :label="label"
    :placeholder="placeholder"
    :input-align="inputAlign"

    :options="dataOptions"
    value-key="val"

    :required="required"
    :readonly="readonly"
    :rules="rules"
    :desc-position="descPosition"
    :desc="field.desc"
    border
    clearable
    v-on="$listeners"
  />
  <!-- 日期/ 当前时间、当前日期 -->
  <ibps-date-picker
    v-else-if="fieldType==='datePicker'|| fieldType==='currentDate'|| fieldType==='currentTime'"
    v-model="dateDataModel"
    :label="field.label"
    :desc="field.desc"
    :desc-position="descPosition"
    :placeholder="placeholder"
    :format="dateFormat"
    :input-align="inputAlign"

    :name="field.name"
    :required="required"
    :readonly="fieldType==='currentTime'||fieldType==='currentDate'?true:readonly"
    :rules="rules"
    type="custom"
    v-on="$listeners"
  />

  <!-- 开关控件 -->
  <ibps-switch
    v-else-if="fieldType==='switch'"
    v-model="dataModel"
    :name="field.name"
    :label="field.label"
    :placeholder="placeholder"
    :desc="field.desc"
    :desc-position="descPosition"
    :input-align="inputAlign"

    :active-value="fieldOptions.active_value"
    :inactive-value="fieldOptions.inactive_value"
    :active-text="fieldOptions.active_text"
    :inactive-text="fieldOptions.inactive_text"
    :active-color="fieldOptions.active_color"
    :inactive-color="fieldOptions.inactive_color"

    :required="required"
    :disabled="readonly"
    :rules="rules"

    v-on="$listeners"
  />

  <!-- 滑块控件 -->
  <ibps-slider
    v-else-if="fieldType==='slider'"
    v-model="numberDataModel"
    :name="field.name"
    :label="field.label"
    :desc="field.desc"
    :desc-position="descPosition"
    :placeholder="placeholder"

    :max="fieldOptions.max"
    :min="fieldOptions.min"
    :step="fieldOptions.step"

    :required="required"
    :disabled="readonly"
    :rules="rules"
    v-on="$listeners"
  />

  <!-- 评分控件 -->
  <ibps-rate
    v-else-if="fieldType==='rate'"
    v-model="numberDataModel"
    :name="field.name"
    :label="field.label"
    :desc="field.desc"
    :desc-position="descPosition"
    :placeholder="placeholder"
    :input-align="inputAlign"

    :count="fieldOptions.max"
    :allow-half="fieldOptions.allow_half"

    :required="required"
    :readonly="readonly"
    :rules="rules"
    v-on="$listeners"
  />
  <!-- 富文本 -->
  <ibps-editor
    v-else-if="fieldType==='editor'"
    v-model="dataModel"
    :label="field.label"
    :desc="field.desc"
    :desc-position="descPosition"
    :placeholder="placeholder"
    :height="height"

    :name="field.name"
    :required="required"
    :readonly="readonly"
    :rules="rules"
    v-on="$listeners"
  />
  <!-- 数据字典 -->
  <ibps-dictionary
    v-else-if="fieldType==='dictionary'"
    v-model="dataModel"
    :label="field.label"
    :desc="field.desc"
    :desc-position="descPosition"
    :placeholder="placeholder"
    :type-key="fieldOptions.dictionary"
    :select-mode="fieldOptions.select_mode"
    :display-mode="fieldOptions.display_mode"
    :separator="fieldOptions.split"
    :multiple="multiple"
    :input-align="inputAlign"

    :name="field.name"
    :required="required"
    :readonly="readonly"
    :rules="rules"
    v-on="$listeners"
  />
  <!-- 自动编号 -->
  <ibps-auto-number
    v-else-if="fieldType==='autoNumber'"
    v-model="dataModel"
    :label="field.label"
    :desc="field.desc"
    :desc-position="descPosition"
    :placeholder="placeholder"
    :identity="fieldOptions.identity"
    :init="$utils.toBoolean(fieldOptions.init)"
    :input-align="inputAlign"

    :name="field.name"
    :required="required"
    :readonly="readonly"
    :rules="rules"
    v-on="$listeners"
  />
  <!-- 上传附件 -->
  <ibps-uploader
    v-else-if="fieldType==='attachment'"
    v-model="dataModel"
    :label="field.label"
    :desc="field.desc"
    :desc-position="descPosition"
    :placeholder="placeholder"
    :store="fieldOptions.store||'json'"
    :max-size="maxFileSize"
    :limit="fileQuantity"
    :accept="fileAccept"
    :file-formates="fileFormates"
    :multiple="multiple"
    :download="fieldOptions.download"
    :upload-type="fieldOptions.uploadType"
    :input-align="inputAlign"

    :name="field.name"
    :required="required"
    :readonly="readonly"
    :rules="rules"
    v-on="$listeners"
  />

  <!-- 选择器 -->
  <ibps-selector
    v-else-if="fieldType==='selector' || fieldType==='currentUser'|| fieldType==='currentOrg'"
    v-model="dataModel"
    :label="field.label"
    :desc="field.desc"
    :desc-position="descPosition"
    :placeholder="placeholder"
    :store="fieldOptions.store||'id'"
    :type="fieldOptions.selector_type||'user'"
    :multiple="multiple"
    :bind-id="bindId"
    :field-options="fieldOptions"
    :filter="fieldOptions.filter"
    :input-align="inputAlign"

    :name="field.name"
    :required="required"
    :readonly="(fieldType==='currentUser' || fieldType==='currentOrg')?true:readonly"
    :rules="rules"
    @bind-callback="selectorBindCallback"
    v-on="$listeners"
  />
  <!-- 自定义对话框 -->
  <ibps-custom-dialog
    v-else-if="fieldType==='customDialog'"
    v-model="dataModel"
    :label="field.label"
    :desc="field.desc"
    :desc-position="descPosition"
    :placeholder="placeholder"
    :multiple="multipleSelect"
    :template-key="fieldOptions.dialog"
    :store="fieldOptions.store"
    :field-options="fieldOptions"
    :dynamic-params="dynamicParams"
    :input-align="inputAlign"

    :name="field.name"
    :required="required"
    :readonly="readonly"
    :rules="rules"
    v-on="$listeners"
    @callback="handleLinkageData"
    @attr-callback="handleLinkageAttr"
  />
  <!-- 关联数据 -->
  <ibps-linkdata
    v-else-if="fieldType==='linkdata'"
    v-model="dataModel"
    :label="field.label"
    :desc="field.desc"
    :desc-position="descPosition"
    :placeholder="placeholder"
    :multiple="multipleSelect"
    :template-key="fieldOptions.linkdata"
    :store="fieldOptions.store||'id'"
    :dynamic-params="dynamicParams"
    :input-align="inputAlign"

    :value-key="valueKey"
    :label-type="labelType"
    :label-key="labelKey"

    :name="field.name"
    :required="required"
    :readonly="readonly"
    :rules="rules"
    v-on="$listeners"
    @callback="handleLinkageData"
    @attr-callback="handleLinkageAttr"
  />

  <!-- 地址 -->
  <ibps-address
    v-else-if="fieldType==='address'"
    v-model="dataModel"
    :label="field.label"
    :desc="field.desc"
    :desc-position="descPosition"
    :placeholder="placeholder"
    :top="fieldOptions.top"
    :top-val="addressTopVal"
    :level="fieldOptions.level"
    :has-street="fieldOptions.is_street"
    :input-align="inputAlign"

    :name="field.name"
    :required="required"
    :readonly="readonly"
    :rules="rules"
    v-on="$listeners"
  />

  <!-- 签名 -->
  <ibps-signature
    v-else-if="fieldType==='signature'"
    v-model="dataModel"
    :label="field.label"
    :desc="field.desc"
    :desc-position="descPosition"
    :placeholder="placeholder"
    :height="height"

    :name="field.name"
    :required="required"
    :readonly="readonly"
    :rules="rules"
    v-on="$listeners"
  />
  <!-- 图片 -->
  <ibps-image
    v-else-if="fieldType==='image'"
    v-model="dataModel"
    :label="field.label"
    :desc="field.desc"
    :desc-position="descPosition"

    :width="fieldOptions.width"
    :height="fieldOptions.height"
    :limit="fieldOptions.limit"
    :accept="imagesAccept"
    :file-formates="fileFormates"
    :media="fieldOptions.media"
    :tip="fieldOptions.tip"
    :max-size="maxFileSize"
    :upload-type="fieldOptions.uploadType"
    :readonly="readonly"
    :required="required"
    :rules="rules"
    v-on="$listeners"
  />

  <!-- =======================自定义控件==============================-->
  <!-- 自定义组件 -->
  <div v-else-if="fieldType==='component'">
    <component
      :is="fieldOptions.component_name"
      v-model="dataModel"
      :field="field"
      :form-data="formData"
      :readonly="readonly"
      :readonly-style="readonlyStyle"
      :code="code"
      :row="row"
      :params="params"
      :input-align="inputAlign"
      @change-data="changeFormData"
      v-on="$listeners"
    />
  </div>
  <!-- 自定义控件 -->
  <div v-else-if="fieldType==='control'">
    <component
      :is="fieldOptions.component_name"
      v-model="dataModel"
      :field="field"
      :form-data="formData"
      :readonly="readonly"
      :readonly-style="readonlyStyle"
      :code="code"
      :row="row"
      :params="params"
      :input-align="inputAlign"
      @change-data="changeFormData"
      v-on="$listeners"
    />
  </div>

  <!-- 隐藏域-->
  <input
    v-else-if="fieldType==='hidden'"
    v-model="dataModel"
    type="hidden"
    v-on="$listeners"
  >

  <!-- 描述-->
  <ibps-desc
    v-else-if="fieldType==='desc'"
    v-model="dataModel"
    :label="field.label"
    :border="fieldOptions.split_line"
    :desc="field.desc"
    :desc-position="descPosition"
    :border-style="fieldOptions.line_style"
    :input-align="inputAlign"
    v-on="$listeners"
  />

  <!-- 文本-->
  <van-field
    v-else-if="fieldType==='label'"
    v-model="dataModel"
    :label="label"
    :desc="field.desc"
    :desc-position="descPosition"
    :placeholder="placeholder"
    :type="fieldType"
    :height="fieldOptions.height"
    :input-align="inputAlign"

    :name="field.name"
    :required="required"
    readonly

    autosize
    v-on="$listeners"
  >
    <template #label>
      {{ label }}<van-icon v-if="field.desc && descPosition==='lableIcon'" name="warning" class="ibps-dialog-icon" @click="showDesc(label,field.desc)" />
    </template>
  </van-field>
  <!-- 链接 -->
  <ibps-hyperlink
    v-else-if="fieldType==='hyperlink'"
    :label="label"
    :desc="field.desc"
    :desc-position="descPosition"
    :show-type="fieldOptions.showType"
    :text="fieldOptions.text"
    :type="fieldOptions.type"
    :input-align="inputAlign"

    :link="fieldOptions.link"
    :text-type="fieldOptions.textType"
    :link-type="fieldOptions.linkType"
    :text-javascript="fieldOptions.text_javascript"
    :form-data="dynamicForm"
    preview-entrance

    :icon="fieldOptions.icon?fieldOptions.icon:''"
    v-on="$listeners"
  />

  <!-- 分割线 -->
  <van-divider
    v-else-if="fieldType==='divider'"
    :content-position="fieldOptions.content_position"
  >{{ field.label }}</van-divider>

  <!--警告-->
  <ibps-alert
    v-else-if="fieldType==='alert'"
    :title="field.label"
    :description="field.desc"
    :type="fieldOptions.type"
    :closable="fieldOptions.closable"
    :close-text="fieldOptions.close_text"
    :center="fieldOptions.center"
    :show-icon="fieldOptions.show_icon"
    :effect="fieldOptions.effect"
  />
  <!-- 流程实例-->
  <ibps-bpm-inst-his
    v-else-if="fieldType === 'bpmInstHis'"
    v-model="dataModel"
    :label="field.label"
    :desc="field.desc"
    :desc-position="descPosition"
    :height="height"
    :params="bpmInstHisParams"
    :input-align="inputAlign"

    :rules="rules"
    :name="field.name"
    :required="required"
    :readonly="readonly"
    v-on="$listeners"
  />
  <!-- 流程关联 -->
  <ibps-bpm-link
    v-else-if="fieldType === 'bpmLink'"
    :label="field.label"
    :desc="field.desc"
    :desc-position="descPosition"
    :name="field.name"
    :data="params.bpmLinkData"
    :field-options="fieldOptions"
    :input-align="inputAlign"
  />
  <!-- 审批历史-->
  <div
    v-else-if="fieldType === 'approval_history'"
  >
    <ibps-approval-history
      v-if="showApprovalHistory"
      :label="field.label"
      :desc="field.desc"
      :desc-position="descPosition"
      :task-id="params.taskId"
      :inst-id="params.instId"
      :biz-key="params.bizKey"
      :input-align="inputAlign"
    />
  </div>

  <!-- 流程图-->
  <div
    v-else-if="fieldType === 'flow_diagram'"
  >
    <ibps-flow-diagram
      v-if="showFlowDiagram"
      :label="field.label"
      :desc="field.desc"
      :def-id="params.defId"
      :task-id="params.taskId"
      :inst-id="params.instId"
      :biz-key="params.bizKey"
      :input-align="inputAlign"
    />
  </div>
  <!-- 审批意见-->
  <ibps-approval-opinion
    v-else-if="fieldType==='approval_opinion'"
    v-model="dataModel"
    :label="label"
    :desc="field.desc"
    :desc-position="descPosition"
    :placeholder="placeholder"
    :data="formOpinion"
    :layout="fieldOptions.arrangement"
    :options="fieldOptions.options"
    :has-common-statment="!!(fieldOptions.common_statment === true || fieldOptions.common_statment === 'true')"
    :height="fieldOptions.height"

    :name="field.name"
    :required="required"
    :readonly="readonly"

    autosize
    clearable
  />

  <span v-else>未支持控件类型[{{ fieldType }}]</span>
</template>
<script>
import Vue from 'vue'
import { getByKey, queryDataTable } from '@/api/platform/data/dataTemplate'
import ActionUtils from '@/utils/action'
import fecha from '@/utils/fecha'
import FormOptions from '../constants/formOptions'
import FormUtils from '../utils/formUtil'
import { fileTypes as FILE_TYPES, accept as ACCEPT } from '@/business/platform/file/constants/fileTypes'
const _import = require('@/utils/util.import.' + process.env.NODE_ENV)

export default {
  inject: ['dynamicForm'],
  props: {
    value: {
      type: [String, Number, Boolean, Array, Object, Date]
    },
    formData: [Object, Array], // 所有字段数据,(包含主主子表)

    field: {
      type: Object,
      required: true
    },
    required: {
      type: Boolean,
      default: false
    },
    rules: {
      type: Array
    },
    readonly: {
      type: Boolean,
      default: false
    },
    readonlyStyle: {
      type: String,
      default: 'text'
    },
    code: String, // 表名
    row: [String, Number], // 子表行数
    params: {
      type: Object
    },
    formOpinion: Array,
    descPosition: String
  },
  data() {
    return {
      dataModel: this.value,
      ajaxOptions: [],
      dataTemplate: {}
    }
  },
  computed: {
    fieldType() {
      return this.field.field_type
    },
    fieldOptions() {
      return this.field.field_options || {}
    },
    dateDataModel: {
      get() {
        return this.formatDate(this.value)
      },
      set(value) {
        this.dataModel = value
      }
    },
    numberDataModel: {
      get() {
        if (this.$utils.isEmpty(this.dataModel)) { return 0 }
        return Number(this.dataModel)
      },
      set(value) {
        this.dataModel = value
      }
    },

    label() {
      if (this.$utils.isNotEmpty(this.fieldOptions.units)) {
        return this.field.label + '(' + this.fieldOptions.units + ')'
      }
      return this.field.label
    },
    inputAlign() {
      return this.params && this.$utils.isNotEmpty(this.params.inputAlign) ? this.params.inputAlign || 'left' : 'left'
    },
    // 自适应内容高度
    autosize() {
      let autosize = this.fieldOptions.autosize
      if (this.fieldOptions.autosize && (this.fieldOptions.min_rows || this.fieldOptions.max_rows)) {
        const rows = {}
        rows.minHeight = this.fieldOptions.min_rows ? this.fieldOptions.min_rows * 24 : null
        rows.maxHeight = this.fieldOptions.max_rows ? this.fieldOptions.max_rows * 24 : null
        autosize = rows
      }
      return autosize
    },
    // 日期格式
    dateFormat() {
      if (this.field.field_type === 'currentDate') {
        return FormOptions.t.DATE_FORMATS['date']
      } else if (this.field.field_type === 'currentTime') {
        return FormOptions.t.DATE_FORMATS['time']
      } else {
        if (this.fieldOptions['datefmt_type'] && this.fieldOptions['datefmt_type'] !== 'custom') {
          return FormOptions.t.DATE_FORMATS[this.fieldOptions['datefmt_type']] || FormOptions.t.DATE_FORMATS['date']
        } else {
          return this.fieldOptions['datefmt'] || FormOptions.t.DATE_FORMATS['date']
        }
      }
    },
    /**
     * 单选、多选、下拉等选项
     */
    dataOptions() {
      return this.fieldOptions['options'] || this.ajaxOptions
    },
    /**
     * 其他选项的值
     */
    otherOptionValue: {
      get() {
        const otherName = this.fieldOptions['option_other_id']
        if (this.$utils.isEmpty(otherName)) return
        return this.models[otherName] || ''
      },
      set(value) {
        const otherName = this.fieldOptions['option_other_id']
        if (this.$utils.isEmpty(otherName)) return
        this.$emit('change-data', otherName, value)
      }
    },
    /**
     *  占位符
     */
    placeholder() {
      return !this.readonly ? this.fieldOptions['placeholder'] : ''
    },
    /**
     * 下拉占位符
     */
    selectPlaceholder() {
      return !this.readonly ? (this.fieldOptions['include_blank_value'] || this.fieldOptions['placeholder']) : ''
    },
    /**
     * 最大文件上传
     */
    maxFileSize() {
      if (this.$utils.isNotEmpty(this.fieldOptions.max_file_size)) {
        return this.fieldOptions.max_file_size * 1024 * 1024
      } else if (this.$utils.isNotEmpty(this.fieldOptions.size)) {
        const size = parseFloat(this.fieldOptions.size)
        return size * 1024 * 1024
      }
      return 100 * 1024 * 1024 // 最大100M
    },
    /**
     * 最大文件个数
     */
    fileQuantity() {
      const fileQuantity = this.fieldOptions.max_file_quantity
      if (this.$utils.isNotEmpty(fileQuantity) && (fileQuantity !== '-1' || fileQuantity !== -1)) {
        return parseInt(fileQuantity, 10)
      }
      return null
    },

    /**
     * 文件允许类型
     */
    fileAccept() {
      const mediaType = this.fieldOptions.media_type
      if (this.$utils.isEmpty(mediaType)) { return '*' }
      return ACCEPT[mediaType] || '*'
    },
    imagesAccept() {
      const accept = this.fieldOptions.accept
      if (this.$utils.isEmpty(accept)) { return ACCEPT['images'] }
      if (accept === 'custom') {
        return this.fieldOptions.media
      }
      return accept
    },
    /**
     * 文件格式
     */
    fileFormates() {
      const mediaType = this.fieldOptions.media_type
      if (this.$utils.isEmpty(mediaType)) { return [] }
      let media = FILE_TYPES[mediaType]
      if (this.$utils.isEmpty(media)) {
        media = (this.fieldOptions.media || '').split(',')
      }
      return media.map((v) => {
        return '.' + v
      })
    },
    /**
     * 绑定ID
     */
    bindId() {
      const bindId = this.fieldOptions['bind_id']
      if (this.$utils.isEmpty(bindId)) { return '' }
      return this.formData[bindId] || ''
    },
    /**
     * 是否多选[字符串型]
     */
    multipleSelect() {
      return this.$utils.toBoolean(this.fieldOptions['multiple'] === 'Y', true)
    },
    /**
     * 是否多选
     */
    multiple() {
      return this.$utils.toBoolean(this.fieldOptions['multiple'], true)
    },
    /**
     * 高度
     */
    height() {
      return this.fieldOptions.height ? parseInt(this.fieldOptions.height, 10) : null
    },
    /**
     * 地址最顶值
     */
    addressTopVal() {
      return FormUtils.getAddressTopVal(this.fieldOptions)
    },
    // 是否显示审批历史
    showApprovalHistory() {
      if (this.params.defId && this.params.instId && this.params.bizKey) {
        return false
      }
      return !!(this.params.taskId || this.params.instId || this.params.bizKey)
    },
    // 是否显示流程图
    showFlowDiagram() {
      return !!(this.params.defId || this.params.taskId || this.params.instId || this.params.bizKey)
    },
    bpmInstHisParams() {
      const filter = this.fieldOptions.filter || {}
      return {
        bpmDefScope: filter.bpmDefScope || 'all',
        bpmDefKey: filter.bpmDefKey,
        script: filter.script,
        starterScope: filter.starterScope || 'current',
        starter: filter.starter
      }
    },
    valueKey() {
      return FormUtils.getLinkValueKey(this.fieldOptions, this.models)
    },
    labelType() {
      return FormUtils.getLinkLabelType(this.fieldOptions, this.models)
    },
    labelKey() {
      return FormUtils.getLinkLabelKey(this.fieldOptions, this.models)
    },
    hasDynamicParams() {
      return FormUtils.hasLinkDynamicParams(this.fieldOptions)
    },
    dynamicParams() {
      return FormUtils.getLinkDynamicParams(this.fieldOptions, this.formData, this.code, this.row)
    },
    models() {
      if (!this.formData) return {}
      return this.$utils.isNotEmpty(this.row) ? (this.formData[this.code] ? this.formData[this.code][this.row] : this.formData) : this.formData
    },
    isValueSource() {
      return ((this.fieldType === 'radio' || this.fieldType === 'checkbox' || this.fieldType === 'select') &&
       this.fieldOptions['datasource'] === 'valuesource')
    }
  },
  watch: {
    value: {
      handler(val) {
        this.dataModel = val
      },
      deep: true
    },
    dataModel: {
      handler(val) {
        this.$emit('update:value', val)
      },
      deep: true
    },
    dynamicParams: {
      handler(val, oldVal) {
        if (val !== oldVal && this.isValueSource) {
          this.loadAjaxOptions()
        }
      },
      deep: true
    }
  },
  created() {
    if (this.isValueSource) {
      this.fieldOptions['options'] = null
      getByKey({
        dataTemplateKey: this.fieldOptions['value_source']
      }).then(response => {
        this.dataTemplate = this.$utils.parseData(response.data)
        this.loadAjaxOptions()
      }).catch(() => {
      })
    }
    if (this.fieldType === 'component' || this.fieldType === 'control') {
      const component = _import(this.fieldOptions.component_url)
      if (component) {
        Vue.component(this.fieldOptions.component_name, component)
      }
    }
  },
  methods: {
    showDesc(title, message) {
      ActionUtils.descDialog({ title, message })
    },
    getValuesourceParams(template, dataTemplate) {
      const formParams = {}
      const responseData = JSON.parse(JSON.stringify(template))
      responseData.datasetKey = dataTemplate.datasetKey
      responseData.unique = this.valueKey
      responseData['key'] = this.fieldOptions['value_source']
      responseData['dynamic_params'] = this.dynamicParams
      formParams['response_data'] = JSON.stringify(responseData)
      formParams['filter_condition_key'] = ''
      return ActionUtils.formatParams(formParams)
    },
    loadAjaxOptions() {
      if (this.$utils.isEmpty(this.dataTemplate)) {
        return
      }
      const template = this.dataTemplate.templates[0]
      queryDataTable(this.getValuesourceParams(template, this.dataTemplate), false).then(resp => {
        const data = resp.data || {}
        const dataResult = data.dataResult || []
        const options = dataResult.map(item => {
          return {
            val: item[this.valueKey],
            label: item[this.labelKey]
          }
        })
        this.ajaxOptions = options
      })
    },
    formatDate(value) {
      if (this.$utils.isEmpty(value)) return ''
      if (value instanceof Date) {
        return fecha.format(value, this.dateFormat)
      } else {
        try {
          return fecha.format(this.parseFormatDate(value, this.dateFormat), this.dateFormat)
        } catch (error) {
          return value
        }
      }
    },
    /**
     * 处理格式错误的bug
     */
    parseFormatDate(time, cFormat) {
      let d = fecha.parse(time, cFormat || 'yyyy-MM-dd')
      if (d) return d
      const dateFormat = ['yyyy-MM-dd HH:mm:ss', 'yyyy-MM-dd', 'yyyy-MM', 'HH:mm:ss', 'HH:mm']
      for (let i = 0; i < dateFormat.length; i++) {
        d = fecha.parse(time, dateFormat[i])
        if (d) return d
      }
      return time
    },
    getBindId: function() {
      return this.fieldOptions['bind_id'] || ''
    },

    // ===========处理联动字段
    // 选择器存储格式-绑定标识
    selectorBindCallback(data, type) {
      const linkLinkage = this.fieldOptions['bindFiled'] // 绑定字段
      let bind = this.fieldOptions['bind'] // 获取作为绑定字段属性值得属性
      if (type === 'role') {
        bind = 'roleAlias'
      }
      if (this.$utils.isEmpty(linkLinkage) || this.$utils.isEmpty(data)) { return }
      const field = linkLinkage
      const fieldObj = field ? field.split('.') : []// 改变的字段
      const selectorData = JSON.parse(JSON.stringify(data))
      const targetValues = []
      selectorData.forEach(s => {
        targetValues.push(s[bind])
      })
      const targetString = targetValues.join(',')
      if (this.$utils.isNotEmpty(fieldObj)) {
        const fieldName = fieldObj.length > 1 ? fieldObj[1] : fieldObj[0]
        if (this.$utils.isNotEmpty(fieldName) && this.models.hasOwnProperty(fieldName)) {
          this.changeFormData(fieldName, targetString || '')
        }
      }
    },
    /**
     * 联动数据
     */
    handleLinkageData(selectedData) {
      if (this.multipleSelect || this.$utils.isEmpty(selectedData)) {
        return
      }
      const linkLinkage = this.fieldOptions['link_linkage']

      if (this.$utils.isEmpty(linkLinkage)) { return }
      const data = selectedData[0]
      for (let i = 0; i < linkLinkage.length; i++) {
        const item = linkLinkage[i]
        const field = item.field
        const fieldObj = field ? field.split('.') : []// 改变的字段
        if (this.$utils.isNotEmpty(fieldObj)) {
          const fieldName = fieldObj.length > 1 ? fieldObj[1] : fieldObj[0]
          if (this.$utils.isNotEmpty(fieldName) && this.models.hasOwnProperty(fieldName)) {
            this.changeFormData(fieldName, data[item.name] || '')
          }
        }
      }
    },
    /**
     *  联动属性
     */
    handleLinkageAttr(selectedData) {
      if (this.multipleSelect || this.$utils.isEmpty(selectedData)) {
        return
      }
      const linkAttr = this.fieldOptions['link_attr']
      if (this.$utils.isEmpty(linkAttr)) { return }
      const data = selectedData[0]
      for (let i = 0; i < linkAttr.length; i++) {
        const item = linkAttr[i]
        const field = item.field
        const fieldObj = field ? field.split('.') : []// 改变的字段
        if (this.$utils.isNotEmpty(fieldObj)) {
          const fieldName = fieldObj.length > 1 ? fieldObj[1] : fieldObj[0]
          if (this.$utils.isNotEmpty(fieldName) && this.models.hasOwnProperty(fieldName)) {
            this.changeFormData(fieldName, data[item.name] || '')
          }
        }
      }
    },
    getEl() {
      return this.$refs.formItem.getEl()
    },
    /**
     * 改变表单的数据
     */
    changeFormData(name, data) {
      this.$emit('change-data', name, data)
    },
    // 处理表单意见
    handleOpinion(val) {
      const option = {
        [this.field.name]: val
      }
      this.$emit('change-form-opinion', option)
    }
  }
}
</script>
<style lang="scss" scoped>
  .field-desc{
    background: #F3F3F3;
    font-size: 12px;
    color: #999999;
    line-height: 20px;
    padding:2px 0 10px 15px ;
  }
</style>
