<template>
	<div class="xd-input-range">
		<div class="xd-input-range__select" v-if="select.length > 0" :style="{width: selectWidth}">
			<xd-select-list
				:placeholder="selectPlaceholder"
				:default-value="bindSelect.select"
				:disabled="disabled"
				:multiple="multiple"
				:list="select"
				@change="handleBlur"
				v-model="bindSelect.select"
				clearable
				filterable
				collapse-tags
			></xd-select-list>
		</div>
		<div class="xd-input-range__input" @click="handleMouseDown" :class="{isAction: isAction, isError: isError}">
			<div class="xd-input-range__icon" v-if="icon" @click.stop><i @click.stop :class="icon"></i></div>
			<div class="xd-input-range__unit" v-else-if="unit">{{unit}}</div>
			<div class="xd-input-range__start">
				<input
					:style="{width: width}"
					:disabled="disabled"
					type="number"
					v-model="bindSelect.start"
					@focus.prevent="handleMouseDown"
					@click.stop
					@input="handleBlur"
					@blur="handleBlur"
					:placeholder="SPlaceholder"
				></input>
			</div>
			<div class="xd-input-range__to">至</div>
			<div class="xd-input-range__end">
				<input
					:style="{width: width}"
					type="number"
					:disabled="disabled"
					@focus.prevent="handleMouseDown"
					@click.stop
					@input="handleBlur"
					@blur="handleBlur"
					:placeholder="EPlaceholder"
					v-model="bindSelect.end"
				></input>
			</div>
		</div>
	</div>
</template>

<script>
  import emitter from 'element-ui/src/mixins/emitter';
  import XdSelectList from "@/components/XdSelectList";
  export default {
    name: "XdInputRange",
    components: {
      XdSelectList
		},
    mixins: [emitter],
		props:{
      defaultValue: {
        type: Object|null,
        default() {
          return []
        },
      },

      maps: {
        type: Object | null,
        default() {
          return null
        },
      },

      setting: {
        type: Object,
        default() {
          return {
            isRequire:true
          }
        },
      },

      disabled: {
        type: Boolean,
        default: false,
      },

      size: {
        type: String,
        default: 'medium', //medium / small / mini
      },

      placeholder: {
        type: Object,
        default() {
          return {
          }
        },
      },

      required: {
        type: Boolean,
        default: false,
      },

      //是否启用自定义校验器
      useCustomRules: {
        type: Boolean,
        default: false,
      },

      //数字字符串 转 数字
      isNumber: {
        type: Boolean,
        default: true,
      },

      //自定义方法
      handleCustom: {
        type: Function || null,
        default: null
      },

		},
		data(){
      return {
        bindSelect: {
          start: null,
					end: null,
					select: null,
				},


        //默认map关系显示
        defaultMap: {
          start: 'start',
          end: 'end',
          select: 'select'
        },

        isError: false,
        isAction: false,
				body: null,
        start: '',
        end: '',
        width: '100px',
        SPlaceholder: '请输入',
        EPlaceholder: '请输入',

				//select
        selectWidth: '120px',
        selectPlaceholder: '请选择',
        select: [],
        multiple: false,

				//单位
        unit: null,

				//icon
				icon: null,

				isPrice: false,
			}
		},

		created(){
      if (this.placeholder['SPlaceholder'] !== undefined) this.SPlaceholder = this.placeholder['SPlaceholder'];
      if (this.placeholder['EPlaceholder'] !== undefined) this.EPlaceholder = this.placeholder['EPlaceholder'];
      if (this.placeholder['selectPlaceholder'] !== undefined) this.selectPlaceholder = this.placeholder['selectPlaceholder'];
      if (this.setting['unit']) this.unit = this.setting['unit'];
      if (this.setting['icon']) this.icon = this.setting['icon'];
      if (this.setting['width'] !== undefined) this.width = this.setting['width'];
      if (this.setting['isPrice'] !== undefined) this.isPrice = this.setting['isPrice'];


      if (this.setting['selectWidth'] !== undefined) this.selectWidth = this.setting['selectWidth'];
      if (this.setting['selectMultiple'] !== undefined
				&& this.$xdHelper.checkVarType(this.setting['selectMultiple']) === 'boolean') this.multiple = this.setting['selectMultiple'];
      if (this.setting['select'] &&
				this.$xdHelper.checkVarType(this.setting['select']) === 'array'
			) this.select = this.setting['select'];

      //设置默认值为空时候处理
      if (this.defaultValue === null || this.defaultValue.length === 0) {
				//todo 初始化插件所使用到绑定值
      }
      //非空处理
      else {
        this.handleMapToList();
      }

      //绑定数据
      this.update();
		},

		mounted(){
      this.$nextTick(()=>{
        this.body = document.getElementsByTagName('body').item(0);
			})
		},

		methods: {
      handleMouseDown(){
        const handleEvent = (e)=>{
          let reg = /^(xd-input-range).+$/;
          e = window.event || e;
          let target = e.target || e.srcElement;
          if (!reg.test(target.className)) {
            this.isAction = false;
            this.body.removeEventListener('click', handleEvent);
          }
				};
        if(this.isAction === false) {
          this.isAction = true;
          this.body.addEventListener('click', handleEvent , false);
				}
			},

			handleBlur(){
        this.update();
			},

      /**
       * @description 返回映射关系对象数据（需要自己实现）
			 * 把内部数据转化为返回数据格式
       */
      handleListToMap() {
        let startFlag = this.bindSelect.start === undefined || this.bindSelect.start === '';
        let endFlag = this.bindSelect.end === undefined || this.bindSelect.end === '';

        if ((this.unit || this.icon) && this.select.length > 0){
          if(this.setting.isRequire){
            if (startFlag
              || endFlag
              || (!this.bindSelect.select || this.bindSelect.select.length === 0)
            ) {
              return null
            }
          }
          
          let temp = {};
          let start = this.getMap('start', false);
          if (start) temp[start] = this.bindSelect.start;
          let end = this.getMap('end', false);
          if (end) temp[end] = this.bindSelect.end;
          let select = this.getMap('select', false);
          if (select) temp[select] = this.bindSelect.select;
          if (this.isPrice) {
            temp[start] = this.$xdHelper.multiplyFloatNumber(temp[start], 100)
            temp[end] = this.$xdHelper.multiplyFloatNumber(temp[end], 100)
          }
          return temp
				}
        if(this.unit || this.icon) {
          if (startFlag || endFlag) {
            return null
          }
          let temp = {};
          let start = this.getMap('start', false);
          if(start) temp[start] = this.bindSelect.start;
          let end = this.getMap('end', false);
          if (end) temp[end] = this.bindSelect.end;
          if(this.isPrice) {
            temp[start] = this.$xdHelper.multiplyFloatNumber(temp[start], 100)
            temp[end] = this.$xdHelper.multiplyFloatNumber(temp[end], 100)
					}
          return temp
				}

      },

      /**
       * @description 初始化映射关系到数据列表(需要自己实现)
			 * 把默认数据转化为内部数据
       */
      handleMapToList() {
        if (this.unit || this.icon) {
          if (this.$xdHelper.checkVarType(this.defaultValue) === 'object') {
            Object.keys(this.defaultValue).map(key => {
              let keyStr = this.getMap(key, true);
              if (keyStr) {
                this.$set(this.bindSelect, keyStr, this.defaultValue[key]);
              }
            });
          }
				}
      },

      //插件系统方法///////////////////////////////////////
      /**
       * @description 获取Maps中键与值
       * @param type {boolean} 返回值类型  true=>获取键  false=>值
       * @param keyword {string} 查找关键字
       * @return {null|string} null=>未找到  string=>找到
       */
      getMap(keyword, type) {
        let maps = null;
        let value = null;
        if (this.maps !== null && !this.$xdHelper.isEmpty(this.maps)) {
          maps = this.$xdHelper.cloneDeep(this.maps);
        }

        //先默认maps关系中找
        Object.keys(this.defaultMap).map(ky => {
          //获取键
          if (type) {
            if (this.defaultMap[ky] === keyword) {
              value = ky;
            }
          } else {
            if (this.defaultMap[keyword]) value = this.defaultMap[keyword];
          }
        });

        //无外部map关系并且在默认关系表中无键
        if (value === null && maps === null) {
          //console.log('1')
          return null;
        }

        //无外部map关系并且在默认关系表中键
        if (value !== null && maps === null) {
          //console.log('2', value)
          return value;
        }

        //有外部map关系进行查找
        Object.keys(maps).map(ky => {
          //获取键
          if (type) {
            if (maps[ky] === keyword) {
              value = ky;
            }
          } else {
            if (this.maps[keyword]) value = this.maps[keyword];
          }
        });
        //console.log('3')
        return value;

      },


      /**
			 * @description 需要校验检查参数是正确处理方法
       */
			checkParams(){
        return this.handleListToMap();
			},


      /**
			 * @description 双向绑定数据处理
       */
			update(){
        this.$emit('input', this.checkParams());
        if (this.$parent.$options['componentName'] === 'ElFormItem') {
          this.dispatch('ElFormItem', 'el.form.change', [this.checkParams()]);
          this.dispatch('ElFormItem', 'el.form.blur', [this.checkParams()])
          this.isError = !!this.$parent.validateMessage;
        }
			},


		}
  }
