shoes.js 17.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
/**
 * Created by qiujun on 2018/4/13.
 */
const mySqlCli = global.yoho.utils.mysqlCli;
const TABLE_SHOES_ANSWER = 'act_shoes_answers';
const TABLE_SHOES_FRIENDS = 'act_shoes_friends';
const TABLE_USER = 'user';

class ShoesModel extends global.yoho.BaseModel {
    constructor(ctx) {
        super(ctx);
    }


    /**
     * 查询两个用户是不是好友关系
     * @param unionId
     * @param friendUnionId
     * @returns {Promise.<*>}
     */
    async checkFriends(unionId, friendUnionId) {
        let strSql = `SELECT * FROM ${TABLE_SHOES_FRIENDS}
                        WHERE union_id = :unionId
                        AND friend_union_id = :friendUnionId;`;

        return mySqlCli.query(strSql, {
            unionId,
            friendUnionId
        });
    }

    /**
     * 给两个用户添加好友关系
     * @param actId
     * @param unionId
     * @param friendUnionId
     * @returns {Promise.<void>}
     */
    async addFriends(actId, unionId, friendUnionId) {
        let strSql_1 = `SELECT * FROM ${TABLE_USER} WHERE union_id = :unionId;`;
        let strSql_2 = `SELECT * FROM ${TABLE_USER} WHERE union_id = :friendUnionId;`;
        let strInsert_u = `INSERT INTO ${TABLE_SHOES_FRIENDS} (user_id, friend_id, union_id, friend_union_id, act_id)
                        VALUES (:userId, :friendId, :unionId, :friendUnionId, :actId);`;
        let strInsert_f = `INSERT INTO ${TABLE_SHOES_FRIENDS} (user_id, friend_id, union_id, friend_union_id, act_id)
                        VALUES (:friendId, :userId, :friendUnionId, :unionId, :actId);`;

        let userInfo = await mySqlCli.query(strSql_1, {unionId});
        let friendInfo = await mySqlCli.query(strSql_2, {friendUnionId});
        let userId = 0;
        let friendId = 0;

        if (userInfo.length > 0) {
            userId = userInfo[0].id;
        }
        if (friendInfo.length > 0) {
            friendId = friendInfo[0].id;
        }

        if (userId && friendId) {
            // 插两条好友数据,互相为好友
            let ufId = await mySqlCli.insert(strInsert_u, {userId, friendId, unionId, friendUnionId, actId});
            let fuId = await mySqlCli.insert(strInsert_f, {friendId, userId, friendUnionId, unionId, actId});

            return Promise.resolve({
                act_id: actId,
                ufId: ufId,
                fuId: fuId,
                user_id: userId,
                friend_id: friendId,
                union_id: unionId,
                friend_union_id: friendUnionId
            });
        } else {
            return Promise.reject(
                {
                    code: 203,
                    data: {userId: userId, friendId: friendId},
                    message: '用户查询失败'
                });
        }
    }

    /**
     * 通过unionId获取用户id
     * @param unionId
     * @returns {Promise.<*>}
     */
    getUserId(unionId) {
        let strSql = `SELECT id FROM ${TABLE_USER} WHERE union_id = :unionId;`;

        return mySqlCli.query(strSql, {unionId});
    }

    /**
     * 查询用户的游戏记录
     * @param actId
     * @param unionId
     * @returns {Promise.<*>}
     */
    async checkUserPlayed(actId, unionId) {
        let strUser = `SELECT id, user_phone FROM ${TABLE_USER} WHERE union_id = :unionId`;
        let strPlayed = `SELECT user_id, question_id, user_select_answer FROM ${TABLE_SHOES_ANSWER}
                         WHERE user_id = :userId AND act_id = :actId;`;


        let userInfo = await mySqlCli.query(strUser, {unionId});
        let userId = 0;
        let userPhone = 0;

        if (userInfo && userInfo.length > 0) {
            userId = userInfo[0].id;
            let phone = userInfo[0].user_phone;

            if (parseInt(phone, 10) !== 0) {
                userPhone = 1;
            }
        } else {
            return Promise.reject({
                code: 205,
                message: '没有该用户'
            });
        }

        let playedInfo = await mySqlCli.query(strPlayed, {userId, actId});

        if (playedInfo && playedInfo.length > 0) {
            return Promise.resolve(Object.assign({}, {data: playedInfo}, {phone: userPhone}));
        } else {
            return Promise.reject({
                code: 204,
                message: '没有查询到用户游戏记录'
            });
        }
    }

