'use strict';

const Controller = require('egg').Controller;
const moment = require('moment');
const WECHAT_CODE_URL = 'https://open.weixin.qq.com/connect/oauth2/authorize';
const WECHAT_AUTH = 'https://api.weixin.qq.com/sns/oauth2/access_token';
const WECHAT_APPID = 'wx3c772df2d8d78da3';
const WECHAT_APPID_TEST = 'wxa9df2d60730b25d9';
const WECHAT_SECRET = 'b369fd28a9f9320ebe4e35dfaa00b194';
const WECHAT_SECRET_TEST = 'dfede7a3b543149a88b07b46bcc28e00';
const REDIRECT_PAGE = '/webserve/accumulation/index';
class WechatController extends Controller {


  // 公众号公积金查询H5授权跳转
  async oauthLogin() {

    const { ctx } = this;
    const code = ctx.query.code;
    const channel_id = ctx.query.channel_id;
    const app_id = [ 'https://lan-nginx.jianbing.com', 'https://pro-nginx.jianbing.com' ].includes(this.config.NODE_BASE_URL) ? WECHAT_APPID : WECHAT_APPID_TEST;
    const appsecret = [ 'https://lan-nginx.jianbing.com', 'https://pro-nginx.jianbing.com' ].includes(this.config.NODE_BASE_URL) ? WECHAT_SECRET : WECHAT_SECRET_TEST;
    if (!code || code.length === 0) { // this.app.config.OUT_P_NODE_URL
      const target_url = WECHAT_CODE_URL + `?appid=${app_id}&redirect_uri=${encodeURIComponent(`${this.app.config.PULIC_BASE_URL}/51business/api/gjj/wechat/oauth_login?&channel_id=${channel_id}`)}&response_type=code&scope=snsapi_base&state=gjjquery#wechat_redirect`;
      ctx.redirect(target_url); return;
    }
    const url = `${WECHAT_AUTH}?appid=${app_id}&secret=${appsecret}&code=${code}&grant_type=authorization_code`;
    const result = await ctx.helper.send_request(url, {}, { method: 'GET' });
    ctx.logger.info(JSON.stringify({ wx_gjj_query: result }));
    if (result.status !== 200) {
      ctx.failed('获取openid失败1');
    }
    const wx_ret = result.data;
    if (!wx_ret.openid) {
      ctx.failed('获取openid失败2');
    }
    const openid = wx_ret.openid;
    // 在微信端需要关闭微信重新打开才会销毁cookie值，所以在这里重置cookie值
    ctx.cookies.set('openid', openid, { httpOnly: false, signed: false, path: '/', overwrite: true });
    ctx.cookies.set('token', null, { httpOnly: false, signed: false, path: '/', overwrite: true });
    ctx.cookies.set('user_id', null, { httpOnly: false, signed: false, path: '/', overwrite: true });
    ctx.cookies.set('app_user_id', null, { httpOnly: false, signed: false, path: '/', overwrite: true });
    ctx.cookies.set('jianbing_customer_id', null, { httpOnly: false, signed: false, path: '/', overwrite: true });
    ctx.cookies.set('auth_token', null, { httpOnly: false, signed: false, path: '/', overwrite: true });

    const redirect_url = this.app.config.PULIC_BASE_URL + REDIRECT_PAGE;
    // 判断是否已绑定手机号
    const user_exist_url = `${this.app.config.NODE_BASE_URL}/user_api/v1/user/is_exist/${openid}`;
    const bind_phone_result = await ctx.helper.send_request(user_exist_url, { type: 5 }, { method: 'GET' });
    ctx.logger.info(JSON.stringify({ bind_phone_result }));
    if (bind_phone_result.status !== 200) {
      ctx.redirect(redirect_url + `?channel_id=${channel_id}&type=noLogin`); return;
    }
    const user_exist_ret = bind_phone_result.data;
    if (user_exist_ret.result !== 'true') { // 未绑定的手机号时
      ctx.redirect(redirect_url + `?channel_id=${channel_id}&type=noLogin`); return;
    }
    const user_id = user_exist_ret.uid;

    // 已绑定手机的 继续 判断是否有导入公积金
    const login_result = await this.user_login({ code, openid, channel_id });// 已绑定的用户 直接登录
    if (login_result.anew && !login_result.token) {
      ctx.redirect(redirect_url + `?channel_id=${channel_id}&type=noLogin`); return;
    }

    const gjj_exist_url = `${this.app.config.NODE_BASE_URL}/cassandra-server/gjj/list/${user_id}`;
    const gjj_exist_result = await ctx.helper.send_request(gjj_exist_url, {}, { method: 'GET' });
    ctx.logger.info(JSON.stringify({ gjj_exist_result }));
    if (gjj_exist_result.status !== 200) { // 调用公积金接口出错
      ctx.redirect(redirect_url + `?channel_id=${channel_id}&type=noLogin`); return;
    }
    const gjj_exist_ret = gjj_exist_result.data;
    if (!gjj_exist_ret.ret || gjj_exist_ret.ret.length === 0) { // 没有导入公积金时
      ctx.redirect(redirect_url + `?channel_id=${channel_id}&type=noLogin`); return;
    }

    ctx.redirect(redirect_url + `?channel_id=${channel_id}&type=hasLogin`); return;// 已导入公积金
  }

