<template>
  <div class="aos-defdoc">
    <el-select
      v-if="editable && showType === 'select'"
      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-if="!editable" class="el-form-item__content aos-form-input-text">
      {{defValueLable}}
    </div>
    <div v-if="editable && showType === 'checkbox' && multiple" class="aos-defdoc__container">
      <!-- <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox> -->
      <el-checkbox-group v-model="defValue" @change="handleCheckedChange">
        <el-checkbox v-for="item in options" :label="item.code" :key="item.code">{{item.name}}</el-checkbox>
      </el-checkbox-group>
    </div>
    <div v-if="editable && showType === 'button' && multiple" class="aos-defdoc__container">
      <el-checkbox-group v-model="defValue" @change="handleCheckedChange" size="mini">
        <el-checkbox-button v-for="item in options" :label="item.code" :key="item.code">{{item.name}}</el-checkbox-button>
      </el-checkbox-group>
    </div>
    <div v-if="editable && showType === 'checkbox' && !multiple" class="aos-defdoc__container">
       <el-radio-group v-model="defValue" @change="handleRadioChange">
        <el-radio v-for="item in options"  :label="item.code" :key="item.code">{{item.name}}</el-radio>
      </el-radio-group>
    </div>
    <div v-if="editable && showType === 'button' && !multiple" class="aos-defdoc__container">
       <el-radio-group v-model="defValue" @change="handleRadioChange" size="mini">
        <el-radio-button v-for="item in options"  :label="item.code" :key="item.code">{{item.name}}</el-radio-button>
      </el-radio-group>
    </div>
   
  </div>
</template>