    async getUserPlayedInfo(actId, unionId) {
        let strUser = `SELECT id FROM ${TABLE_USER} WHERE union_id = :unionId`;
        let strPlayed = `SELECT user_id, question_id, user_select_answer FROM ${TABLE_SHOES_ANSWER}
                         WHERE user_id = :userId AND act_id = :actId;`;


        let userInfo = await mySqlCli.query(strUser, {unionId});
        let userId = 0;

        if (userInfo && userInfo.length > 0) {
            userId = userInfo[0].id;
        } else {
            return {
                code: 205,
                message: '没有该用户'
            };
        }

        let playedInfo = await mySqlCli.query(strPlayed, {userId, actId});

        if (playedInfo && playedInfo.length > 0) {
            return {
                code: 204,
                data: playedInfo,
                message: '查询到用户游戏记录'
            };
        } else {
            return {
                code: 200,
                data: [],
                message: '没有查询到用户游戏记录'
            };
        }
    }

    /**
     * 保存用户答题信息(多条)
     * @param actId
     * @param userId
     * @param questionId
     * @param userSelectAnswer
     * @param isCorrect
     * @returns {*}
     */
    saveUserResult(actId, userId, list, index, result) {
        let questionId = list[index].questionId;
        let userSelectAnswer = list[index].userSelectOption;
        let isCorrect = list[index].isCorrect;
        let that = this;


        let strSql = `INSERT INTO ${TABLE_SHOES_ANSWER} (act_id, user_id, question_id, user_select_answer, is_correct)
                        VALUES (:actId, :userId, :questionId, :userSelectAnswer, :isCorrect);`;



        if (index < list.length) {

            mySqlCli.insert(strSql, {
                actId,
                userId,
                questionId,
                userSelectAnswer,
                isCorrect
            }).then(ret => {
                index += 1;
                result.push(ret);
                that.saveUserResult(actId, userId, list, index, result);
            });
        } else {
            return Promise.resolve(result);
        }
    }

    /**
     * 插入用户数据(单条)
     * @param actId
     * @param userId
     * @param questionId
     * @param userSelectAnswer
     * @param isCorrect
     * @returns {Promise.<void>}
     */
    saveResult(actId, userId, questionId, userSelectAnswer, isCorrect, playTime) {
        let strSql = `INSERT INTO ${TABLE_SHOES_ANSWER} (act_id, user_id, question_id, user_select_answer, is_correct, play_time)
                        VALUES (:actId, :userId, :questionId, :userSelectAnswer, :isCorrect, :playTime);`;

        return mySqlCli.insert(strSql, {
            actId,
            userId,
            questionId,
            userSelectAnswer,
            isCorrect,
            playTime
        });
    }

    /**
     * 获取用户得分
     * @param unionId
     * @param actId
     * @param perScore
     * @returns {Promise.<*>}
     */
    async getUserScore(unionId, actId, perScore) {
        let strSql = `SELECT * FROM ${TABLE_USER} WHERE union_id = :unionId;`;
        let strScore = `SELECT COUNT(*) as count FROM ${TABLE_SHOES_ANSWER} WHERE user_id = :userId
                        AND act_id = :actId AND is_correct=1;`;
        let userInfo = await mySqlCli.query(strSql, {
            unionId
        });

        if (userInfo.length > 0) {
            let userInfoObj = userInfo[0];
            let userId = userInfoObj.id;
            let userAvatar = userInfoObj.user_avatar;
            let userName = userInfoObj.user_name;
            let scoreInfo = await mySqlCli.query(strScore, {
                userId,
                actId
            });

            let score = scoreInfo[0].count * perScore;

            return Promise.resolve({
                userid: userId,
                unionid: unionId,
                nickname: userName,
                headimgurl: userAvatar,
                score: score
            });

        } else {
            return Promise.reject({
                code: 203,
                message: '用户不存在'
            });
        }
    }

