import axios from "axios";
// 是否使用本地测试模式
const usingLocal = false;
export default {
  // 设置表单数据
  setFormData(data, callback) {
    const json = JSON.stringify(data);
    if (usingLocal) {
      localStorage["form_data"] = json;
    } else {
      axios
        .request({
          url: "/api/v1/cd/fromData/insert",
          method: "post",
          data: {
            formDataJson: json
          }
        })
        .then(response => {
          if (response.status == 200) {
            const d = response.data;
            if (d.code) {
              const data = d.data;
              callback && callback.call(undefined, data);
            }
          }
        });
    }
  },
  // 修改表单数据
  changeFormData(id, data, callback) {
    const json = JSON.stringify(data);
    if (usingLocal) {
      this.setFormData(data, callback);
    } else {
      axios
        .request({
          url: "/api/v1/cd/fromData/update",
          method: "post",
          data: {
            formDataJson: json,
            formDataId: id
          }
        })
        .then(response => {
          if (response.status == 200) {
            const d = response.data;
            if (d.code) {
              const data = d.data;
              callback && callback.call(undefined, data);
            }
          }
        });
    }
  },
  // 获取表单数据
  getFormData(id, callback) {
    if (usingLocal) {
      const json = JSON.parse(localStorage["form_data"]);
      callback && callback.call(undefined, json);
    } else {
      if (!id) {
        alert("表单唯一标识不能为空");
        return;
      }
      axios
        .request({
          url: "/api/v1/cd/fromData/" + id,
          method: "get"
        })
        .then(response => {
          if (response.status == 200) {
            const d = response.data;
            if (d.code) {
              const data = d.data;
              if (data && data.form_data_json) {
                const json = JSON.parse(data.form_data_json);
                callback && callback.call(undefined, json);
              } else {
                alert("表单数据不存在,请检查表单id是否正确");
              }
            }
          }
        });
    }
  }
};
