<template>
  <van-field
    ref="input"
    v-model="inputValue"
    :label="label"
    :name="name"
    :size="size"
    :placeholder="placeholder"
    :border="border"
    :disabled="disabled"
    :required="required"
    :clearable="clearable"
    :clickable="clickable"
    :is-link="isLink"
    :error="error"
    :error-message="errorMessage"

    :arrow-direction="arrowDirection"
    :label-class="labelClass"
    :label-width="labelWidth"
    :label-align="labelAlign"
    :input-align="inputAlign"
    :error-message-align="errorMessageAlign"
    :autosize="autosize"
    :left-icon="leftIcon"
    :right-icon="rightIcon"
    :icon-prefix="iconPrefix"
    :rules="editable?rules:null"
    readonly
    @click-input="onClick"
  >
    <template #label>
      {{ label }}<van-icon v-if="desc && descPosition==='lableIcon'" name="warning" class="ibps-dialog-icon" @click="$action.descDialog({ title:label, message:desc })" />
    </template>
    <template v-if="editable" #right-icon>
      <van-icon
        v-if="showClear"
        name="clear"
        class="van-field__clear"
        @click.native.stop="onRightIconClick"
      />
      <van-icon
        v-else
        :name="showPopup?'arrow-up':'arrow-down'"
        @click.native.stop="onClick"
      />

    </template>
    <template #input>
      <div v-if="$utils.isNotEmpty(selectedData)" class="van-field__control">
        <van-tag
          v-for="(item,index) in selectedData"
          :key="item[valueKey]+index"
          type="primary"
          class="ibps-tag-span"
          size="medium"
          plain
        >
          <field-formatter
            :label-key="showLableKey"
            :data="item"
            :template-fields="templateFields"
          />
        </van-tag>
      </div>
      <input v-else :placeholder="placeholder" class="van-field__control" readonly>
      <!-- 数据模版对话框-->
      <data-template-popup
        :visible="showPopup"
        :template-key="templateKey"
        :params="params"
        :value="selectedValue"
        :multiple="multiple"

        :left-text="leftText"
        :id-key="idKey"
        :value-key="valueKey"
        :label-key="labelKey"
        :parent-id-key="parentIdKey"
        :is-tree="isTree"
        :query-key="queryKey"
        :template-fields="templateFields"
        :dynamic-params="dynamicParams"

        @init-data="initData"
        @cancel="onCancel"
        @confirm="onConfirm"
      />

    </template>
  </van-field>
</template>

<script>
/**
 * 自定义对话框
 * 1、列表
 *
 * 2、树形
 *
 *
 */

import i18n from '@/utils/i18n' // Internationalization 国际化

import { isDef } from 'vant/lib/utils'
import FieldMixin from '@/mixins/field'
import { loadDataTemplateByKey, getDataTemplateListTemplate, buildDataTemplateFields } from '@/business/platform/data/utils'
import DataTemplatePopup from '../../data-template/template'
import FieldFormatter from '../../data-template/field-formatter'