    /**
     * 获取用户得分及排名
     * @param unionId
     * @param actId
     * @param perScore
     * @returns {Promise.<*>}
     */
    async getUserRankScore(unionId, actId, perScore) {
        let strUser = `SELECT * FROM ${TABLE_USER} WHERE union_id = :unionId;`;
        let strScore = `SELECT C.* FROM (SELECT (@rowNo := @rowNo + 1) AS rownum, A.* FROM
                        (SELECT SUM(is_correct) as count, SUM(play_time) as playTime, AVG(UNIX_TIMESTAMP(create_time)) as create_time, user_id from act_shoes_answers WHERE act_id = :actId group by user_id order by count desc, playTime asc) A,
                        (SELECT @rowNo := 0) B) C WHERE C.user_id = :userId;`;

        let userInfo = await mySqlCli.query(strUser, {
            unionId
        });



        if (userInfo.length > 0) {
            let userInfoObj = userInfo[0];
            let userId = userInfoObj.id;
            let userAvatar = userInfoObj.user_avatar;
            let userName = userInfoObj.user_name;
            let scoreInfo = await mySqlCli.query(strScore, {
                userId,
                actId
            });

            if (scoreInfo && scoreInfo.length > 0) {
                let score = scoreInfo[0].count * perScore;
                let rank = scoreInfo[0].rownum;
                let playTime = scoreInfo[0].playTime;
                let createTime = parseInt((new Date()).getTime() / 1000, 10) - parseInt(scoreInfo[0].create_time, 10);

                return {
                    code: 200,
                    userid: userId,
                    unionid: unionId,
                    nickname: userName,
                    headimgurl: userAvatar,
                    score: score,
                    rank: rank,
                    playTime: playTime,
                    createTime: createTime
                };
            } else {
                return {
                    code: 201,
                    unionId: unionId,
                    message: '用户无得分'
                };
            }


        } else {
            return {
                code: 203,
                message: '用户不存在'
            };
        }
    }

    /**
     * 获取好友得分
     * @param userId
     * @param actId
     * @param perScore
     * @param userScore
     * @returns {Promise.<*>}
     */
    async getFriendsScoreList(userId, actId, perScore, userScore) {
        let strSql = `SELECT
                      U.id,
                      U.union_id,
                      U.user_name,
                      U.user_avatar,
                      SF.user_id,
                      SF.friend_id
                      FROM ${TABLE_USER} U
                      INNER JOIN
                      ${TABLE_SHOES_FRIENDS} SF
                      ON U.id = SF.friend_id WHERE SF.user_id = :userId
                      ORDER BY SF.create_time DESC;`;

        let friendsInfo = await mySqlCli.query(strSql, {userId}); // 查询到所有好友信息
        let friendsIds = [];
        let friendList = [];
        let record = {
            winNum: 0,
            dogfallNum: 0,
            failNum: 0
        };

        for (let i = 0; i < friendsInfo.length; i++) { // 把好友id放入数组
            friendsIds.push(friendsInfo[i].id);
        }
        if (friendsIds.length === 0) { // 如果好友数为 0,则直接返回空数组
            return Promise.resolve({
                record,
                friendList
            });
        }

        let friendIds = friendsIds.join(',');
        let strScore = `SELECT user_id, SUM(is_correct) as count FROM ${TABLE_SHOES_ANSWER}
                        WHERE user_id in (${friendIds}) AND act_id = :actId group by user_id;`;
        let scoreInfo = await mySqlCli.query(strScore, {
            actId,
        });

        if (scoreInfo && scoreInfo.length > 0) { // 给friendList插入处理后的结果(得分及信息)
            for (let i = 0; i < scoreInfo.length; i++) {
                let friendId = scoreInfo[i].user_id;
                let friendScore = scoreInfo[i].count * perScore;

                if (friendScore < userScore) { // 处理输赢数量
                    record.winNum += 1;
                } else if (friendScore === userScore) {
                    record.dogfallNum += 1;
                } else {
                    record.failNum += 1;
                }
                for (let j = 0; j < friendsInfo.length; j++) {
                    if (friendId === friendsInfo[j].id) {
                        let friend_obj = {};

                        friend_obj.score = friendScore;
                        friend_obj.unionid = friendsInfo[j].union_id;
                        friend_obj.nickname = friendsInfo[j].user_name;
                        friend_obj.headimgurl = friendsInfo[j].user_avatar;

                        friendList.push(friend_obj);
                        break;
                    }
                }
            }
        }

        return Promise.resolve({
            record,
            friendList
        });

    }

