
import { SurveyRecModel } from '@db/SurveyRec';
import { SurveyModel } from '@db/Survery';
import { checkWjxSign, getRedisSubChannel } from 'app/pubUtils/sdkUtil';
import { Service } from 'egg';
import { RedisClient } from 'redis';
import { REDIS_KEY } from '@consts';
import { RoleModel } from '@db/Role';

/**
 * Test Service
 */
export default class Sdk extends Service {

    public async wjxCallback(params: any) {
        // 1. 检查sign
        if(!checkWjxSign(params.activity, params.index, params.sign)) {
            return 0
        }
        // 2. 查询配置
        let curConfig = await SurveyModel.findBySurveyId(params.activity);
        if(!curConfig) return 0;

        let roleId = params[`q${curConfig.roleIndex}`];
        if(!roleId) return 0;

        let role = await RoleModel.findByRoleId(roleId);
        if(!role) return 0;

        let rec = await SurveyRecModel.findByRoleIdAndId(roleId, params.activity);
        if(rec) return 0;

        rec = await SurveyRecModel.createSurveyRec(roleId, params.activity, params.index, JSON.stringify(params));

        // 3. 发邮件
        let redisClient: RedisClient = this.app.context.redisClient;
        let name = getRedisSubChannel(REDIS_KEY.SURVEY_CHANNEL, this.app.config.env);
        let result = await redisClient.publishAsync(name, rec.code);
        if(result == 0) {
            console.error('用户名违规处理, 未发布到订阅频道');
            return 0
        }
        return 1
    }

}
