<template>
	<div class="xd-order-full-rule">
		<div class="xd-order-full-rule__tips top" v-if="setting.tipsPos === 'top'" v-html="setting.tips"></div>
		<div
			class="xd-order-full-rule__item"
			v-for="(item,index) in list" :key="item.key"
		>
			<div>{{setting.fullName}}</div>
			<div>
				<el-input
					:disabled="disabled"
					@input="()=>{change();update();}"
					@blue="()=>{change();update();}"
					:size="size"
					type="number"
					:placeholder="placeholder.fullPlaceholder"
					v-model="item.full_price"
				>
					<template v-if="setting.fullUnit" slot="append">{{setting.fullUnit}}</template>
				</el-input>
			</div>
			<div>{{setting.cutName}}</div>
			<div>
				<el-input
					:disabled="disabled"
					@input="()=>{change();update();}"
					@blue="()=>{change();update();}"
					type="number"
					:size="size"
					:placeholder="placeholder.cutPlaceholder"
					v-model="item.cut_price"
				>
					<template v-if="setting.cutUnit" slot="append">{{setting.fullUnit}}</template>
				</el-input>
			</div>
			<template v-if="!isOne">
				<i :class="{'xd-disabled':disabled}" v-if="(index + 1) === list.length" class="el-icon-circle-plus" @click="addItem" ></i>
				<i :class="{'xd-disabled':disabled}" v-if="list.length > 1" class="el-icon-remove" @click="removeItem(index)"></i>
			</template>
		</div>
		<div class="xd-order-full-rule__tips bottom" v-if="setting.tipsPos === 'bottom'" v-html="setting.tips"></div>
	</div>
</template>

<script>
  import emitter from 'element-ui/src/mixins/emitter';

  export default {
    name: "XdFullCutRule",
    mixins: [emitter],
		props:{
      defaultValue:{
        type: Array,
				default(){
    				return []
				},
			},

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

			setting: {
        type: Object,
        default() {
          return {
            fullUnit: '元',
            cutUnit: '元',
            fullName: '金额满',
            cutName: '运费减',
            tipsPos: 'bottom', // top bottom
						tips: '如：设置16:00前下单，最早可提前2小时；16:00后下单，最早可提前1天。<br />若：用户在16点前下单，最早可选择当前下单时间往后2小时的时间；16点后下单，最早只能选择第2天。'
					}
        },
			},

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

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

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

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

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

      //数字字符串 转 数字
      isNumber: {
        type: Boolean,
        default: true,
      },
		},
		data(){
      return {
				list: [ ],
				isOne: false,

				formatItem: {
          full_price: '',
          cut_price: ''
				},

				//默认map关系显示
        defaultMap:{
          full_price: 'full_price',
          cut_price: 'cut_price'
				}

			}
		},

		created(){
      if(this.setting.isOne !== undefined) this.isOne = this.setting.isOne;
  		if(this.defaultValue === null || this.defaultValue.length === 0) {
  		  this.list.push(this.getItem())
			}
  		else {
  		  this.handleMapToList();
			}

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

		methods: {
      addItem(){
        if(this.disabled) return;
        this.list.push(this.getItem());
        this.change();
        this.update();
			},

			removeItem(index){
        if(this.disabled) return;
        this.list.splice(index, 1);
        this.change();
        this.update();
			},

      getItem(){
        return {
          ...this.$xdHelper.cloneDeep(this.formatItem),
					key: this.$xdHelper.randomChar(20)
				}
			},


      /**
			 * @description 返回映射关系对象数据
			 */
      handleListToMap(){
        return this.$xdHelper.cloneDeep(this.list).map(item=>{
				  let temp = {};
				  Object.keys(item).map(key =>{
				    if(key !== 'key') {
              let str = this.getMap(key, false);
              temp[str] = item[key];
              temp[str] = this.$xdHelper.multiplyFloatNumber(Number(item[key]), 100);
						}

					});
				  return temp;
				});
			},

      /**
       * @description 初始化映射关系到数据列表
       */
      handleMapToList() {
        let list = this.defaultValue.map(item=>{
          let temp = {};
					Object.keys(item).map(key=>{
					  let keyStr = this.getMap(key, true);
            if(keyStr) {
              temp[keyStr] = this.$xdHelper.divisionFloatNumber(item[key], 100);
              temp['key'] = this.$xdHelper.randomChar(20);
						}
					});
					return temp
				}).filter(item => {
          return !this.checkVarEmpty(item.full_price) || !this.checkVarEmpty(item.cut_price)
        });
        if(list.length === 0) this.list.push(this.getItem());
        else this.list = list;
      },


      checkVarEmpty(value) {
        return (value === undefined || value === "" || value === null);
      },


			//插件系统方法///////////////////////////////////////
      /**
       * @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 = this.list.filter(item=>{
			    return (item.full_price === '' || item.cut_price === '' )
						|| (item.full_price < 0 || item.cut_price < 0)
        });

			  //使用自定义校验器
			  if(this.useCustomRules && temp.length > 0) return this.handleListToMap();
			  //使用简单校验器
			  if(temp.length > 0) return [];
				return this.handleListToMap();
			},

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


      /**
			 * @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()])
        }
			},


		}
  }
</script>

<style scoped lang="scss">
	.xd-order-full-rule {
		max-width: 740px;
		overflow-x: auto;

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

		&__tips {
			line-height: 22px;
			font-size: 12px;
			color: #999;
		}

		&__item {
			display: flex;
			justify-content: flex-start;
			align-items: center;
			margin-bottom: 10px;
			&:last-child {
				margin-bottom: 0;
			}

			& > div {
				margin-right: 10px;

				&:first-child, &:nth-child(3) {
					flex-shrink: 0;
				}

				&:nth-child(2), &:nth-child(4){
					min-width: 100px;
				}


			}

			& > i {
				font-size: 24px;
				flex-shrink: 0;
				cursor: pointer;
				&.el-icon-remove {
					color: $red;
				}

				&.el-icon-circle-plus {
					color: $blue;
				}

			}
		}

		.el-icon-circle-plus {
			color: #42B983;
		}

		.el-icon-remove {
			color: #F56C6C;
		}

    & i.xd-disabled {
      opacity: .5;
      cursor: not-allowed;
    }
	}


	@media screen and (max-width: 768px) {
		.xd-order-full-rule {
			padding-bottom: 8px;

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

			& ::v-deep .el-input__inner {
				padding: 0 6px !important;
			}

			&__item {
				& > div {
					margin-right: 6px;
					font-size: 12px;
					&:nth-child(2), &:nth-child(4) {
						min-width: 110px;

					}


				}
			}
		}
	}
</style>
