'use strict';

module.exports = (options, app) => {
    return async function (ctx, next) {//

        //给第三方用的 跳过 设备判断
        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)) {
                await next();
                return;
            }
        }

        const deviceId = ctx.cookies.get('device_id', { signed: false });
        const deviceLoginId = ctx.cookies.get('device_login_id', { signed: false });
        if (!deviceId || deviceId.length === 0 || !deviceLoginId || deviceLoginId.length === 0) {//如果cookie中不存在device_id和device_login_id 先做设备登录 针对H5

            let pastDeviceno = ctx.cookies.get('past_deviceno', { signed: false });
            let deviceNo = ctx.cookies.get('device_no', { signed: false });
            let channelAlias = ctx.cookies.get('channel_alias', { signed: false });

            if (!pastDeviceno || pastDeviceno.length == 0) {//cookie中取不到从头部中获取
                pastDeviceno = ctx.request.header.past_deviceno || undefined;
            }
            if (!deviceNo || deviceNo.length == 0) {
                deviceNo = ctx.request.header.device_no || undefined;
            }
            if (!channelAlias || channelAlias.length == 0) {
                channelAlias = ctx.request.header.channel_alias || undefined;
            }

            ctx.logger.info('middleware_device_login_params: ' + JSON.stringify({pastDeviceno, deviceNo, channelAlias}));
            //和H5约定 从cookie中获取设备编号和渠道号 做设备登录；H5调接口前就会把这三个参数存到cookies中，如果没有device_init中将会出现 无效用户
            if (pastDeviceno && pastDeviceno.length !== 0 && deviceNo && deviceNo.length !== 0 && deviceNo && channelAlias && channelAlias.length !== 0) {

                const app_channel_info = await ctx.blockModel.AppChannel.one({ where: { alias: channelAlias } });
                if (!app_channel_info  || Object.keys(app_channel_info).length == 0) {
                    ctx.failed('渠道未配置');
                }
                if (!app_channel_info.app_id) {
                    ctx.failed('渠道未配置');
                }
                const params = {
                    past_deviceno: pastDeviceno, // description: '原设备编号'
                    device_no: deviceNo, // description: '设备编号'
                    channel_alias: channelAlias,//description：'渠道别名'
                    channel_id: app_channel_info.channel_id, // description: '‘渠道编号’,即之前的place_cid'
                    app_id: app_channel_info.app_id,// description: 'app编号'
                    device_info: {},
                };
                ctx.logger.info('middleware_device_login_params: ' + JSON.stringify(params));
                const result_device_login = await ctx.helper.send_request(ctx.app.config.NODE_URL + '/login/device', params, { method: 'POST' });//设备登录
                const device_login_data = result_device_login.data;
                ctx.logger.info('middleware_device_login_result: ' + JSON.stringify(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_no) {//设备指纹
                    ctx.failed('device login error, device_no 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 device_id = device_login_data.device_id;
                const device_login_id = device_login_data.device_login_logs_id;
                const expire = 7200 * 1000;
                const date = new Date();
                ctx.setDeviceId(device_id);
                ctx.setDeviceLoginId(device_login_id);
                ctx.cookies.set('device_id', device_id, {  httpOnly: false, signed: false, maxAge: expire, expires: date, path: '/', });
                ctx.cookies.set('device_login_id', device_login_id, { httpOnly: false, signed: false, maxAge: expire, expires: date, path: '/', });
            }

        }
        await next();
    };
};