<template>
  <div class="aos-defdoc">
    <el-select
      v-if="editable"
      ref="aosDefdoc"
      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.code"
        :label="item.name"
        :value="item.code">
      </el-option>
    </el-select>
    <div v-else class="el-form-item__content aos-form-input-text">
      {{defValueLable}}
    </div>
  </div>
</template>

<script>
export default {
  name: 'AosDefdoc',
  props: {
    value: {
      type: [String,Array],
      required: true,
      default: ''
    },
    // 字典组件的code,对应
    defCode: {
      type: String,
      required: true
    },
    // 字典的分组
    tag: {
      type: String,
      default: ''
    },
    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
    },
    customerUrl: {
      type: String
    }
  },
  data () {
    return {
      options: [],
      defValue: '',
      defValueLable: '',
      firstInit: true
    }
  },
  methods: {
    getOptions () {
      if (!this.defCode) {
        this.$message({
          type: 'error',
          message: '字典组件的defCode不能为空'
        })
        return
      }
      // let dict = this.$storage.get('dict', 'session') || {}
      // if (dict && Object.keys(dict).length > 0 && dict[this.defCode]) {
      //   this.options = dict[this.defCode]
      //   if (this.firstInit && this.firstDefault) {
      //     this.setFirstDefault()
      //     this.firstInit = false
      //   }
      //   return window.Promise.resolve();
      // } else {
        let url = "/ap/defdoc-detail-enable/" + this.defCode
        if (this.tag) {
          url = "/ap/defdoc-detail-by-tag/" + this.defCode + '/' + this.tag
        }
        if (this.customerUrl) {
          url = this.customerUrl + this.defCode
        }
        return this.$optimizeHttp({
          url: url,
          method: 'get'
        }).then((res) => {
          if (res.status === 200) {
            this.options = res.data;
            if (this.firstInit && this.firstDefault) {
              this.setFirstDefault()
            }
            this.firstInit = false
            // dict[this.defCode] = res.data
            // this.$storage.add('dict', 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].code)
          this.$emit('change', this.defValue)
        }
      } else {
        if (!this.defValue) {
          this.defValue = this.options[0].code
          this.$emit('change', this.defValue)
        }
      }
    },
    handleDefChange (data) {
      this.setDefValue(data)
      let emitData = '';
      if (this.multiple) {
        if (data && data.length > 0) {
          data.forEach((item,index) => {
            emitData += item
            if (index < data.length - 1) {
              emitData += ','
            }
          })
        }
      } else {
        emitData = data
      }
      this.$emit('change', emitData)
    },
    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 = ""
        data.forEach((item, index) => {
          const sourceData = this.$_.find(this.options, { code: item })
          if (sourceData) {
            this.defValueLable += sourceData.name
            if (index < data.length - 1) {
              this.defValueLable += ',';
            }
          }
        })
      } else {
        const sourceData = this.$_.find(this.options, { code: data })
        if (sourceData) {
          this.defValueLable = sourceData.name
        } else {
          this.defValueLable = ''
        }
      }
    },
    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()
    this.firstInit = true
  },
  watch: {
    defValue: function (val, oldVal) {
      if (this.options && this.options.length > 0 && val && !this.$_.isEqual(val, oldVal)) {
        window.Promise.all([this.getOptions()]).then(() => {
          this.setDefValue(this.defValue);
        });
      }
    },
    value: function (val, oldVal) {
      if (!this.$_.isEqual(val, oldVal)) {
        this.init()
      }
    },
    defCode: function (val, oldVal) {
      if (!this.$_.isEqual(val, oldVal)) {
        this.init()
      }
    },
    tag: function (val, oldVal) {
      if (!this.$_.isEqual(val, oldVal)) {
        this.init()
      }
    },
    customerUrl: function (val, oldVal) {
      if (!this.$_.isEqual(val, oldVal)) {
        this.init()
      }
    },
  }
}
</script>
