'use strict';

const Controller = require('egg').Controller;

class ResponseController extends Controller {

    //内部授权注册
    async internalAuth() {
        //https://b.jianbing.com/51business/api/response/internal/auth?target_url=https://b.jianbing.com/webserve/51estate/index&channel_id=fc_gjjfc1
        const { ctx } = this;
        const header = ctx.request.header;
        const input_params = ctx.query;
        let target_url = input_params.target_url;
        const rule = {
            target_url: { type: 'string', required: true },
            channel_id: { type: 'string', required: true },
        }
        ctx.validate(rule, input_params);

        const channel_alias = input_params.channel_id;
        if (target_url.indexOf('?') !== -1) {
            target_url += `&channel_id=${channel_alias}`;
        } else {
            target_url += `?channel_id=${channel_alias}`;
        }

        const target_url1 = decodeURI(target_url);
        const target_url2 = encodeURI(target_url1);

        //如果cookie中已存在 5要素 则可直接 跳到目标地址
        const token = ctx.cookies.get('token', { signed: false });
        const user_id = ctx.cookies.get('user_id', { signed: false });
        const app_user_id = ctx.cookies.get('app_user_id', { signed: false });
        const device_id = ctx.cookies.get('device_id', { signed: false });
        const device_login_id = ctx.cookies.get('device_login_id', { signed: false });
        ctx.logger.info('target_user--' + JSON.stringify({ target_cookies_user: { token, user_id, app_user_id, device_id, device_login_id } }));
        if (token && user_id && app_user_id && device_id && device_login_id) {
            ctx.redirect(target_url2);
            return;
        }

        const user_sid = ctx.cookies.get('jianbing_customer_id', { signed: false });
        const auth_token = ctx.cookies.get('auth_token', { signed: false });
        // ctx.logger.info('target_user--' + new Date().getTime() + JSON.stringify({ target_old_user: { auth_token, user_sid } }));
        const phone_info = await ctx.service.user.get_phone_by_user_sid({ user_sid: user_sid, token: auth_token });//获取用户手机号码
        // ctx.logger.info('phone_info: ' + JSON.stringify(phone_info));
        const phone = phone_info.phone;
        // const phone = '15968762898';
        const app_channel_info = await ctx.blockModel.AppChannel.one({ where: { alias: channel_alias } });//
        // ctx.logger.info('app_channel_info: ' + JSON.stringify(app_channel_info));
        const channel_id = (app_channel_info && app_channel_info.channel_id) ? app_channel_info.channel_id : false;
        const app_id = (app_channel_info && app_channel_info.app_id) ? app_channel_info.app_id : false;

        let node_user_center_login_ret = {};
        if (phone && channel_id && app_id) {//当配置的渠道别名 无法找到对应的 channel_id 和app_id时 使用设备登录
            const go_register_params = {
                phone: phone,
                app_id: app_id,
                channel_id: channel_id,
            }
            // ctx.logger.info('go_register_params: ' + JSON.stringify(go_register_params));
            // console.info(this.config.NODE_URL + '/login/go_register');
            const result_go_register = await ctx.helper.send_request(this.config.NODE_URL + '/login/go_register', go_register_params, { method: 'POST' });//通过手机号直接注册新用户中心
            node_user_center_login_ret = result_go_register.data;
            // ctx.logger.info('target_user--'  + new Date().getTime() +  JSON.stringify({ target_old_user: { go_register_params, node_user_center_login_ret } }));
            // ctx.logger.info('go_register_result: ' + JSON.stringify(node_user_center_login_ret));
            ctx.logger.info(JSON.stringify({ url: ctx.app.config.NODE_URL + '/login/go_register', go_register_params: go_register_params, go_register_result: node_user_center_login_ret }));
            node_user_center_login_ret.user_id = node_user_center_login_ret.uid;
            node_user_center_login_ret.device_login_id = node_user_center_login_ret.device_login_logs_id;
            delete (node_user_center_login_ret.uid);
            delete (node_user_center_login_ret.device_login_logs_id);
        }

        // ctx.logger.info('target_user--'  + new Date().getTime() +  JSON.stringify({ target_old_user: { channel_id, app_id } }));
        if (!phone || !channel_id || !app_id || !node_user_center_login_ret.token) {//  或渠道错误 或直接注册新用户中心失败时 使用设备登录
            const user_agent = header.user_agent ? 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 device_no = ctx.helper.md5(user_agent + ip);
            const past_deviceno = device_no + new Date().getTime();//根据 user_agent 和ip生成设备号
            const device_login_params = {
                past_deviceno: past_deviceno,
                channel_id: channel_id,
                app_id: app_id,
                device_info: {},
            }
            // ctx.logger.info('device_login_params: ' + JSON.stringify(device_login_params));//设备登录参数
            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;//设备登录返回结果
            // ctx.logger.info('device_login_result: ' + JSON.stringify(device_login_data));
            ctx.logger.info('target_user--'  + new Date().getTime() +  JSON.stringify({ target_old_user: { device_login_params, result_device_login } }));
            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');
            }
            node_user_center_login_ret.device_id = device_login_data.device_id;
            node_user_center_login_ret.device_login_id = device_login_data.device_login_logs_id;
        }
        
        const expire = 7200 * 1000;
        const date = new Date();
        for (let key in node_user_center_login_ret) {
            const value = node_user_center_login_ret[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 });
            }
        }
        
        ctx.redirect(target_url2);
        return;
    }


}

module.exports = ResponseController;
