/* eslint-disable nuxt/no-cjs-in-config */
const path = require('path')
const fs = require('fs')

/* env configs */
const globalEnvConfig = require(`./config/global.js`)
const envConfig = require(`./config/${process.env.mode || 'production'}.js`)
const env = Object.assign(globalEnvConfig, envConfig)

/* ali-oss */
const WebpackAliOSSPlugin = require('@gdyfe/webpack-alioss-plugin')

/* version from package.json */
const { version } = require('./package.json')

const PROJECT_NAME = 'lottery'
const IS_USE_OSS = process.env.NODE_ENV === 'production' && !env.private
const plugins = IS_USE_OSS
  ? [
      // 优化打包速度
      new WebpackAliOSSPlugin({
        accessKeyId: 'LTAI5tDdsn3rPhNSkED4jDDz',
        accessKeySecret: 'rsWsmunIglT1NqYUNe8fvbjl02UqTk',
        region: 'oss-cn-hangzhou',
        bucket: `guangdianyun-static-${env.run_server}`,
        prefix: PROJECT_NAME,
        limit: 10, // 备份最近 10 个版本的 oss 文件
        format: version,
        exclude: [/.*\.html$/], // 或者 /.*\.html$/,排除.html文件的上传
        deleteAll: false, // 优先匹配 format 配置项
        output: path.resolve(__dirname, './nuxt-dist/dist/client'),
        local: true // 上传打包输出目录里的文件
      })
    ]
  : []
const REMOTE_OSS_DOMAIN = `//static-${env.run_server}.guangdianyun.tv`

const sentryConfig = IS_USE_OSS
  ? {
      sentry: {
        dsn: 'https://610a9f4b831d4d10b228658886eaa18d@sentry.guangdianyun.tv/14',
        config: {
          environment: env.run_server,
          release: version,
          autoSessionTracking: false
        },
        lazy: true
      }
    }
  : {}

const gtagConfig = IS_USE_OSS
  ? {
      'google-gtag': {
        id: 'G-HZHJLDPT80', // required
        config: {
          anonymize_ip: true,
          send_page_view: false
        }
      }
    }
  : {}

export default {
  buildDir: 'nuxt-dist',
  env,
  router: {
    base: globalEnvConfig.baseUrl,
    middleware: ['device'],
    extendRoutes(routes, resolve) {
      routes.push({
        path: '/',
        redirect: '/list',
        components: null
      })
      routes.push({
        path: '/index/:id',
        components: {
          default: resolve(__dirname, 'pages/index') // or routes[index].component
        }
      })
    }
  },
  // Global page headers: https://go.nuxtjs.dev/config-head
  head: {
    title: '',
    meta: [
      { charset: 'utf-8' },
      {
        name: 'viewport',
        content: 'width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, viewport-fit=cover'
      },
      { hid: 'description', name: 'description', content: '' },
      { name: 'format-detection', content: 'telephone=no' },
      {
        hid: 'description',
        name: 'description',
        content: '问卷报表'
      }
    ],
    link: [
      {
        rel: 'stylesheet',
        href: `${env.OSS_DOMAIN}/common/icon/iconfont.css`,
        ssr: false
      },
      { rel: 'icon', href: `${env.OSS_DOMAIN}/common/img/gdy_favicon.png` },
      { rel: 'stylesheet', href: `${REMOTE_OSS_DOMAIN}/web-component/complaintsDeal/complaintsDeal.min.css` },
      {
        href: '//apiliveroom.dev.guangdianyun.tv/v1',
        rel: 'dns-prefetch'
      },
      {
        href: '//activity.guangdianyun.tv',
        rel: 'dns-prefetch'
      },
      {
        href: '//static-pro.guangdianyun.tv',
        rel: 'dns-prefetch'
      },
      {
        href: '//res.wx.qq.com',
        rel: 'dns-prefetch'
      },
      {
        href: '//www.googletagmanager.com',
        rel: 'dns-prefetch'
      }
    ],
    script: [{ src: `${REMOTE_OSS_DOMAIN}/web-component/complaintsDeal/complaintsDeal.min.js`, defer: true }]
  },

  // Global CSS: https://go.nuxtjs.dev/config-css
  css: ['@/assets/styles/main.less'],

  // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
  plugins: [
    { src: '@/plugins/routeHooks' },
    { src: '@/plugins/vant' },
    { src: '@/filters' },
    { src: '@/plugins/vueClipboard' },
    { src: '@/plugins/dmsService', ssr: false },
    { src: '@/plugins/pvStatisticalService', ssr: false },
    { src: '@/plugins/deviceId', ssr: false }
  ],

  // Auto import components: https://go.nuxtjs.dev/config-components
  components: true,

  // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
  buildModules: [
    // https://go.nuxtjs.dev/eslint
    '@nuxtjs/eslint-module',
    '@nuxtjs/style-resources'
  ],
  /* less全局变量 */
  styleResources: {
    less: './assets/styles/variable.less'
  },
  // Modules: https://go.nuxtjs.dev/config-modules
  modules: ['@nuxtjs/axios', '@nuxtjs/sentry', '@nuxtjs/google-gtag'],
  /*
   ** Axios module configuration
   ** See https://axios.nuxtjs.org/options
   */
  ...sentryConfig,
  ...gtagConfig,
  axios: {},
  server: {
    https: {
      cert: fs.readFileSync('./certs/localhost.pem'),
      key: fs.readFileSync('./certs/localhost-key.pem')
    },
    port: env.run_port, // default: 3000
    host: '0.0.0.0' // default: localhost
  },
  // Build Configuration: https://go.nuxtjs.dev/config-build
  build: {
    publicPath: !env.private
      ? `${REMOTE_OSS_DOMAIN}/${PROJECT_NAME}/${version}`
      : `/${env.X_CA_STAGE.toLowerCase() || 'prod'}/`,
    transpile: [/vant.*?less/],
    babel: {
      plugins: [
        [
          'import',
          {
            libraryName: 'vant',
            style: name => {
              return `${name}/style/less.js`
            }
          },
          'vant'
        ]
      ]
    },
    postcss: {
      plugins: {
        'postcss-pxtorem': {
          rootValue: 75,
          selectorBlackList: [/^html$/, /^body$/, '.lottery-entry', 'tippy'], // 忽略转换正则匹配项
          propList: ['*']
        }
      }
    },
    plugins
  }
}
