import * as API from "api/virtual/orders";

export default {
  components: {
    MDrawer: resolve => require(["components/drawer"], resolve)
  },
  props: {
    show: {
      type: Boolean,
      default: false
    },
    source: {
      type: Number,
      default: 0
    },
    type: {
      type: Number,
      default: 0
    },
    data: {
      type: Object,
      default: {}
    }
  },
  data() {
    return {
      my_show: false,
      isUpdate: false,
      loading: false,
      params: {
        remark: ""
      }
    };
  },
  watch: {
    show(bool) {
      this.my_show = bool;
      if (bool) {
        if (this.data) {
          console.log("data", this.data);
          for (let k in this.data) {
            if (k in this.params) {
              this.params[k] = this.data[k];
            }
          }
        }
      }
    }
  },
  methods: {
    ok() {
      this.params.type = this.type;
      this.post();
    },
    post() {
      this.loading = true;
      let params = JSON.parse(JSON.stringify(this.params));
      if (this.data) {
        // 编辑
        API.update(params, this.data.id)
          .then(res => {
            this.loading = false;
            if (res.code == 0) {
              this.handelSuccess();
            }
          })
          .catch(err => {
            this.loading = false;
          });
      } else {
        // 添加
        API.create(params)
          .then(res => {
            this.loading = false;
            if (res.code == 0) {
              this.handelSuccess();
            }
          })
          .catch(err => {
            this.loading = false;
          });
      }
    },
    visibleChange(bool) {
      if (!bool) {
        this.$emit("update:show", false);
      }
    },
    clear() {
      for (let k in this.params) {
        this.params[k] = "";
      }

      this.my_show = false;
    },
    handelSuccess() {
      this.$Message.info("操作成功");
      this.clear();
      if (this.data) {
        this.$emit("update-success");
      } else {
        this.$emit("add-success");
      }
    }
  }
};
