<template>
	<div class="xd-multiple-input" :style="[boxComp]">
    <div
      class="xd-multiple-input__after"
      v-if="setting.after"
      v-html="setting.after"
    ></div>
		<div
			class="xd-multiple-input__item"
			v-for="(item,index) in inputs"
			:key="index"
			:class="{
				multipleOuter: item['multiple'] && item.type === 'select',
				multipleUnit: item['multiple'] && item.unit,
				one: inputs.length ===1
			}"

		>
			<template v-if="item.type === 'input'">
				<div>
					<el-input
						class="xd-multiple-input__item-input"
						v-model="item['value']"
						type="text"
						:placeholder="item['placeholder']"
						:disabled="disabled"
						clearable
						@input="()=>{update();change();}"
						@blur="()=>{update();change();}"
					>
						<span slot="append" v-if="item['unit']" v-html="item['unit']"></span>
					</el-input>
				</div>
			</template>
			<template v-if="item.type === 'select'">
				<div class="xd-multiple-input__item-select">
					<xd-select-list
						:class="{multiple: item['multiple']}"
						clearable
						:collapse-tags="collapseTags"
						v-model="item['value']"
						:placeholder="item['placeholder'] || '-请选择-'"
						:default-value="item['value']"
						:list="item['list']"
						:multiple="item['multiple']"
						:disabled="disabled"
						@change="()=>{update();change();}"
						@clear="()=>{update();change();}"
					></xd-select-list>
					<span v-if="item['unit']" v-html="item['unit']"></span>
				</div>
			</template>
      <template v-if="item.type === 'time'">
        <el-time-select
          class="xd-time-select"
          v-model="item['value']"
          :picker-options="item['options']"
          :placeholder="item['placeholder'] || '请选择时间'"
          :value-format="item['formatValue']"
          @change="()=>{update();change();}"
          @clear="()=>{update();change();}"
          :disabled="disabled"
        >
        </el-time-select>
        <span class="span" v-if="item['unit']" v-html="item['unit']"></span>
      </template>
      <template v-if="item.type === 'date'">
        <el-date-picker
          v-model="item['value']"
          :picker-options="item['options']"
          :placeholder="item['placeholder'] || '请选择时间'"
          :value-format="item['formatValue']"
          :format="item['format']"
          :disabled="disabled"
        >
        </el-date-picker>
      </template>
		</div>
    <div
      class="xd-multiple-input__before"
      v-if="setting.before"
      v-html="setting.before"
    ></div>
	</div>
