<template>
	<div
    class="xd-product-params"
    :style="{background: bgColor}"
    v-if="system.length > 0 || custom.length > 0 "
    :class="{disabled:disabled}"
  >
		<div class="xd-product-params__system" v-if="system.length > 0">
			<div class="xd-product-params__system-item" v-for="(item,index) in system" :key="item.attr_id">
				<div :style="{width: width}">{{item.name}}</div>
				<div>
					<xd-select-list
						class="xd-product-params__system-item-input"
						v-if="item.input_type === 'SELECT'"
						v-model="item.value"
						:default-value="item.value"
						:list="item.options"
						@change="()=>{change();update();}"
						@clear="()=>{change();update();}"
					></xd-select-list>
					<xd-radio-list
						v-if="item.input_type === 'RADIO'"
						v-model="item.value"
						:default-value="item.value"
						:list="item.options"
						@change="()=>{change();update();}"
					></xd-radio-list>
					<xd-check-list
						v-if="item.input_type === 'CHECKBOX'"
						v-model="item.value"
						:default-value="item.value"
						:list="item.options"
						@change="()=>{change();update();}"
					></xd-check-list>
					<el-input
						v-if="item.input_type === 'INPUT'"
						placeholder="请输入内容"
						class="xd-product-params__system-item-input"
						:disabled="disabled"
						@input="()=>{change();update();}"
						:size="size"
						v-model="item.value"
					>
					</el-input>
				</div>
			</div>
		</div>
		<div class="xd-product-params__custom" v-if="can_add_param && custom.length > 0">
			<div class="xd-product-params__custom-item" v-for="(item,index) in custom" :key="item.key">
				<div class="xd-product-params__custom-key">
					<span>参数名称：</span>
					<el-input
						style="width: 130px"
						:disabled="disabled"
						@input="()=>{change();update();}"
						:size="size"
						:placeholder="placeholder.startPlaceholder"
						v-model="item.name"
					>
					</el-input>
				</div>
				<div class="xd-product-params__custom-value">
					<span>参数值：</span>
					<el-input
						style="width: 130px"
						:disabled="disabled"
						@input="()=>{change();update();}"
						:size="size"
						:placeholder="placeholder.endPlaceholder"
						v-model="item.value"
					>
					</el-input>
				</div>
				<div class="xd-product-params__custom-btn" >
					<i v-if="(index + 1) === custom.length" class="el-icon-circle-plus" @click="addItem"></i>
					<i v-if="custom.length > 1" class="el-icon-remove" @click="removeItem(index)"></i>
				</div>
			</div>
		</div>
	</div>
