<template>
  <div class="scan-area-steps">
    <div class="step-body">
      <component
        :is="currentComponent"
        :ref="currentComponent"
        :image-url="imageUrl"
        :cur-setting="newSetting"
        @on-next="toNext"
        @on-ready="stepReady"
      ></component>
    </div>

    <div class="step-ctrl">
      <Button
        type="primary"
        @click="prevStep"
        v-if="!isFirstStep"
        style="margin-right: 20px;"
      >
        上一步
      </Button>
      <Button type="primary" @click="nextStep" :disabled="nextHolder">
        {{ isLastStep ? "完成" : "下一步" }}
      </Button>
    </div>
  </div>
</template>

<script>
import CodeArea from "./steps/CodeArea";
import CoverArea from "./steps/CoverArea";
import ImageOrientation from "./steps/ImageOrientation";
import TailorArea from "./steps/TailorArea";
import { deepCopy } from "../../../plugins/utils";

const STEPS_LIST = [
  {
    name: "code-area",
    title: "条形码区域"
  },
  {
    name: "cover-area",
    title: "覆盖区域"
  },
  {
    name: "tailor-area",
    title: "裁剪区域"
  },
  {
    name: "image-orientation",
    title: "试卷方向"
  }
];

export default {
  name: "scan-area-steps",
  components: { CodeArea, CoverArea, ImageOrientation, TailorArea },
  props: {
    imageUrl: {
      type: String,
      require: true
    },
    curSetting: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      STEPS_LIST,
      current: 0,
      nextHolder: true,
      dataReady: true,
      newSetting: {}
    };
  },
  created() {
    this.newSetting = deepCopy(this.curSetting);
  },
  computed: {
    currentComponent() {
      return this.STEPS_LIST[this.current].name;
    },
    isFirstStep() {
      return this.current === 0;
    },
    isLastStep() {
      return this.current === this.lastStep;
    },
    lastStep() {
      return this.STEPS_LIST.length - 1;
    }
  },
  methods: {
    prevStep() {
      if (this.isFirstStep) return;
      this.current -= 1;
    },
    nextStep() {
      if (this.nextHolder) return;
      this.$refs[this.currentComponent].checkValid();
    },
    toNext(setting) {
      console.log(setting);

      Object.entries(setting).map(([key, val]) => {
        this.newSetting[key] =
          typeof val === "object"
            ? Object.assign({}, this.newSetting[key], val)
            : val;
      });
      if (this.isLastStep) {
        this.$emit("on-finished", this.newSetting);
        return;
      }
      this.current += 1;
      this.nextHolder = true;
    },
    stepReady() {
      this.nextHolder = false;
    }
  }
};
</script>
