'use strict';
module.exports = () => {
  return async function deviceInit(ctx, next) {

    const method = ctx.request.method;
    let input_params = {};
    switch (method) {
      case 'GET':
        input_params = ctx.request.query;
        break;
      case 'POST':
        input_params = ctx.request.body;

        break;
      case 'PUT':
        input_params = ctx.request.body;
        break;
      default:
        break;
    }

    ctx.logger.info(JSON.stringify({ url: ctx.request.url, params: input_params, cookies: ctx.header.cookie }));

    const stack = ctx.app.router.stack;
    const current_path_list = ctx.request.url.split('?');
    const current_path = current_path_list[0];

    let current_url_eq_path = 1;
    for (const element in stack) {

      const path_index = stack[element].path.split(':');
      const path = path_index[0];
      current_url_eq_path = current_path.includes(path) ? 1 : 0;

      if (current_url_eq_path == 1 && stack[element].name != null && stack[element].methods.includes(ctx.request.method)) {
        if (input_params.app_user_id != undefined) {
          ctx.setAppUserId(input_params.app_user_id);
        }

        if (input_params.device_id != undefined) {
          ctx.setDeviceId(input_params.device_id);
        }

        if (input_params.device_login_id != undefined) {
          ctx.setDeviceLoginId(input_params.device_login_id);
        }

        await next();
        return;
      }
    }

    // 优先从cookie中取，取不到再从header中取
    let appUserId = ctx.cookies.get('app_user_id', { signed: false });
    let token = ctx.cookies.get('token', { signed: false });
    let userId = ctx.cookies.get('user_id', { signed: false });
    let deviceId = ctx.cookies.get('device_id', { signed: false });
    let deviceLoginId = ctx.cookies.get('device_login_id', { signed: false });
    let appTypeId = '2150d0f1-ee07-4d17-a019-251be3699bd1';
    let appId = 'DE78A9AC-0407-4998-AE4D-B7F5A64EAC19';
    let oldUserId;

    if (!deviceId || deviceId.length === 0) {
      deviceId = ctx.deviceId;
    }

    if (!deviceLoginId || deviceLoginId.length === 0) {
      deviceLoginId = ctx.deviceLoginId;
    }

    if (!appUserId || appUserId.length === 0) {
      appUserId = typeof (ctx.request.header.app_user_id) !== 'undefined' ? ctx.request.header.app_user_id : undefined;
    }
    if (!token || token.length === 0) {
      token = typeof (ctx.request.header.token) !== 'undefined' ? ctx.request.header.token : undefined;
    }
    if (!userId || userId.length === 0) {
      userId = typeof (ctx.request.header.uid) !== 'undefined' ? ctx.request.header.uid : undefined;
    }

    if (!deviceId || deviceId.length === 0) {
      deviceId = typeof (ctx.request.header.device_id) !== 'undefined' ? ctx.request.header.device_id : undefined;
    }

    if (!deviceLoginId || deviceLoginId.length === 0) {
      deviceLoginId = typeof (ctx.request.header.device_login_id) !== 'undefined' ? ctx.request.header.device_login_id : undefined;
    }

    // if ((deviceId == undefined || !deviceId || deviceId.length === 0) && input_params.device_id != undefined) {
    //   deviceId = input_params.device_id;
    // }
    // 校验
    const jianbing_customer_id = ctx.cookies.get('jianbing_customer_id', { signed: false });
    const auth_token = ctx.cookies.get('auth_token', { signed: false });
    if ((!appUserId || !token || !userId || !deviceId || !deviceLoginId) && jianbing_customer_id && auth_token) {
      const user_login_info = await goRegister(ctx, { jianbing_customer_id, auth_token });
      userId = user_login_info.user_id;
      appUserId = user_login_info.app_user_id;
      token = user_login_info.token;
      deviceId = user_login_info.device_id;
      deviceLoginId = user_login_info.device_login_id;
    }
    const params = {
      app_user_id: appUserId,
      token,
      uid: userId,
      device_id: deviceId,
      device_login_id: deviceLoginId,
    };

    const result = await ctx.helper.send_request(ctx.app.config.NODE_URL + '/user/auth', params, {
      method: 'POST',
    });
    // ctx.logger.info('appUserId: ' + appUserId);
    // ctx.logger.info('request_header: ' + JSON.stringify(ctx.request.header));
    // ctx.logger.info('user_auth_params: ' + JSON.stringify(params));
    // ctx.logger.info('user_auth_result: ' + JSON.stringify(result));
    ctx.logger.info(JSON.stringify({ url: ctx.app.config.NODE_URL + '/user/auth', request_header: ctx.request.header, user_auth_params: params, user_auth_result: result }));
    console.log(result);
    if (result.status !== 201) {
      ctx.failed('token 已失效');
      return;
    }

    //  const data = result.data.data;
    let data = result.data.data;
    if (result.data == undefined || result.data.data == undefined) {
      data = {};
    }
    // const data = {};
    // 所有数据以校验后返回的为准
    appUserId = data.app_user_id || undefined;
    userId = data.uid || undefined;
    deviceId = data.device_id || undefined;
    deviceLoginId = data.device_login_logs_id || undefined;
    appId = data.app_id || undefined;
    appTypeId = data.app_type_id || undefined;
    oldUserId = data.oid || undefined;


    // 写入常量
    ctx.setAppUserId(appUserId);
    ctx.setUserId(userId);
    ctx.setDeviceId(deviceId);
    ctx.setDeviceLoginId(deviceLoginId);
    ctx.setAppId(appId);
    ctx.setAppTypeId(appTypeId);
    ctx.setOldUserId(oldUserId);

    // 设置旧cookie
    let authToken = '';
    if (oldUserId) {
      const moment = require('moment');
      authToken = ctx.helper.md5(String(oldUserId) + moment(new Date()).format('MDYYYY') + 'f74jkdsy83sjf', 'utf8');
    }
    ctx.setOldCookie('jianbing_customer_id=' + oldUserId + ';auth_token=' + authToken);

    await next();

  };

  async function goRegister(ctx, old_user_data = {}) {

    // const { ctx } = this;

    const { jianbing_customer_id, auth_token } = old_user_data;
    if (!jianbing_customer_id || !auth_token) {
      return {};
    }
    const phone_info = await ctx.service.user.get_phone_by_user_sid({ user_sid: jianbing_customer_id, token: auth_token });// 获取用户手机号码
    const phone = phone_info.phone;

    const channel_alias = ctx.cookies.get('channel_alias', { signed: false });
    let app_channel_info = await ctx.blockModel.AppChannel.one({ where: { alias: channel_alias } });//
    if (!app_channel_info || !app_channel_info.app_id || !app_channel_info.channel_id) {
      app_channel_info = await ctx.blockModel.AppChannel.one({ where: { alias: 'n_1_18100_appstore' } });// 如果配置的渠道未渠道信息，使用默认的渠道，以防出错
    }
    const app_id = app_channel_info.app_id;
    const channel_id = app_channel_info.channel_id;
    const go_register_params = {
      phone,
      app_id,
      channel_id,
    };
    const result_go_register = await ctx.helper.send_request(ctx.app.config.NODE_URL + '/login/go_register', go_register_params, { method: 'POST' });// 通过手机号直接注册新用户中心
    const node_user_center_login_ret = result_go_register.data;
    ctx.logger.info(JSON.stringify({ url: ctx.app.config.NODE_URL + '/login/go_register', middleware_go_register_params: go_register_params, middleware_result_go_register: result_go_register }));
    if (!node_user_center_login_ret.token || !node_user_center_login_ret.uid || !node_user_center_login_ret.app_user_id) {
      return {};
    }
    const user_login_info = {
      user_id: node_user_center_login_ret.uid,
      app_user_id: node_user_center_login_ret.app_user_id,
      token: node_user_center_login_ret.token,
      device_id: node_user_center_login_ret.device_id,
      device_login_id: node_user_center_login_ret.device_login_logs_id,
    };
    const expire = 7200 * 1000;
    const date = new Date();
    for (const key in user_login_info) {
      const value = user_login_info[key];
      const exist_value = ctx.cookies.get(key, { signed: false });
      if (!exist_value) {
        ctx.cookies.set(key, value, { httpOnly: false, signed: false, path: '/', overwrite: true });
      }
    }
    return user_login_info;
  }

};