</template>

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

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

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

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

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

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

		},
		data(){
      return {
        can_add_param: false,
				bgColor: 'rgba(242, 243, 245, 1)',
				ext_required: false,
				width: '100px',
      	system: [],
				custom: [],
				empty: {
          "attr_id": "",
          "name": "",
          "value": "",
					"input_type": "INPUT"
        },
			}
		},

		created(){
      if (this.setting['can_add_param']) this.can_add_param = this.setting['can_add_param'];
      if (this.setting['bgColor']) this.bgColor = this.setting['bgColor'];
      if (this.setting['width']) this.width = this.setting['width'];
      if (this.setting['is_required']) this.ext_required = this.setting['is_required'];
      this.handleMapToList();

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

		methods: {

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

      addItem() {
        this.custom.push(this.getItem());
        this.change();
        this.update();
      },

      removeItem(index) {
        this.custom.splice(index, 1);
        this.change();
        this.update();
      },

			getSystemItem(item, tempSystem){
        let temp = '';
				if(item.input_type === 'CHECKBOX') temp = [];
   			let data = tempSystem.filter(it=>{
   			  return item.attr_id === it.attr_id
				});
   			//复选框数据设置
        if (data.length > 0 && item.input_type === 'CHECKBOX'){
          if (this.$xdHelper.checkVarType(data[0].value) === 'string') {
            try{
              data[0].value = JSON.parse(data[0].value)
						}catch (e) {
              data[0].value = []
            }
          }
        }
   			if(data.length === 0) return temp;
   			else return data[0].value;
			},


      /**
       * @description 初始化映射关系到数据列表(需要自己实现)
			 * 把默认数据转化为内部数据
       */
      handleMapToList() {
        let system = this.setting.parameters;
        if(this.defaultValue !== null
					&& this.$xdHelper.checkVarType(this.defaultValue) === 'array'
				) {
        	let tempSystem = [];
        	let tempCustom = [];
          this.defaultValue.map(item=>{
            if(item.attr_id) tempSystem.push(item)
						else tempCustom.push(item)
					});

          //设置自定义参数
          if(tempCustom.length > 0) {
            this.custom = tempCustom.map(item => {
              return {
                ...item,
                key: this.$xdHelper.randomChar(20)
              }
            });
					}
          else this.custom.push(this.getItem())

					//设置自定义参数
          system = system.map(item=>{
            return {
              ...item,
              model: item.value,
							value: this.getSystemItem(item, tempSystem)
						}
					});
				}
        else{
          this.custom.push(this.getItem())
				}
        this.system = system;
      },

			getParams(){
        let temp = [];
        this.system.map(item => {
          temp.push({
            input_type: item['input_type'],
            attr_id: item.attr_id,
            name: item.name,
            value: item.value,
            is_required: item.is_required
          })
        });
        this.custom.map(item => {
          if(item.name && item.value) {
            temp.push({
              attr_id: item.attr_id,
              name: item.name,
              value: item.value,
							input_type: "INPUT"
            })
					}
        });
        return temp;
			},


      /**
			 * @description 需要校验检查参数是正确处理方法
       */
			checkParams(){
   			if(this.required) {
   			  let data = this.$xdHelper.cloneDeep(this.getParams());
   			  let flag = true;
          let error=[];
          data.map(item=>{
            if(item.attr_id === '') {
              if(this.is_required) {
                if (!item.value || !item.name){
                  error.push(item);
                  flag = false;
                }
							}
						}
            else {
              if(item.is_required) {
                if (this.$xdHelper.checkVarType(item.value) === 'string' && !item.value) {
                  error.push(item);
                  flag = false;
                }
                if (this.$xdHelper.checkVarType(item.value) === 'array' && item.value.length === 0) {
                  error.push(item);
                  flag = false;
                }
							}
						}
					});

          data = data.map(item=>{
					  delete item['is_required'];
					  // if(item.input_type === 'CHECKBOX') {
            //   item.value = JSON.stringify(item.value)
						// }
					  return item
					});

          if(flag) return data;
          else return {error: error}
				}
				return this.getParams()
			},

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


      /**
			 * @description 双向绑定数据处理
       */
			update(){
			  console.log('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-product-params {

    &.disabled {
      position: relative;
      &::after {
        position: absolute;
        border-radius: 4px;
        left: 0;
        right: 0;
        bottom: 0;
        top:0;
        content: ' ';
        cursor: not-allowed;
        background: rgba(0,0,0,.03);
        z-index: 100;
      }
    }

    ::v-deep {
      & input,
      & input:focus,
      & textarea,
      & textarea:focus {
        border-color:#ccc!important
      }
    }


		padding: 10px;
		border-radius: 4px;
		width: 100%;

		&__system {
			overflow-x: auto;
			&-item {
				display: flex;
				justify-content: flex-start;
				align-items: flex-start;
				padding: 2px 0;

				&-input {
					width: 230px;
				}

				& > *:first-child {
					width: 120px;
					text-align: right;
					flex-shrink: 0;
					margin-right: 10px;
				}
			}
		}


		&__custom {
			border-top: 1px dotted #fff;
			margin-top: 10px;
			padding-top: 10px;
			overflow-x: auto;

			&-item {
				display: flex;
				justify-content: flex-start;
				align-items: center;
				margin-bottom: 5px;

				&:last-child {
					margin-bottom: 0;
				}
			}

			&-btn {
				display: flex;
				justify-content: center;
				align-items: center;
				margin-left: 5px;
				flex-shrink: 0;
				& > i {
					font-size: 24px;
					flex-shrink: 0;
					cursor: pointer;

					&.el-icon-remove {
						color: $red;
					}

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

				}
			}

			&-key{
				margin-right: 5px;
			}
			&-key, &-value {
				display: flex;
				justify-content: flex-start;
				align-items: center;
				flex-shrink: 0;
				& > span {
					flex-shrink: 0;
					color: #999;
				}
			}
		}

	}

	@media screen and (max-width: 768px) {
		.xd-product-params {
			&__system {
				&-item {
					&-input {
						width: 160px;
					}
				}
			}
		}
	}
</style>
