<%
/*
Note: The contents of this file will be directly overwritten when EZDML is upgraded. Instead of modifying this file directly, copy the file to a new name and modify the new file.

注意：程序升级时会直接覆盖此文件内容，请不要直接修改此文件，如果需要请将此文件复制到新名称，然后对新文件进行修改。

2022-02-11: 生成vue-ele-admin

*/

//本页面采用EZDML模板语法（<%开头的脚本编译前会自动进行转换，类似JSP，脚本调试器里点编译能看到转换后的代码）
//生成的结果内容中也包含JS，所以要注意分清哪些代码是EZDML执行、哪些是浏览器执行的

%>
const Mock = require('mockjs')
const { param2Obj } = require('./utils')

const user = require('./user')
const table = require('./table')

<%
  var md=curModel;
  for(var j=0; j<md.tables.count; j++)
  {
    var tb = md.tables.getItem(j);
    if(!tb.isChecked || (tb.typeName == 'TEXT') )
      continue;
%>
const ez_${ChnToPY(tb.name)} = require('./ez_mock/${ChnToPY(curModel.name)}/${ChnToPY(tb.name)}')
<%
  }
%>

const mocks = [
  ...user,
  ...table,
<%
  var md=curModel;
  for(var j=0; j<md.tables.count; j++)
  {
    var tb = md.tables.getItem(j);
    if(!tb.isChecked || (tb.typeName == 'TEXT') )
      continue;
%>
  ...ez_${ChnToPY(tb.name)},
<%
  }
%>
]

// for front mock
// please use it cautiously, it will redefine XMLHttpRequest,
// which will cause many of your third-party libraries to be invalidated(like progress event).
function mockXHR() {
  // mock patch
  // https://github.com/nuysoft/Mock/issues/300
  Mock.XHR.prototype.proxy_send = Mock.XHR.prototype.send
  Mock.XHR.prototype.send = function() {
    if (this.custom.xhr) {
      this.custom.xhr.withCredentials = this.withCredentials || false

      if (this.responseType) {
        this.custom.xhr.responseType = this.responseType
      }
    }
    this.proxy_send(...arguments)
  }

  function XHR2ExpressReqWrap(respond) {
    return function(options) {
      let result = null
      if (respond instanceof Function) {
        const { body, type, url } = options
        // https://expressjs.com/en/4x/api.html#req
        result = respond({
          method: type,
          body: JSON.parse(body),
          query: param2Obj(url)
        })
      } else {
        result = respond
      }
      return Mock.mock(result)
    }
  }

  for (const i of mocks) {
    Mock.mock(new RegExp(i.url), i.type || 'get', XHR2ExpressReqWrap(i.response))
  }
}

module.exports = {
  mocks,
  mockXHR
}