  // 判断是否有公积金导入并跳转
  // async checkGjj() {

  //     const { ctx } = this;
  //     const user_id = ctx.userId;
  //     //判断是否有导入公积金
  //     console.info(user_id);
  //     const gjj_exist_url = `${this.app.config.NODE_BASE_URL}/cassandra-server/gjj/list/${user_id}`;
  //     const gjj_exist_result = await ctx.helper.send_request(gjj_exist_url, {}, { method: 'GET' });
  //     ctx.logger.info(JSON.stringify({ gjj_exist_result: gjj_exist_result }));
  //     if (gjj_exist_result.status !== 200) {
  //         ctx.redirect(NO_GJJ_PAGE); return;
  //     }
  //     ctx.redirect(GJJ_DETAIL_PAGE); return;
  // }

  async checkLogin() {

    const { ctx } = this;
    const user_id = ctx.userId;
    let is_login = false;
    if (user_id) {
      is_login = true;
    }
    // const phone = await ctx.helper.getPhoneCity('15968762898');
    ctx.success({ result: is_login });
  }


  async user_login(params) {

    const { ctx } = this;
    const { code, openid, channel_id } = params;

    const user_agent = ctx.request.header.user_agent ? ctx.request.header.user_agent : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36';
    const ip = ctx.helper.getClientIP();
    const past_deviceno = ctx.helper.md5(user_agent + ip);

    const app_channel_info = await ctx.blockModel.AppChannel.one({ where: { alias: channel_id } });
    if (!app_channel_info || Object.keys(app_channel_info).length === 0) {
      ctx.failed('渠道未配置');
    }
    if (!app_channel_info.app_id) {
      ctx.failed('渠道未关联APPID');
    }

    const device_login_params = {
      past_deviceno,
      channel_id: app_channel_info.channel_id,
      app_id: app_channel_info.app_id,
      device_info: {},
    };
    const result_device_login = await ctx.helper.send_request(this.config.NODE_URL + '/login/device', device_login_params, { method: 'POST' });// 设备登录
    const device_login_data = result_device_login.data;// 设备登录返回结果
    if (!device_login_data || Object.keys(device_login_data).length === 0) {
      ctx.failed('device login error, device_login_data empty');
    }
    if (!device_login_data.past_deviceno) { // 使用设备码+时间+随机数产生的一个尽量避免重复的字符串，类似游客版h5
      ctx.failed('device login error, past_deviceno empty');
    }
    if (!device_login_data.device_id) { // Devices字段表主键ID
      ctx.failed('device login error, device_id empty');
    }
    if (!device_login_data.device_login_logs_id) { // DeviceLoginLogs字段表主键ID
      ctx.failed('device login error, device_login_logs_id empty');
    }

    const user_login_params = {// 用户登录传递的参数
      past_deviceno, // 使用设备码+时间+随机数产生的一个尽量避免重复的字符串，类似游客版h5登
      // device_no: device_login_data.device_no,//使用新的sdk生成的设备指纹
      login_type: '5', // 登录类型：1 验证码手机登录, 2 password手机登录,4 token登录,5 微信登录,
      passport: code, // 登录账号：手机登录值为手机
      password: code, // 类型对应的值
      app_user_id: params.app_user_id || '', // app用户ID token登陆时传的参数  可空
      code: code || '', // 第三方授权登录时的code  可空
      device_info: {}, // 设备信息
      openid: openid || '', // 例如微信公众号的openid（不传默认是51查个税）
    };
    const result_user_login = await ctx.helper.send_request(this.config.NODE_URL + '/login/user', user_login_params, { method: 'POST' });// 用户登录
    ctx.logger.info(JSON.stringify({ user_login_params, result_user_login }));
    const user_login_data = result_user_login.data;// 用户登录返回结果
    if (!user_login_data || Object.keys(user_login_data).length === 0) {
      ctx.failed('用户的登录失败');
    }
    if (!user_login_data.token || !user_login_data.uid) {
      const error_msg = user_login_data.error ? user_login_data.error : '用户的登录失败';
      if (error_msg === '需要重新授权') {
        return { anew: 1 };
      }
      ctx.failed(error_msg);
    }
    // 获取用户信息
    const login_token = user_login_data.token;
    const app_user_id = user_login_data.app_user_id;
    const user_id = user_login_data.uid;
    const device_id = device_login_data.device_id;
    const device_login_id = device_login_data.device_login_logs_id;

    // 老版用户信息
    const old_user_sid = user_login_data.old_uid;
    let auth_token = '';
    if (old_user_sid) {
      auth_token = ctx.helper.md5(String(old_user_sid) + moment(new Date()).format('MDYYYY') + 'f74jkdsy83sjf', 'utf8');
    }

    const user_info = {
      token: login_token,
      app_user_id,
      user_id,
      device_id,
      device_login_id,
      android_url: `${this.config.OUT_P_NODE_URL}/frontendh5/lp/wc/index?down=${encodeURIComponent(app_channel_info.android_url)}`,
      ios_url: app_channel_info.ios_url,
      jianbing_customer_id: old_user_sid,
      auth_token,
    };
    for (const key in user_info) {
      const value = user_info[key];
      ctx.cookies.set(key, value, { httpOnly: false, signed: false, path: '/', overwrite: true });
    }

    return user_info;

  }

