<template>
  <view class="form-step">
    <view class="form-item">
      <text :class="['form-label', required ? 'required' : '']">{{ label }}</text>
      <text class="add-btn" @click="addStep">添加</text>
    </view>
    <view class="step" v-for="(item, i) in steps" :key="i">
      <text class="step-label">第{{ i + 1 }}步</text>
      <input type="text" class="step-inp" :value="item.text" placeholder="请输入步骤内容"
        placeholder-class="placeholder" @input="onStepInput(i, $event)" />
      <image src="https://mrrplus.oss-cn-beijing.aliyuncs.com/wxstaic/images/delete_icon.png"
        class="delete-icon" mode="aspectFit" @click="deleteStep(i)"></image>
    </view>
  </view>
</template>

<script>
export default {
  name: 'FormItemServiceStep',
  props: {
    value: {
      type: [Array, String],
      default: function () { return []; }
    },
    label: {
      type: String,
      default: '服务流程'
    },
    required: {
      type: Boolean,
      default: false
    }
  },
  data: function () {
    return {
      steps: []
    };
  },
  watch: {
    value: {
      handler: function (val) {
        if (typeof val === 'string') {
          try {
            this.steps = JSON.parse(val) || [];
          } catch (e) {
            this.steps = [];
          }
        } else if (Array.isArray(val)) {
          this.steps = val.slice();
        } else {
          this.steps = [];
        }
      },
      immediate: true
    }
  },
  methods: {
    addStep: function () {
      var i = this.steps.length + 1;
      this.steps.push({
        title: '第' + i + '步',
        text: '',
        photo: ''
      });
      this._emit();
    },
    deleteStep: function (i) {
      this.steps.splice(i, 1);
      this._emit();
    },
    onStepInput: function (i, e) {
      var value = e && e.target ? e.target.value : e;
      this.steps[i].text = value;
      this._emit();
    },
    _emit: function () {
      this.$emit('input', this.steps);
    }
  }
};
</script>

<style scoped>
.form-step {
  width: 100%;
}

.form-item {
  display: flex;
  flex-flow: row nowrap;
  justify-content: space-between;
  align-items: center;
  padding: 0;
}

.form-label {
  font-size: 28rpx;
  color: #333333;
}

.required::before {
  content: '*';
  color: #ff0000;
  margin-right: 4rpx;
}

.add-btn {
  font-size: 28rpx;
  color: #ff4d6a;
}

.step {
  display: flex;
  flex-flow: row nowrap;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0 0;
}

.step-label {
  font-size: 28rpx;
  color: #333333;
  white-space: nowrap;
}

.step-inp {
  flex: 1;
  font-size: 28rpx;
  color: #333333;
  margin-left: 20rpx;
  padding: 0 24rpx;
  background-color: rgba(230, 230, 230, 0.5);
  height: 72rpx;
  border-radius: 8rpx;
}

.delete-icon {
  width: 40rpx;
  height: 40rpx;
  margin-left: 16rpx;
  flex-shrink: 0;
}
</style>