export default {
  name: 'ibps-linkdata',
  components: {
    DataTemplatePopup,
    FieldFormatter
  },
  mixins: [FieldMixin],
  props: {
    templateKey: { // 数据模版key
      type: String,
      required: true
    },
    store: { // 存储类型 对应[多选]有效，json： json字符串,id:只存储id， array：存储数组数据 ，arrayId: 字符串类型。
      type: String,
      default: 'id',
      validator: function(value) {
        return ['json', 'id', 'array', 'arrayId'].indexOf(value) !== -1
      }
    },
    storeSeparator: { // 存储值分割符，对于设置字符串类型的分隔符
      type: String,
      default: ','
    },
    leftText: {
      type: String,
      default: i18n.t('cancel')
    },
    multiple: { // 是否多选
      type: Boolean,
      default: false
    },
    valueKey: { // 值key
      type: String
    },
    labelType: { // 文本类型
      type: String,
      default: 'first'
    },
    labelKey: { // 文本key
      type: [String, Function]
    },
    emptyText: {
      type: String,
      default: '暂无数据'
    },
    dynamicParams: Object
  },
  data() {
    return {
      dialogId: '#id#',
      dialogTitle: '#title#',
      idKey: 'id_',
      parentIdKey: '',
      isTree: false,
      queryKey: '',
      params: {},
      templateFields: {}, // 模版字段
      showPopup: false, // 弹窗
      selectedData: [], // 选中的数据，这个值是用于展示的
      selectedValue: [] // 选中的值 是valueKey的值
    }
  },
  computed: {
    showClear() {
      return this.clearable && this.$utils.isNotEmpty(this.value) && isDef(this.value) && this.editable
    },
    showLableKey() {
      return this.labelKey
    }
  },
  watch: {
    value: {
      handler() {
        if (this.$utils.isEmpty(this.value)) {
          this.selectedData = []
        }
        // 初始化数据
        this.initSelectedData()
      },
      immediate: true
    }
  },
  created() {
    // 初始化加载配置的数据
    this.loadData(this.templateKey)
  },
  methods: {
    // 加载加载配置数据
    loadData(key) {
      const params = {}
      loadDataTemplateByKey(key, params).then((data) => {
        const template = getDataTemplateListTemplate(data)

        this.templateFields = buildDataTemplateFields(data.fields)
        this.buildKey(data, template)
      }).catch((e) => {
        console.error(e)
      })
    },
    buildKey(dataTemplate, template) {
      this.idKey = dataTemplate['unique']
      this.queryKey = this.getQueryKey(template['query_columns'])
      const resultColumns = template['result_columns']
      if (this.$utils.isEmpty(resultColumns)) { return }
      // this.labelKey = resultColumns[0]['name']
      // if (dataTemplate.showType === 'tree') { // 树形
      //   this.isTree = true
      //   const displayColumns = template['display_columns']
      //   if (this.$utils.isNotEmpty(displayColumns)) {
      //     this.labelKey = displayColumns['name_key']
      //     this.idKey = displayColumns['id_key']
      //     this.parentIdKey = displayColumns['pid_key']
      //   }
      // } else if (dataTemplate.showType === 'list') {
      // this.isTree = false
      // const displayColumns = template['display_columns']
      // if (this.$utils.isNotEmpty(displayColumns)) {
      //   this.labelKey = (displayColumns[0] ? displayColumns[0]['name'] : '') || ''
      // }
      // }
    },
    initSelectedData() {
      this.selectedValue = this.getArrayValue(this.value)
    },
    getArrayValue(value) {
      if (this.$utils.isEmpty(value)) {
        return []
      }
      if (this.store === 'json') { // json
        const o = Object.prototype.toString.call(this.$utils.parseData(value)) === '[object Object]'
        try {
          const data = o ? [this.$utils.parseData(value)] : this.$utils.parseData(value)
          return data.map((d) => {
            return d[this.valueKey]
          })
        } catch (error) {
          console.error(error)
          return []
        }
      } else if (this.store === 'id') { // id
        return value.split(this.storeSeparator)
      } else if (this.store === 'arrayId') { // 数组id
        return value
      } else {
        return value.map((d) => {
          return d[this.valueKey]
        })
      }
    },
    getStoreValue(value) {
      const res = []
      if (this.store === 'json') { // json
        if (this.$utils.isEmpty(value)) {
          return ''
        }
        value.forEach(v => {
          if (this.$utils.isEmpty(v)) { return true }
          const o = {}
          o[this.valueKey] = v[this.valueKey]
          o[this.labelKey] = v[this.labelKey]
          res.push(o)
        })
        return JSON.stringify(res)
      } else if (this.store === 'id') { // id
        value.forEach(v => {
          res.push(v[this.valueKey])
        })
        return res.join(this.storeSeparator)
      } else if (this.store === 'arrayId') { // 数组id
        return value.map((d) => {
          return d[this.valueKey]
        })
      } else { // 数组
        return value || []
      }
    },
    onClick() {
      if (!this.editable) { return }
      this.initSelectedData()
      this.showPopup = true
    },
    onCancel() {
      this.showPopup = false
    },
    onConfirm(selectedData) {
      if (this.$utils.isEmpty(selectedData)) {
        this.$notify({
          type: 'warning',
          message: '请选择！'
        })
        return
      }
      this.showPopup = false

      this.selectedData = selectedData
      this.setInputValue(this.getStoreValue(selectedData))
    },
    onRightIconClick() {
      this.showClear ? this.onClear() : this.onClick()
    },
    onClear() {
      this.setInputValue(this.getStoreValue([]))
    },
    setInputValue(value) {
      const result = this.formatData(value)
      this.$emit('input', result)
      // 处理回调
      this.$nextTick(() => {
        this.$emit('callback', this.selectedData)
        this.$emit('attr-callback', this.selectedData)
      })
    },
    // 回调初始化数据
    initData(data) {
      this.selectedData = data
      this._setInputValue()
      this.$nextTick(() => {
        this.$emit('attr-callback', this.selectedData)
      })
    },
    getQueryKey(queryColumns) {
      if (this.$utils.isNotEmpty(queryColumns) && queryColumns[0]) {
        return queryColumns[0].name
      }
    },
    formatData(data) {
      if (this.$utils.isEmpty(data)) {
        return ''
      }
      if (this.store === 'json') { // json
        const resutlList = JSON.parse(this.$utils.newData(data))
        resutlList.forEach(element => {
          element[this.dialogId] = element[this.valueKey]
          element[this.dialogTitle] = element[this.labelKey]
        })
        return JSON.stringify(resutlList)
      } else if (this.store === 'id') {
        return data
      }
    }
  }
}
</script>
