<template>
	<div class="xd-input-unit" :class="{inline: inline, is_select:selectList.length > 0, is_unit:unit}">
		<template v-if="selectList.length > 0">
			<div class="xd-input-unit__leftTips" v-if="setting.before">{{setting.before}}</div>
			<el-input
				:placeholder="placeholder['selectPlaceholder']"
				v-model="bindSelect.input"
				class="xd-input-unit__select"
				:style="{width:width}"
				:type="type"
				:disabled="disabled"
				@input="()=>{update();change()}"
				@blur="()=>{update();change()}"
			>
				<el-select
					:disabled="disabled"
					:style="{width: selectWidth}"
					v-model="bindSelect.unit"
					:slot="pos"
					placeholder="请选择"
					@change="()=>{update();change()}"
				>
					<el-option v-for="item in selectList" :label="item.label" :value="item.value" :key="item.value"></el-option>
				</el-select>
			</el-input>
			<div class="xd-input-unit__tips" v-html="setting['tips']"></div>
		</template>
		<template v-if="unit">
			<div class="xd-input-unit__leftTips" v-if="setting.before">{{setting.before}}</div>
			<el-input
				class="xd-input-unit__input"
				v-model="bindValue"
				:placeholder="placeholder['unitPlaceholder']"
				:type="type"
				:style="{width:width}"
				:disabled="disabled"
				@input="()=>{update();change()}"
				@blur="()=>{update();change()}"
			>
				<template :slot="pos">{{unit}}</template>
			</el-input>
			<div class="xd-input-unit__tips" v-html="setting['tips']"></div>
		</template>
	</div>
</template>

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

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

      setting: {
        type: Object,
        default() {
          return {
            unit: '元',
            unitPost: 'append', // prepend, append
					}
        },
      },

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

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

      placeholder: {
        type: Object,
        default() {
          return {
            unitPlaceholder: '请输入金额',
            selectPlaceholder: '请输入金额',
          }
        },
      },

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

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

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

      //自定义方法
      handleCustom: {
        type: Function || null,
        default: null
      },
			
		},
		data(){
      return {
        bindValue: '',
        bindSelect: {
          input: '',
          unit: ''
				},
        inline: true, //inline和block
        width: '200px',
        pos: '', // prepend, append
        type: '', //类性与el-input 的类型保持一致

        //默认map关系显示
        defaultMap: {
          input: 'input',
          unit: 'unit'
        },
        
        //带单位
        unit: '',
				
				//带选则单位
        selectList: [],
        selectWidth: '',
			}
		},
		
		created(){
      if (this.setting['type']) this.type = this.setting['type'];
      if (this.setting['pos']) this.pos = this.setting['pos'];
      if (this.setting['width']) this.width = this.setting['width'];
      if (this.setting['inline'] !== undefined) this.inline = this.setting['inline'];
      if (!this.$xdHelper.isPC()) this.inline = false;
      
      //单位显示
      if (this.setting['unit']) this.unit = this.setting['unit'];
      
      
      
      //单位选择
      if (this.setting['selectWidth']) this.selectWidth = this.setting['selectWidth'];
      if(this.setting['select'] &&
				this.$xdHelper.checkVarType(this.setting['select']) === 'array'
				&& this.setting['select'].length > 0
			){
   			this.selectList = this.setting['select'];
			}
			
      
      //设置默认值为空时候处理
      if (this.defaultValue !== null) {
				if (this.setting['unit']) this.bindValue = this.defaultValue;
        if (this.setting['select']) this.handleMapToList();
      }
      

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

      /**
       * @description 返回映射关系对象数据（需要自己实现）
			 * 把内部数据转化为返回数据格式
       */
      handleListToMap() {
        let temp = {};
        Object.keys(this.bindSelect).map(key =>{
          let str = this.getMap(key, false);
          if(str) {
            if(key === 'input' && this.type === 'number') temp[str] = Number(this.bindSelect[key]);
            else temp[str] = this.bindSelect[key];
					}
				});
        
        return temp;
      },

      /**
       * @description 初始化映射关系到数据列表(需要自己实现)
			 * 把默认数据转化为内部数据
       */
      handleMapToList() {
        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(){
        if (!this.required) return this.handleListToMap();
        
        //过滤条件需要自己实现
        let temp = null;
        if(this.setting.strict === true){
          if(![undefined,''].includes(this.bindSelect.input) && this.bindSelect.unit) {
            temp = true;
          }
        }else{
          if(this.bindSelect.input && this.bindSelect.unit) {
            temp = true;
          }
        }

       	

        //todo 使用自定义校验器
        if (this.useCustomRules && temp === null) return this.handleListToMap();
        
        //todo 使用简单校验器
        if (temp === null) return null;
        
        //校验成功
        return this.handleListToMap();
			},
			
			/**
			 * @description 数据改变事件
			 */
			change(){
        if (this.unit) this.$emit('onChange', this.unitType === 'number' ? Number(this.bindValue) : this.bindValue);
        else this.$emit('onChange', this.checkParams())
			},


      /**
			 * @description 双向绑定数据处理
       */
			update(){
			  let params = null;
			  if(this.unit) params = this.unitType === 'number'? Number(this.bindValue): this.bindValue;
        else params = this.checkParams();
        this.$emit('input', params);
        if (this.$parent.$options['componentName'] === 'ElFormItem') {
          this.dispatch('ElFormItem', 'el.form.change', [params]);
          this.dispatch('ElFormItem', 'el.form.blur', [params])
        }
			},
			
			
		}
  }
</script>

<style scoped lang="scss">
	.xd-input-unit {
		&.is_select {
			::v-deep .el-input-group__append,
			::v-deep .el-input-group__prepend {
				padding: 0 15px;
			}
		}
		
		&.is_unit {
			::v-deep .el-input-group__append,
			::v-deep .el-input-group__prepend {
				padding: 0 10px;
			}
		}
		
		&__tips, &__leftTips {
			padding-top: 10px;
			line-height: 22px;
			font-size: 12px;
			color: #999;
		}
		
		&.inline {
			display: flex;
			justify-content: flex-start;
			align-items: center;
			
			.xd-input-unit__leftTips {
				flex-shrink: 0;
				padding-top: 0;
				padding-right: 10px;
			}
			
			.xd-input-unit__tips  {
				flex: 1;
				padding-top: 0;
				padding-left: 10px;
			}
			
			.xd-input-unit__input {
				flex-shrink: 0;
			}
		}
		
		
	}
	
	@media screen and (max-width: 768px) {
		.xd-input-unit {
			&__tips, &__leftTips {
				padding-top: 5px;
				line-height: 22px;
				font-size: 12px;
				color: #999;
			}
			
			&__leftTips {
				padding-bottom: 5px;
			}
			
			&.inline {
				display: flex;
				justify-content: flex-start;
				align-items: center;
				flex-flow: wrap;
				justify-items: flex-start;
				
				.xd-input-unit__tips {
					flex: auto;
					width: 100%;
					padding-top: 10px;
					padding-left: 0;
					line-height: 18px;
				}
				
				.xd-input-unit__input {
					flex: 1;
					max-width: 100%;
					width: 100%;
				}
				
				.xd-input-unit__leftTips {
					flex-shrink: 0;
					padding-top: 0!important;
					padding-right: 10px;
					
				}
			}
			
			
			& ::v-deep .el-input-group__append,
			& ::v-deep .el-input-group__prepend {
				padding: 0 5px;
			}
		}
		
	}
</style>
