const express = require('express')
const webpack = require('webpack')
const config = require('./webpack.dev.conf')
const proxyMiddleware = require('http-proxy-middleware')

const app = express()
const compiler = webpack(config)

const server = 'http://192.168.50.67:31567/'
const local = 'http://127.0.0.1:9026/'
const proxyTable = {
  '/rs/logic/exportfile': {
    target: server
  },
  '/dataManage': {
    target: server
  },
  '/api/af-revenue/sql/': {
    pathRewrite: {
      '^/api/af-revenue': '/'
    },
    target: local
  },
  '/api/af-revenue/report/': {
    pathRewrite: {
      '^/api/af-revenue': '/'
    },
    target: local
  },
  '/api/af-revenue/logic': {
    pathRewrite: {
      '^/api/af-revenue': '/'
    },
    target: local
  },
  '/api': {
    target: server
  },
  '/rs/sql/chargeQuery_by_gasproperties': {
    target: server
  },
  '/rs/logic/chargeQuery_by_gasproperties_line': {
    target: server
  },
  '/files': {
    target: server
  },
  // 查找资源服务数据
  '/rs/search': {
    target: server
  },
  // 查找资源服务数据
  '/rs/logic/getLogin': {
    target: server
  },
  // 查找资源服务数据
  '/rs/logic/getInitData': {
    target: server
  },
  '/rs/logic/getSaleInitData': {
    target: server
  },
  // 用户登录服务地址
  '/rs/user': {
    target: server
  },
  '/rs/path/getParams': {
    target: server
  },
  '/rs/data': {
    target: server
  },
  '/rs/license': {
    target: server
  },
  '/rs/db': {
    target: server
  },
  '/excel': {
    target: server
  },
  '/rs/config': {
    target: server
  },
  '/rs/sql/getLicenseById': {
    target: server
  },
  '/rs/report': {
    target: server
  },
  '/rs/vue': {
    target: server
  },
  '/rs/file': {
    target: server
  },
  '/rs/sql/singleTable': {
    target: server
  },
  '/rs': {
    target: server
  }
}

const devMiddleware = require('webpack-dev-middleware')(compiler, {
  publicPath: config.output.publicPath,
  stats: {
    colors: true,
    chunks: false
  }
})

const hotMiddleware = require('webpack-hot-middleware')(compiler)
// force page reload when html-webpack-plugin template changes
compiler.plugin('compilation', function (compilation) {
  compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
    hotMiddleware.publish({action: 'reload'})
    cb()
  })
})

// proxy api requests
Object.keys(proxyTable).forEach(function (context) {
  let options = proxyTable[context]
  if (typeof options === 'string') {
    options = {target: options}
  }
  app.use(proxyMiddleware(context, options))
})

app.use(require('connect-history-api-fallback')())

app.use(devMiddleware)

app.use(hotMiddleware)

app.use('/static', express.static('./static'))

module.exports = app.listen(8015, function (err) {
  if (err) {
    console.log(err)
    return
  }
  console.log('Listening at http://localhost:8015')
})