<script>
import cloneDeep from 'lodash/cloneDeep'
import debounce from 'throttle-debounce/debounce';
export default {
  name: 'AosDefdoc',
  props: {
    value: {
      type: [String,Array],
      required: true,
      default: ''
    },
    // 字典组件的code,对应
    defCode: {
      type: String,
    },
    // 字典的分组
    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
    },
    noDefCode: {
      type: Boolean,
      default: false
    },
    ormCode: {
      type: String
    },
    ormName: {
      type: String
    },
    ormData: {
      type: String
    },
    ormStatus: {
      type: String
    },
    showType: {
      type: String,
      default: 'select'
    },
    // 是否外部选项
    outer: {
      type: Boolean,
      default: false
    },
    // 外部具体选项
    outerOptions: {
      type: Array,
      default: function () {
        return []
      }
    }
  },
  data () {
    return {
      options: [],
      defValue: '',
      defValueLable: '',
      firstInit: true,
      isIndeterminate: true,
      checkAll: false,
      debounceHandleChangeEmit: '',
    }
  },
  methods: {
    handleChangeEmit () {
      this.$emit('change', this.emitData, this.emitFullData)
    },
    handleCheckAllChange () {
      this.isIndeterminate = false;
    },
    handleCheckedChange (data) {
      this.defValue = data
      this.setDefValueLabel(data)
      this.handleChangeEmit()
    },
    handleRadioChange (data) {
      this.defValue = data
      this.setDefValueLabel(data)
      this.handleChangeEmit()
    },
    getOptions () {
      if (this.outer) {
        this.options = cloneDeep(this.outerOptions)
        if (this.firstInit && this.firstDefault) {
          this.setFirstDefault()
        }
        return Promise.resolve(this.outerOptions)
      } else {
        if (!this.noDefCode && !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 = "/core/api/defdoc-detail-enable/" + this.defCode
          if (this.tag) {
            url = "/core/api/defdoc-detail-by-tag/" + this.defCode + '/' + this.tag
          }
          if (this.customerUrl) {
            if (!this.noDefCode) {
              url = this.customerUrl + this.defCode
            } else {
              url = this.customerUrl
            }
          }
          return this.$optimizeHttp({
            url: url,
            method: 'get'
          }).then((res) => {
            if (this.ormStatus && res[this.ormStatus]) {
              if (this.ormData && res[this.ormData]) {
                this.options = cloneDeep(res[this.ormData])
                this.options.forEach(item => {
                  if (this.ormCode && item[this.ormCode]) {
                    item.code = item[this.ormCode]
                  }
                  if (this.ormName && item[this.ormName]) {
                    item.name = item[this.ormName]
                  }
                })
                if (this.firstInit && this.firstDefault) {
                  this.setFirstDefault()
                }
                this.firstInit = false
              }
            } else {
              if (res.status === 200) {
                this.options = cloneDeep(res.data);
                this.options.forEach(item => {
                  if (this.ormCode && item[this.ormCode]) {
                    item.code = item[this.ormCode]
                  }
                  if (this.ormName && item[this.ormName]) {
                    item.name = item[this.ormName]
                  }
                })
                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(() => {})

      }
      // }
    },
    /**
     * @description: 设置默认第一项,当有值的时候不设置
     * @param {type} none
     * @return: undefined
     */
    setFirstDefault () {
      if (this.multiple) {
        if (this.defValue.length <= 0) {
          this.defValue = []
          this.defValue.push(this.options[0].code)
        }
      } else {
        if (!this.defValue) {
          this.defValue = this.options[0].code
        }
      }
      this.handleChangeEmit()
    },
    handleDefChange (data) {
      this.defValue = data
      this.setDefValueLabel(data)
      this.handleChangeEmit()
    },
    handleVisibleChange (data) {
      this.$emit('visible-change', data)
    },
    handleRemoveTag (tag) {
      this.$emit('remove-tag', tag)
    },
    handleClear () {
      this.$emit('clear', this.defValue)
    },
    reset () {
      this.defValue = ''
      this.defValueLable = ''
    },
    handleBlur (e) {
      this.$emit('blur', e)
    },
    handleFocus (e) {
      this.$emit('focus', e)
    },
    setDefValueLabel (data) {
      window.Promise.all([this.getOptions()]).then(() => {
        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) {
        let value = this.value
        if (value) {
          this.defValue = value.split(',')
        } else {
          this.defValue = []
        }
      } else {
        this.defValue = this.value || ''
      }
      this.setDefValueLabel(this.defValue);
      this.debounceHandleChangeEmit()
    }
  },
  created () {
    this.debounceHandleChangeEmit = debounce(10, this.handleChangeEmit)
    this.init()
    this.firstInit = true
  },
  computed: {
    emitData () {
      let emitData = '';
      if (this.multiple) {
        if (this.defValue && this.defValue.length > 0) {
          this.defValue.forEach((item,index) => {
            emitData += item;
            if (index < this.defValue.length - 1) {
              emitData += ',';
            }
          });
        }
      } else {
        emitData = this.defValue;
      }
      return emitData
    },
    emitFullData () {
      let emitFullData = [];
      let options = this.options
      if (this.multiple) {
        if (this.defValue && this.defValue.length > 0) {
          this.defValue.forEach(item => {
            const data = this.$_.find(options, { code: item });
            if (data) {
              emitFullData.push(data)
            }
          });
        }
      } else {
        const data = this.$_.find(options, { code: this.defValue });
        if (data) {
          emitFullData.push(data)
        }
      }
      return emitFullData
    }
  },
  watch: {
    // defValue: function (val, oldVal) {
    //   if (this.options && this.options.length > 0 && val && !this.$_.isEqual(val, oldVal)) {
    //     window.Promise.all([this.getOptions()]).then(() => {
    //       this.setDefValueLabel(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()
      }
    },
    outer: function (val, oldVal) {
      if (!this.$_.isEqual(val, oldVal)) {
        this.init()
      }
    },
    outerOptions: function (val, oldVal) {
      if (!this.$_.isEqual(val, oldVal)) {
        this.init()
      }
    },
  }
}
</script>