    async getAllUserScoreList(actId, perScore) {
        let strScore = `SELECT C.* FROM
                        (SELECT (@rowNo := @rowNo + 1) AS rownum,
                        A.* FROM
                        (SELECT
                        U.union_id,
                        U.user_name,
                        U.user_avatar,
                        U.user_phone,
                        SUM(S.is_correct) as count,
                        SUM(S.play_time) as playTime,
                        AVG(UNIX_TIMESTAMP(S.create_time)) as create_time,
                        S.user_id as user_id
                        FROM ${TABLE_USER} AS U INNER JOIN
                        ${TABLE_SHOES_ANSWER} AS S
                        ON U.id = S.user_id
                        WHERE S.act_id=:actId
                        group by S.user_id
                        order by count desc, playTime asc) A, (SELECT @rowNo := 0) B) C 
                        limit 0, 100`;


        let scoreInfo = await mySqlCli.query(strScore, {
            actId
        });

        let friendList = [];

        if (scoreInfo && scoreInfo.length > 0) {
            for (let i = 0; i < scoreInfo.length; i++) {
                let friendObj = {};

                friendObj.score = scoreInfo[i].count * perScore;
                friendObj.rank = scoreInfo[i].rownum;
                friendObj.userId = scoreInfo[i].user_id;
                friendObj.headimgurl = scoreInfo[i].user_avatar;
                friendObj.nickname = scoreInfo[i].user_name;
                friendObj.playTime = scoreInfo[i].playTime;
                friendObj.createTime = parseInt((new Date()).getTime() / 1000, 10) - parseInt(scoreInfo[i].create_time, 10);

                // friendObj.unionid = scoreInfo[i].union_id.split('').reverse().join(''); // unionId反过来排列后再输出

                friendList.push(friendObj);
            }

            return Promise.resolve(friendList);
        }
    }

    async getUserPhoneList(actId, perScore, limit) {
        let strScore = `SELECT C.* FROM
                        (SELECT (@rowNo := @rowNo + 1) AS rownum,
                        A.* FROM
                        (SELECT
                        U.union_id,
                        U.user_name,
                        U.user_avatar,
                        U.user_phone,
                        SUM(S.is_correct) as count,
                        SUM(S.play_time) as playTime,
                        AVG(UNIX_TIMESTAMP(S.create_time)) as create_time,
                        S.user_id as user_id
                        FROM ${TABLE_USER} AS U INNER JOIN
                        ${TABLE_SHOES_ANSWER} AS S
                        ON U.id = S.user_id
                        WHERE S.act_id=:actId
                        group by S.user_id
                        order by count desc, playTime asc) A, (SELECT @rowNo := 0) B) C 
                        limit 0, ${limit}`;


        let scoreInfo = await mySqlCli.query(strScore, {
            actId
        });

        let friendList = [];

        if (scoreInfo && scoreInfo.length > 0) {
            for (let i = 0; i < scoreInfo.length; i++) {
                let friendObj = {};

                friendObj.score = scoreInfo[i].count * perScore;
                friendObj.rank = scoreInfo[i].rownum;
                friendObj.userId = scoreInfo[i].user_id;
                friendObj.userPhone = scoreInfo[i].user_phone;
                friendObj.headimgurl = scoreInfo[i].user_avatar;
                friendObj.nickname = scoreInfo[i].user_name;
                friendObj.playTime = scoreInfo[i].playTime;
                friendObj.createTime = parseInt((new Date()).getTime() / 1000, 10) - parseInt(scoreInfo[i].create_time, 10);

                // friendObj.unionid = scoreInfo[i].union_id.split('').reverse().join(''); // unionId反过来排列后再输出

                friendList.push(friendObj);
            }

            return Promise.resolve(friendList);
        }
    }
}

module.exports = ShoesModel;