</template>

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

      setting: {
        type: Object,
        default() {
          return {
            inputs: [
              {type: 'input', key: 'input', unit: '%'},
              {type: 'input', key: 'price', unit: '元', isPrice: true},
              {
                type: 'select',
								key: 'select',
								list: [
                  {"label": "万利达集团", "value": 1},
                  {"label": "深圳万利达", "value": 2},
                  {"label": "移动通信设备有限公司", "value": 3},
                  {"label": "味多美", "value": 4},
								],
								multiple: true},
            ],
					}
        },
      },

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

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

    computed:{
      boxComp(){
        if(!this.$xdHelper.isPC()) return {}
        if(this.row === 1) return {height: this.row * this.itemHeight + 'px' }
        if(this.row > 1) return {height: (this.row * this.itemHeight + (this.row-1) * 10) + 'px' }
      }
    },

		data(){
      return {
        inputs: [],
        collapseTags: true,
        value2:new Date(),
        value1:new Date(),
        boxHeight: 0,
        row : 0,
        status: false,
        itemHeight: 36,
			}
		},

		created(){
      this.collapseTags = this.$xdHelper.isPC();
      let inputs = [];
      if(this.setting.inputs && this.$xdHelper.checkVarType(this.setting.inputs) === 'array') {
        inputs = this.setting.inputs.map(item=>{
          if(item.type === 'input') {
            let isPrice = item.isPrice === undefined ? false : item.isPrice;
            return {...item, isPrice, value: ''}
					}
          if(item.type === 'select'){
            let multiple = item.multiple === undefined ? false : item.multiple;
            return { ...item, multiple, value: multiple? []:''}
					}
          if(item.type === 'time') {
            let formatValue = '-';
            if(!item['formatValue']) item['formatValue'] = formatValue
            return {
              ...item,
              options: item['options'] || {start: '00:00', step: '00:30', end: '23:59'},
              formatValue:item['formatValue']
            }
          }
				})
			}


      if(this.defaultValue !== undefined && this.defaultValue !== null) {
        if(this.$xdHelper.checkVarType(this.defaultValue) === 'object') {
          inputs = inputs.map(item=>{
            if (item.type === 'select') {
              let multiple = item.multiple === undefined ? false : item.multiple;
              let value = multiple ? [] : '';
              if(this.defaultValue[item.key]) value = this.defaultValue[item.key];
              return {
                ...item,
                value
              }
            }

            if (item.type === 'input') {
              if (item.isPrice && this.defaultValue[item.key]) item.value = this.$xdHelper.divisionFloatNumber(this.defaultValue[item.key], 100);
              else item.value = this.defaultValue[item.key];
              return item
            }

            if(item.type === 'time') {
              let formatValue = '-';
              if(!item['formatValue']) item['formatValue'] = formatValue;
              item.value =  this.defaultValue[item.key];
              return {
                ...item,
                value: (item.value && item.value.replace(item['formatValue'], ':')) || '',
                options: item['options'] || {start: '00:00', step: '00:30', end: '23:59'},
                formatValue:item['formatValue']
              }
            }
          });
        }
        else if(inputs.length === 1) {
          inputs[0].value = this.defaultValue;
        }
      }
      this.inputs = inputs;

      //绑定数据
      this.update();
      window.onresize = ()=>{
        this.row = Math.floor(this.$el.getBoundingClientRect().height/this.itemHeight);
        console.log(this.row)
      }
		},

    mounted() {
      this.row = Math.floor(this.$el.getBoundingClientRect().height/this.itemHeight);
      this.status = true;
    },

    methods: {
      /**
			 * @description 需要校验检查参数是正确处理方法
       */
			checkParams(){
			  if(this.required) return this.handleRequired();
			  else return this.getData();
			},

      handleRequired(){
			  let temp = false;
			  Object.keys(this.getData()).map(key=>{
			  	if(this.$xdHelper.checkVarType(this.getData()[key] === 'array')
						&& this.getData()[key].length === 0
					) temp = true;
					else {
					  if(this.getData()[key] === undefined) temp = true;
					}
				});
				if(!temp) return this.getData();
				else return null;
			},

			getData(){
			  let temp = {};
			  this.inputs.map(item=>{
			    if(item.type === 'input'){
			      if(item.isPrice){
			        if(!item.value) temp[item.key] =  '';
			        else temp[item.key] = this.$xdHelper.multiplyFloatNumber(Number(item.value), 100);
						}
			      else temp[item.key] = (item.value === undefined || item.value===null) ? '': item.value;
					}
			    else if(item.type === 'select'){
            let multiple = item.multiple === undefined ? false : item.multiple;
            if (multiple){
              if(item.value.length === 0) temp[item.key] = [];
              else {
                temp[item.key] = this.$xdHelper.getValuesForList(item.list, item.value)
              }
						}
            if (!multiple){
              temp[item.key] = (item.value === undefined || item.value===null) ? '': item.value;
            }
					}
          else if(item.type === 'time') {
            temp[item.key] = item.value.replace(/:/,item['formatValue'])
          }
				});

        //单条记录
        if(this.inputs.length === 1) {
          let value = null;
          Object.keys(temp).map(key =>{
            value = temp[key];
          });
          return value;
        }

				return temp
			},

			/**
			 * @description 数据改变事件
			 */
			change(){
			  this.$emit('onChange', this.checkParams())
			},


      /**
			 * @description 双向绑定数据处理
       */
			update(){
			  console.log('update',this.checkParams())
        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()])
        }
			},
		}
  }
</script>

<style scoped lang="scss">
	.xd-multiple-input {
		display: flex;
		justify-content: flex-start;
		align-items: flex-start;
		flex-flow: wrap;
    overflow: hidden;

    &__after,&__before {
      flex-shrink: 0;
      margin-right: 5px;
    }

		& ::v-deep .el-input-group__append {
			padding: 0 10px
		}


		&__item {
			flex-shrink: 0;
      margin: 0 10px 10px 0;

      &.one {
        margin:0!important;
      }

      & .span {
        margin-left: 5px;
      }

			&-input {
				width: 160px;
			}

			&.multipleOuter {
				min-width: 230px;
			}

			&.multipleUnit {
				min-width: 260px;
			}

			&-select {
				display: flex;
				justify-content: flex-start;
				align-items: flex-start;
				flex-flow: nowrap;

				& span {
					margin-left: 10px;
				}
			}


			&  *.multiple {
				& ::v-deep .el-tag.el-tag--info {
					display: flex;
					justify-content: flex-start;
					align-items: center;
					max-width: 130px;
					overflow: hidden;

					& > span {
						flex: 1;
						max-height: 20px;
						overflow: hidden;
						text-overflow: ellipsis;
						display: -webkit-box;
						-webkit-line-clamp: 1;
						max-width: 130px;
					}

					& > i {
						flex-shrink: 0;
					}
				}
			}

      .xd-time-select {
        max-width: 150px;
      }
		}
	}

	@media screen and (max-width: 768px) {
		.xd-multiple-input {
			&__item {
				width: 100% !important;
				max-width: 100% !important;
        margin: 0 0 10px 0;

				&-input {
					width: 100%;
				}

				&.multipleOuter {
					min-width: 100%;
				}

				&.multipleUnit {
					min-width: 100%;
				}
			}
		}
	}
</style>
