export default {
  props: {
    show: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    show(bool) {
      this.my_show = bool;
      if (bool) {
        this.current = 0;
        this.status = 'wait';
        this.circle.percent = 0;
        this.circle.content = '未开始';
      }
    }
  },
  data() {
    return {
      my_show: false,
      loading: false,
      disabled: false,
      steps: [
        {
          'title': '同步注销',
          'content': '指定月份的注销数据',
          'command': 'real:sync-cancelled',
          'max': 100,
          'datePicker': true
        }
      ],
      current: 0,
      circle: {
        percent: 0,
        content: '未开始'
      },
      status: 'wait',
      month: this.moment().subtract('1', 'months').startOf('month').format('YYYY-MM')
    };
  },
  methods: {
    call() {
      if (!this.steps[this.current]) {
        return;
      }

      this.disabled = true;

      let params = {};

      params.command = this.steps[this.current]['command'];

      if (!params.command) {
        return this.$Message.error('命令错误');
      }

      if (this.steps[this.current]['datePicker']) {
        if (!this.month) {
          return this.$Message.error('请选择要同步的月份');
        }

        params.parameters = {
          month: this.moment(this.month).format('YYYY-MM')
        };
      }

      let max = this.steps[this.current]['max'];

      this.status = 'process';
      this.circle.content = '正在' + this.steps[this.current]['title'];

      let interval = setInterval(() => {
        if (this.circle.percent < max) {
          this.circle.percent++;
        }
      }, 1000);

      service.post('/api/artisan/call', params).then(res => {
        if (res.code == 0) {
          this.circle.content = this.steps[this.current]['title'] + '完成';
          this.circle.percent = max;
          this.status = (max == 100) ? 'finish' : 'wait';
          this.current++;
        } else {
          this.circle.content = '同步失败';
          this.circle.percent = this.steps[this.current - 1] ? this.steps[this.current - 1]['max'] : 0;
          this.status = 'error';
        }
        this.disabled = false;

        clearInterval(interval);
      }).catch((err) => {
        this.circle.content = '同步失败';
        this.circle.percent = this.steps[this.current - 1] ? this.steps[this.current - 1]['max'] : 0;
        this.status = 'error';
        this.disabled = false;
        clearInterval(interval);
      });
    },
    changeStep(value) {
      this.current = value + 1;
    },

    visibleChange(bool) {
      if (!bool) {
        this.$emit('update:show', false);
      }
    },

    clear() {
      this.my_show = false;
    }
  }
};
