// app/service/user.js
'use strict';
const Service = require('egg').Service;
const moment = require('moment');

class UserService extends Service {
  /**
     * 通过用户编号获取手机号(校验token)
     * @param {*} data user_sid
     * @param {*} data token
     */
  async get_phone_by_user_sid(data) {
    const { ctx } = this;
    const ret = {
      phone: '',
    };
    if (!data.user_sid || !data.token) {
      return ret;
    }
    // 校验用户和token匹配问题
    let userSid = data.user_sid;
    const token = data.token;
    const authToken = await ctx.helper.md5(String(userSid) + moment().format('MDYYYY') + 'f74jkdsy83sjf', 'utf8');
    ctx.logger.info('get_phone_by_user_sid_params:' + JSON.stringify(data));
    ctx.logger.info('authToken:' + authToken);
    if (token != authToken) {
      const authTokenYesterday = await ctx.helper.md5(String(userSid) + moment().subtract(1, 'days').format('MDYYYY') + 'f74jkdsy83sjf', 'utf8');
      if (authToken != authTokenYesterday) {
        return ret;
      }
    }
    // 根据主键查找用户信息
    userSid = isNaN(userSid) ? ctx.helper.decodeUserSid(userSid) : userSid;
    const filter = { where: { sid: userSid } };
    const userInfo = await ctx.gjjModel.SysUser.one(filter);
    ctx.logger.info('get_phone_by_user_sid:' + JSON.stringify(userInfo));
    if (userInfo === null) {
      return ret;
    }
    ret.phone = userInfo.passport;

    return ret;
  }

  async goRegister(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;
  }
}

module.exports = UserService;
