// @author ilex.h

const express = require('express');

const {
  testData
} = require('./_mock/testMock');

const {
  ruleLibListData
} = require('./_mock/rule');

const app = express();
const port = 8087;
const successCode = 200;

const transCommonResponse = (data) => {
  const result = {
    result: 'SUCCESS',
    dataList: data
  };
  return JSON.stringify(result);
};


app.all('*', (req, res, next) => {
  console.log(req.headers.origin);
  res.header('Access-Control-Allow-Origin', req.headers.origin);
  res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length, X-Access-Token, X-Api-Key, Authorization, Accept,X-Requested-With');
  res.header('Access-Control-Allow-Methods','PUT,POST,GET,DELETE,OPTIONS');
  res.header('Access-Control-Allow-Credentials','true');
  res.header('X-Powered-By',' 3.2.1');
  if (req.method === 'OPTIONS') {
    // 让options请求快速返回
    res.send(successCode);
  } else {
    next();
  }
});

app.get('/', (req, res) => {
  res.writeHead(successCode, { 'Content-Type': 'text/html;charset=utf-8' });
  res.write(
  `
    <!doctype html>
    <html>
      <head>
        <meta charset='gbk'/>
        <title>AMOS-APIS</title>
        <style>
          div {
            background: rgb(101, 78, 163);
            height: 3rem;
            color: white;
            font-size: 30px;
          }

          a {
            display: block;
            padding: 1rem;
          }
        </style>
      </head>
      <body>
        <div>APIS</div>
        <a href='/test'>test</a>
        <a href='/ruledesign/ruleLibList'>ruleLibList</a>
      </body>
    </html>
  `);
});

app.get('/test', (req, res) => {
  const m = testData().dataList;
  res.send(transCommonResponse(m));
});

app.get('/ruledesign/ruleLibList', (req, res) => {
  res.send(transCommonResponse(ruleLibListData().dataList));
});


const server = app.listen(port, () => {
  const host = server.address().address;
  const port = server.address().port;
  console.log('应用实例，访问地址为 http://%s:%s', host, port);
});
