<template>
  <div class="aos-rule-defdoc">
    <el-select
      v-if="editable"
      ref="aosRuleDefdoc"
      v-model="defValue"
      filterable
      :clearable="clearable"
      :disabled="disabled"
      :multiple="multiple"
      :multipleLimit="multipleLimit"
      :collapse-tags="collapseTags"
      :placeholder="placeholder"
      @change="handleDefChange"
      @visible-change="handleVisibleChange"
      @clear="handleClear"
      @blur="handleBlur"
      @focus="handleFocus"
      @remove-tag="handleRemoveTag">
      <el-option
        v-for="item in options"
        :key="item.id"
        :label="item.dictItemName"
        :value="item.dictItemValue">
      </el-option>
    </el-select>
    <div v-else class="el-form-item__content aos-form-input-text">
      {{defValueLable}}
    </div>
  </div>
</template>

<script>
import cloneDeep from 'lodash/cloneDeep'
export default {
  name: 'aosRuleDefdoc',
  props: {
    value: {
      type: [String, Array],
      required: true,
      default: ''
    },
    // 字典组件的code,对应
    defCode: {
      type: String,
      required: true
    },
    editable: {
      type: Boolean,
      required: true,
      default: true
    },
    debounce: {
      type: Number,
      default: 300
    },
    // 参照下拉列表的位置
    placement: {
      type: String,
      default: 'bottom-start'
    },
    // 提示
    placeholder: {
      type: String,
      default: '请选择'
    },
    // 是否可清空
    clearable: {
      type: Boolean,
      default: true
    },
    // 禁用状态
    disabled: {
      type: Boolean,
      default: false
    },
    multiple: {
      type: Boolean,
      default: false
    },
    // 多选限制
    multipleLimit: {
      type: Number,
      default: 0
    },
    collapseTags: {
      type: Boolean,
      default: false
    },
    // 是否默认选中返回的第一项值
    firstDefault: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      options: [],
      defValue: '',
      defValueLable: ''
    }
  },
  methods: {
    getOptions () {
      if (!this.defCode) {
        this.$message({
          type: 'error',
          message: '规则字典组件的defCode不能为空'
        })
        return
      }
      // const dict = this.$storage.get('dictRule', 'session') || {}
      // if (dict && Object.keys(dict).length > 0 && dict[this.defCode]) {
      //   this.options = dict[this.defCode]
      //   if (this.firstDefault) {
      //     this.setFirstDefault()
      //   }
      //   return window.Promise.resolve();
      // } else {
        return this.$optimizeHttp({
          url: '/riskcontrol/api/findByDictTypeCode',
          method: 'post',
          data: {
            dictTypeCode: this.defCode
          }
        }).then((res) => {
          if (res.status === 200) {
            this.options = cloneDeep(res.data.data)
            if (this.firstDefault) {
              this.setFirstDefault()
            }
            // dict[this.defCode] = res.data.data
            // this.$storage.add('dictRule', dict, 'session')
          } else {
            this.$message({
              type: 'error',
              message: res.data.title
            })
          }
        }).catch(() => {
          this.$message({
            type: 'error',
            message: '请求字典数据出错'
          })
        })
      // }
    },
    /**
     * @description: 设置默认第一项,当有值的时候不设置
     * @param {type} none
     * @return: undefined
     */
    setFirstDefault () {
      if (this.multiple) {
        if (this.defValue.length <= 0) {
          this.defValue = []
          this.defValue.push(this.options[0].dictItemValue)
          this.$emit('change', this.defValue, this.options[0])
        }
      } else {
        if (!this.defValue) {
          this.defValue = this.options[0].dictItemValue
          this.$emit('change', this.defValue, this.options[0])
        }
      }
    },
    handleDefChange (data) {
      this.setDefValue(data)
      let emitData = ''
      let itemData = ''
      if (this.multiple) {
        itemData = []
        if (data && data.length > 0) {
          data.forEach(item => {
            emitData += ','
            emitData += item
            itemData.push(this.$_.find(this.options, { dictItemValue: item }))
          })
        }
      } else {
        emitData = data
        itemData = this.$_.find(this.options, { dictItemValue: data })
      }
      this.$emit('change', emitData, itemData)
    },
    handleVisibleChange (data) {
      this.$emit('visible-change', data)
    },
    handleRemoveTag (tag) {
      this.$emit('remove-tag', tag)
    },
    handleClear () {
      this.$emit('clear', this.defValue)
    },
    handleBlur (e) {
      this.$emit('blur', e)
    },
    handleFocus (e) {
      this.$emit('focus', e)
    },
    setDefValue (data) {
      if (this.multiple && data && data.length > 0) {
        this.defValueLable = ''
        const allSourceData = []
        data.forEach(item => {
          const sourceData = this.$_.find(this.options, { dictItemValue: item })
          if (sourceData) {
            this.defValueLable += ','
            this.defValueLable += sourceData.dictItemName
          }
          allSourceData[item] = sourceData
        })
        this.$emit('setDefValue', data, allSourceData)
      } else {
        const sourceData = this.$_.find(this.options, { dictItemValue: data })
        if (sourceData) {
          this.defValueLable = sourceData.dictItemName
        }
        this.$emit('setDefValue', data, sourceData)
      }
    },
    init () {
      if (this.multiple) {
        if (this.value) {
          this.defValue = this.value.split(',')
        } else {
          this.defValue = []
        }
      } else {
        this.defValue = this.value || ''
      }
      window.Promise.all([this.getOptions()]).then(() => {
        this.setDefValue(this.defValue);
      });
    }
  },
  created () {
    this.init()
  },
  watch: {
    defValue: function (val, oldVal) {
      if (this.options && this.options.length > 0 && val && !this.$_.isEqual(val, oldVal)) {
        this.setDefValue(val)
      }
    },
    defCode: function (val, oldVal){
      if (val && val !== oldVal) {
        this.init()
      }
    },
    firstDefault (val, oldVal) {
      if (val) {
        this.getOptions()
      }
    },
    value: function (val, oldVal) {
      if (!this.$_.isEqual(val, oldVal)) {
        this.init()
      }
    }
  }
}
</script>