</script>

<style scoped lang="scss">
	.xd-input-range {
		display: flex;
		justify-content: flex-start;
		align-content: center;
		align-items: center;


		&__select {
			margin-right: 10px;
			flex-shrink: 0;
		}

		&__input {
			flex: 1;
			cursor: pointer;
			display: flex;
			justify-content: flex-start;
			align-items: center;
			flex-flow: nowrap;
			height: 36px;
			border-style: solid;
			border-width: 1px;
			border-color: #dcdfe6;
			box-sizing: border-box;
			border-radius: 4px;

			&:hover {
				transition: border-color .2s;
				border-color: #C2C5CB;
			}

			&.isAction {
				transition: border-color .2s;
				border-color: $blue;
			}

			&.isError {
				transition: border-color .2s;
				border-color: $red;
			}

			& input {
				outline: none;
				border: none;
				width: 100px;
				padding: 0 5px;
				font-size: 13px;
				line-height: 34px;
				text-align: center;
				border-radius: 0 4px 4px 0;
			}
		}

		&__to {
			padding: 0 5px;
			font-size: 14px;
			color: #666;
			height: 100%;
		}

		&__start, &__end {
			height: 100%;
			display: flex;
			justify-content: flex-start;
			align-items: center;
		}

		&__unit,&__icon {
			flex-shrink:0;
			padding: 0 10px;
			background: #f8f8f8;
			border-radius: 4px 0 0 4px;
			font-size: 14px;
			color: #666;
			height: 100%;
		}



	}

	@media screen and (max-width: 768px) {
		.xd-input-range {
			width: 100%;
			flex-flow: wrap;
			overflow-x:auto;
			padding-bottom: 8px;

			&__select {
				margin-right: 0;
				width: 100% !important;
				flex-shrink: 0;
				margin-bottom: 10px;
			}

			& > div {

			}

		}
	}
</style>