  // 微信公众号客服页面授权跳转地址
  async oauthAthena() {

    const { ctx } = this;
    const code = ctx.query.code;
    const channel_id = ctx.query.channel_id;
    const ident = ctx.query.ident;
    if (!ident) ctx.failed('ident配置错误1！');
    const wechatApp = await ctx.huodongModel.WechatApp.findOne({ where: { ident } });
    if (!wechatApp || !wechatApp.appid || !wechatApp.appsecret) ctx.failed('ident配置错误2！');

    const appid = wechatApp.appid;
    const appsecret = wechatApp.appsecret;

    if (!code || code.length === 0) { // this.app.config.OUT_P_NODE_URL
      const target_url = WECHAT_CODE_URL + `?appid=${appid}&redirect_uri=${encodeURIComponent(`${this.app.config.PULIC_BASE_URL}/51business/api/gjj/wechat/oauth_athena?&channel_id=${channel_id}&ident=${ident}`)}&response_type=code&scope=snsapi_base&state=${ident}#wechat_redirect`;
      ctx.redirect(target_url); return;
    }

    const url = `${WECHAT_AUTH}?appid=${appid}&secret=${appsecret}&code=${code}&grant_type=authorization_code`;
    const result = await ctx.helper.send_request(url, {}, { method: 'GET' });
    ctx.logger.info(JSON.stringify({ url, wx_athena_query: result }));
    if (result.status !== 200) {
      ctx.failed('获取openid失败1');
    }
    const wx_ret = result.data;
    if (!wx_ret.openid) {
      ctx.failed('获取openid失败2');
    }
    const openid = wx_ret.openid;

    // 在微信端需要关闭微信重新打开才会销毁cookie值，所以在这里重置cookie值
    ctx.cookies.set('openid', openid, { httpOnly: false, signed: false, path: '/', overwrite: true });
    ctx.cookies.set('token', null, { httpOnly: false, signed: false, path: '/', overwrite: true });
    ctx.cookies.set('user_id', null, { httpOnly: false, signed: false, path: '/', overwrite: true });
    ctx.cookies.set('app_user_id', null, { httpOnly: false, signed: false, path: '/', overwrite: true });
    ctx.cookies.set('jianbing_customer_id', null, { httpOnly: false, signed: false, path: '/', overwrite: true });
    ctx.cookies.set('auth_token', null, { httpOnly: false, signed: false, path: '/', overwrite: true });

    // const redirect_page = wechatApp.login_url ? wechatApp.login_url : (wechatApp.business_url ? wechatApp.business_url : REDIRECT_PAGE);
    const redirect_page = wechatApp.business_url ? wechatApp.business_url : REDIRECT_PAGE;
    const redirect_url = redirect_page.indexOf('http') > -1 ? redirect_page : this.app.config.PULIC_BASE_URL + redirect_page;
    // 判断是否已绑定手机号
    const user_exist_url = `${this.app.config.NODE_BASE_URL}/user_api/v1/user/is_exist/${openid}`;
    const bind_phone_result = await ctx.helper.send_request(user_exist_url, { type: 5 }, { method: 'GET' });
    ctx.logger.info(JSON.stringify({ athena_bind_phone_params: { openid, type: 5 }, athena_bind_phone_result: bind_phone_result }));
    if (bind_phone_result.status !== 200) {
      ctx.redirect(redirect_url + `?channel_id=${channel_id}&type=noLogin`); return;
    }
    const user_exist_ret = bind_phone_result.data;
    if (user_exist_ret.result !== 'true') { // 未绑定的手机号时
      ctx.redirect(redirect_url + `?channel_id=${channel_id}&type=noLogin`); return;
    }

    const login_result = await this.user_login({ code, openid, channel_id });// 已绑定的用户 直接登录
    if (login_result.anew && !login_result.token) {
      ctx.redirect(redirect_url + `?channel_id=${channel_id}&type=noLogin`); return;
    }

    ctx.redirect(redirect_url + `?channel_id=${channel_id}&type=hasLogin`); return;

  }
}
module.exports = WechatController;
