match.ts 34.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 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041

import Model = require('../model');
import sequelize = require('sequelize');
import moment = require('moment');
import _ = require('lodash');
import api_hemera = require('../../../api_hemera');
import ms_schedule = require('./ms_schedule');
import * as nami_data from '../../../nami/nami_data';
import { cache,redis as client, redis, task_lock } from '../../../cache'
const config = require("../../../../config");

import Core = require('../table');
import * as info_db from '../table'
import md5 = require('md5');
import * as zlib from 'zlib';
const matchlock = { flag: false };

export async function start_realtime_message_task(){
   
}


export async function gp_liveScore(root: any, args: any, context: any) {
  //return await matchImp.liveScore(root, args, context, null);
  let result = await liveScore({}, args, {}, null);

  // let result = await cache(async (args: any) => {
  //   return await liveScore({}, args, {}, null)
  // }, args, 3, 'liveScore:v1')

  // let result = await cache(async (args: any) => {
  //   let result = await liveScore({}, args, {}, null);
  //   let buffer = await zlib.gzipSync(JSON.stringify(result))
  //   let z_result = buffer.toString("base64");
  //   return z_result
  // }, args, 3, 'liveScore:v2')
  // if(result){
  //   const buffer = Buffer.from(result, 'base64');
  //   let str_json_result = (await zlib.unzipSync(buffer)).toString();
  //   result = JSON.parse(str_json_result)
  // }

  //弥补ios客户端错误,将count=0的强制为null
  if (result == null || result.count == 0) {
    return {
      count: 0,
      matchs: null,
    }
  }

  //
    //获取nami的足球实时比分数据
    try {
      if(args.matchState=='未'&&[72,45].includes(args.lottery_id) ){
        result.matchs = await this.addNamiScoreLiveData(result.matchs)
      }
    } catch (e) {
      console.info(e);
    }

  return result
}

const liveScore = async (root: any, args: any, context: any, isUpdateCache: any) => {
  let md5Result = md5(JSON.stringify(args)).toUpperCase()
  //add test 
  let key = `${config.CachePrefix}match:match_liveScore:v11_t_${md5Result}`
  let keyCount = `${config.CachePrefix}match:match_liveScoreCount:v11_t_${md5Result}`
  let reply = null
  //isUpdateCache = true;
  if (!isUpdateCache)
    reply = await get10SecondsCache(key, keyCount)
  if (reply != null && !isUpdateCache) {
    return reply
  }
  //数据库出现问题的话,则使用24小时的缓存
  if (matchlock.flag && !isUpdateCache) {
    reply = await get24HoursCache(key, keyCount)
    return reply
  } else {
    reply = await get24HoursCache(key, keyCount)
    if (reply && args.coreIds == null) {
      doGetLiveScore(root, args, context, isUpdateCache, key, keyCount)
      return reply
    } else {
      return await doGetLiveScore(root, args, context, isUpdateCache, key, keyCount)
    }
  }

  return await doGetLiveScore(root, args, context, isUpdateCache, key, keyCount)
};

async function doGetLiveScore(root: any, args: any, context: any, isUpdateCache: any, key: any, keyCount: any) {

  try {
    matchlock.flag = true
    //检查参数
    let where = await getWheres(args)
    //检查分页
    let { limit, offset, order } = checkPages(args);
    //从数据库中获取数据
    let { t, count } = await queryMatchsFromDb(limit, where, offset, order, args);
    let counts: any = count[0] || 0
    //记录查询锁
    matchlock.flag = false
    //实时整理初始的数据,足球与篮球通用,不需要查询微服务的部分
    t = initBaseMatchsData(t);

    //获取7M sportsdt的数据,足球与篮球通用
    try {
      t = await initSportsdtBaseData(t);
    } catch (e) {
      console.info(e);
    }
    //获取7M的足球实时比分数据
    try {
      t = await addSportsdtScoreLiveData(t);
    } catch (e) {
      console.info(e);
    }

    //获取nami的足球实时比分数据
    try {
      t = await addNamiScoreLiveData(t);
    } catch (e) {
      console.info(e);
    }

    //获取7M的篮球实时比分数据
    try {
      t = await addSportsdtBasketballLiveData(t);
    } catch (e) {
      console.info(e);
    }

    //计算情报数据
    t = getSportsInfoCount(t)

    //测试数据,此部分的代码只是为了测试使用
    if (args.isTest != null && args.isTest == 1) {
      addTestData(t);
    }

    //重新排序
    //t= JSON.parse( JSON.stringify(t))
    if(args.order==null){
      t = _.concat(
        _.filter(t, (o: any) => o.MatchState != "未" && o.Sportsdt && o.Sportsdt.SportsdtMatchId),
        _.filter(t, (o: any) => o.MatchState == "未" && o.Sportsdt && o.Sportsdt.SportsdtMatchId)
      )
    }

    if (args.infoId && t.length > 1) {
      //优先使用竞足的数据
      t = _.concat(
        _.orderBy(_.filter(t, (o: any) => o.LotteryId == 72), ['MatchTime'], ['desc']),
        _.orderBy(_.filter(t, (o: any) => o.LotteryId == 45), ['MatchTime'], ['desc']),
        _.orderBy(_.filter(t, (o: any) => o.LotteryId != 72 && o.LotteryId != 45), ['MatchTime'], ['desc'])
      )
      //t=_.orderBy(t,['MatchTime'],['desc'])
      t = _.take(t, 1)
    }

    if (args.lotId == 45 || args.lotId == 74) {
      t = _.orderBy(t, (o) => {
        return parseInt(o.IssueName) * 1000 + parseInt(o.MatchNumber)
      })
    }

    let result = { matchs: t, count: counts.dataValues ? counts.dataValues.count || 0 : 0 };

    //防止恶意进攻,超过查询范围内的不进入到缓存
    if (t.length > 0) {
      setMatchs(key, keyCount, result, args)
    }

    return result
  } catch (e) {
    console.info(e);
    matchlock.flag = false
    let result = await get24HoursCache(key, keyCount)

    if (result) {
      setMatchs(key, keyCount, result, args)
      return result
    } else {
      throw e
    }
  }

  //基础数据查询数据库,篮球实时比分的数据查询老的core数据库
  async function queryMatchsFromDb(limit: any, where: any, offset: any, order: any, args: any) {
    if (args.lotId == 73) {
      // let t =  getMatchListFromOldDb(limit, where, offset, order);
      // //从数据库中获取总记录数
      // let count =  getMatchCountFromOldDb(where);

      let t = getMatchListFromDb(limit, where, offset, order);
      //从数据库中获取总记录数
      let count = getMatchCountFromDb(where);

      let result = await Promise.all([t, count])
      let matchs = _.map(result[0], (match: any) => {
        //match.MatchTime = moment(match.MatchTime).valueOf();
        return match
      })
      return { t: matchs, count: result[1] };
    } else {
      let t = getMatchListFromDb(limit, where, offset, order);
      //从数据库中获取总记录数
      let count = getMatchCountFromDb(where);
      let result = await Promise.all([t, count])
      let matchs = _.map(result[0], (match: any) => {
        //match.MatchTime = moment(match.MatchTime).valueOf();
        return match
      })
      return { t: matchs, count: result[1] };
    }
  }

  //足球实时比分
  async function addSportsdtScoreLiveData(t: any) {
    try {
      if (args.infoId != null || args.matchState == '未' || args.matchState == '进行中' || (t.length == 1)) {

        let livedata = await api_hemera.query('sport', 'getlivedata_from_db', root, {}, 1);
        if (livedata == null) {
          livedata = await api_hemera.queryWithRealtimeFirst('sport', 'getlivedata', root, {});
        }
        livedata = livedata.LiveData;
        t = _.map(t, (o) => {
          if (o.Sportsdt.SportsdtMatchId && livedata[o.Sportsdt.SportsdtMatchId]) {
            let sportsdtLiveData = livedata[o.Sportsdt.SportsdtMatchId];
            let timediff = moment().diff(moment(sportsdtLiveData.TStartTime), "minutes");
            let isUseSportsdt = true;
            // try{
            //   if(parseInt(o.MatchState)>timediff){
            //     isUseSportsdt = false;
            //   }
            // }catch (e:any){}
            if (isUseSportsdt) {
              if (o.Sportsdt.SportsdtIsah == 1) {
                o.BcBf = "";
                if (sportsdtLiveData.Half.length > 0) {
                  let bcbfs = sportsdtLiveData.Half.split("-")
                  o.BcBf = `${bcbfs[1]}-${bcbfs[0]}`;
                }
                if (sportsdtLiveData.Score.length == 2)
                  o.QcBf = `${sportsdtLiveData.Score[1]}-${sportsdtLiveData.Score[0]}`;
                o.HostRed = sportsdtLiveData.RedCard[1];
                o.GuestRed = sportsdtLiveData.RedCard[0];
                o.HostYellow = sportsdtLiveData.YellowCard[1];
                o.GuestYellow = sportsdtLiveData.YellowCard[0];
              } else {
                o.BcBf = sportsdtLiveData.Half;
                if (sportsdtLiveData.Score.length == 2)
                  o.QcBf = `${sportsdtLiveData.Score[0]}-${sportsdtLiveData.Score[1]}`;
                o.HostRed = sportsdtLiveData.RedCard[0];
                o.GuestRed = sportsdtLiveData.RedCard[1];
                o.HostYellow = sportsdtLiveData.YellowCard[0];
                o.GuestYellow = sportsdtLiveData.YellowCard[1];
              }

              switch (sportsdtLiveData.Status) {
                case 1:
                  o.MatchState = timediff <= 45 ? `${timediff}` : "45+";
                  break;
                case 2:
                  o.MatchState = "中场";
                  break;
                case 3:
                  o.MatchState = timediff <= 45 ? `${45 + timediff}` : "90+";
                  break;
                case 4:
                  o.MatchState = "完";
                  break;
              }
              //             比赛状态值,表示如下
              // 0 :未开始
              // 1:上半场
              // 2:中场
              // 3:下半场
              // 4:完场
              // 5:中断
              // 6:取消
              // 7:加时
              // 8:加时
              // 9:加时
              // 10:完场
              // 11:点球大战
              // 12:全场结束
              // 13:延期
              // 14: 腰斩
              // 15: 待定
              // 16:金球
              // 17:未开始
              // *0、17同为未开始,7、8、9为加时,4、10、12完场


              //篮球状态
              // 0 :未开始
              // 1:第一节
              // 2:第一节完
              // 3:第二节
              // 4:第二节完
              // 5:第三节
              // 6:第三节完
              // 7:第四节
              // 8:第四节完
              // 9:完场
              // 10:加时
              // 11:完场(加)
              // 12:中断
              // 13:取消
              // 14: 延期
              // 15: 腰斩
              // 16待定
            }
          }
          return o;
        });
      }
    }
    catch (e:any) {
      console.info(e);
    }
    return t;
  }

  //纳米数据的实时比分
  async function addNamiScoreLiveData(t: any) {
    try {
     
      if ((args.matchState == '未' || args.matchState == '进行中') && (t.length >= 1)) {
        // console.info(`begin addNamiScoreLiveData`);
        let nami_score_list_obj = await nami_data.get_local_nami_realtime_score();
        let sportsdt_id_list = _.map(nami_score_list_obj.id_list,"sportsdt_match_id");

        t = _.map(t, (o) => {
          if (o.Sportsdt.SportsdtMatchId && sportsdt_id_list.includes(o.Sportsdt.SportsdtMatchId)) {
            let leisu_id = _.find(nami_score_list_obj.id_list,(id_obj:any)=>{
              return id_obj.sportsdt_match_id == o.Sportsdt.SportsdtMatchId
            }).leisu_match_id;

            let livedata = _.find(nami_score_list_obj.list,(name_obj)=>{return name_obj.id==leisu_id});
            // let livedata = _.find(nami_score_list_obj.list,(name_obj)=>{return name_obj.score[1]>1});//测试
            // console.info(JSON.stringify(livedata),moment(livedata.score[4]*1000).format("YYYY-MM-DD HH:mm:ss"));
            if(livedata==null){
              return o
            }

            // console.info(`找到的雷速数据`)

            let score_list = livedata.score;
            // livedata.score字段格式:[2783605,8,[1, 0, 0, 0, -1, 0, 0],[1, 0, 0, 0, -1, 0, 0],0,""]
            // 0:"纳米比赛id - int"
            // 1:"比赛状态,详见状态码->比赛状态 - int"
            // 2:Array[7]
            // 0:"主队比分(常规时间) - int"
            // 1:"主队半场比分 - int"
            // 2:"主队红牌 - int"
            // 3:"主队黄牌 - int"
            // 4:"主队角球,-1表示没有角球数据 - int"
            // 5:"主队加时比分(120分钟,即包括常规时间比分),加时赛才有 - int"
            // 6:"主队点球大战比分(不包含常规时间及加时赛比分),点球大战才有 - int"
            // 3:Array[7]
            // 0:"客队比分(常规时间) - int"
            // 1:"客队半场比分 - int"
            // 2:"客队红牌 - int"
            // 3:"客队黄牌 - int"
            // 4:"客队角球,-1表示没有角球数据 - int"
            // 5:"客队加时比分(120分钟,即包括常规时间比分),加时赛才有 - int"
            // 6:"客队点球大战比分(不包含常规时间及加时赛比分),点球大战才有 - int"
            // 4:"开球时间戳,上/下半场开球时间(根据比赛状态判断) - int"
            // 5:"备注信息,可忽略 - string"
            let timediff = moment().add(4,'second').diff(moment(score_list[4]*1000), "minutes");
            if (o.Sportsdt.SportsdtIsah != 1) {
              o.QcBf = `${score_list[2][0]}-${score_list[3][0]}`;
              o.BcBf = `${score_list[2][1]}-${score_list[3][1]}`;
              o.HostRed = score_list[2][2];
              o.GuestRed = score_list[3][2];
              o.HostYellow = score_list[2][4];
              o.GuestYellow = score_list[3][4];
            }else{
              o.QcBf = `${score_list[3][0]}-${score_list[2][0]}`;
              o.BcBf = `${score_list[3][1]}-${score_list[2][1]}`;
              o.HostRed = score_list[3][2];
              o.GuestRed = score_list[2][2];
              o.HostYellow = score_list[3][4];
              o.GuestYellow = score_list[2][4];
            } 

            // 状态码score_list[1]	描述
            // 0	比赛异常,说明:暂未判断具体原因的异常比赛,可能但不限于:腰斩、取消等等,建议隐藏处理
            // 1	未开赛
            // 2	上半场
            // 3	中场
            // 4	下半场
            // 5	加时赛
            // 6	加时赛(弃用)
            // 7	点球决战
            // 8	完场
            // 9	推迟
            // 10	中断
            // 11	腰斩
            // 12	取消
            // 13	待定
            switch (score_list[1]) {
              case 2:
                o.MatchState = timediff <= 45 ? `${timediff}` : "45+";
                break;
              case 3:
                o.MatchState = "中场";
                break;
              case 4:
                o.MatchState = timediff <= 45 ? `${45 + timediff}` : "90+";
                break;
              case 5:
                o.MatchState = "加时";
                break;
              case 7:
                o.MatchState = "点球";
                break;
              case 8:
                o.MatchState = "完"; break;
              case 9:
                o.MatchState = "推迟"; break;
              case 10:
                o.MatchState = "中断"; break;
              case 11:
                o.MatchState = "腰斩"; break;
              case 12:
                o.MatchState = "取消"; 
                break;
            }
          }
          return o;
        });
      }
    }
    catch (e:any) {
      console.info(e);
    }
    return t;
  }

  //篮球实时比分
  async function addSportsdtBasketballLiveData(t: any) {
    try {

    }
    catch (e:any) {
      console.info(e);
    }
    return t;
  }

  async function initSportsdtBaseData(t: any) {
    // let [ms_schedules,livegame] = await Promise.all([
    //   api_hemera.query('info', 'getmsschedulesbycoreids', root, { coreIds: _.map(t, o => o.Id) }),
    //   api_hemera.query('sport', 'getlivegame', root, {})
    // ]);
    //let ms_schedules = await api_hemera.query('info', 'getmsschedulesbycoreids', root, { coreIds: _.map(t, o => o.Id) },200);

    let ms_schedules = await ms_schedule.getMsSchedulesByCoreIds({ CoreIds: _.map(t, o => o.Id) });

    t = t.map((o: any) => {
      o = JSON.parse(JSON.stringify(o));
      let schedule = _.find(ms_schedules, s => {
        return s.core_match_id == o.Id;
      });
      o.Sportsdt = {};
      try {
        o.YiqiuMatchId = schedule.yiqiu_match_id;
        if (schedule != null) {
          o.Sportsdt.SportsdtMatchId = schedule.sportsdt_match_id;
          o.Sportsdt.N = schedule.sportsdt_n;
          o.Sportsdt.SportsdtIsah = schedule.sportsdt_isah;
          if(o.InfoId==null&&schedule.info_match_id!=null){
            o.InfoId=schedule.info_match_id;
          }
          if (schedule.sportsdt_isah == 1) {
            o.Sportsdt.SportsdtHostTeamId = schedule.sportsdt_guest_team_id;
            o.Sportsdt.SportsdtGuestTeamId = schedule.sportsdt_host_team_id;
          } else {
            o.Sportsdt.SportsdtHostTeamId = schedule.sportsdt_host_team_id;
            o.Sportsdt.SportsdtGuestTeamId = schedule.sportsdt_guest_team_id;
          }

          o.Sportsdt.SportsdtCompetitionId = schedule.sportsdt_competition_id;
          o.Sportsdt.SportsdtType = schedule.sportsdt_type;
          o.Sportsdt.SportsdtDegree = schedule.sportsdt_degree;
          o.Sportsdt.SportsdtNum = schedule.sportsdt_num;
          o.Sportsdt.SportsdtStarttime = schedule.sportsdt_starttime;
          o.Sportsdt.LotteryId = o.LotteryId;
        }

        //`http://data.7m.com.cn/team_data/${params.teamid}/logo_img/club_logo.jpg`

        // if(livegame&&livegame.Competition&&livegame.Competition[schedule.sportsdt_competition_id]){
        //   o.GameName = livegame.Competition[schedule.sportsdt_competition_id].ShortName
        // }
      }
      catch (e:any) { }
      o.Odds = {};
      try {
        if (schedule != null) {
          o.Odds.CoreId = o.Id;
          o.Odds.CoreLotteryId = o.LotteryId;
          o.Odds.SportsdtId = schedule.sportsdt_match_id;
          o.Odds.MatchState = o.MatchState;
          o.Odds.BetSps = o.BetSps
          o.Odds.SportsdtIsah = o.Sportsdt.SportsdtIsah
        }
      } catch (e) {
        console.info(e);
      }
      return o;
    });
    return t;
  }

  function addTestData(t: any) {
    if (args.matchState == '未' && t.length > 0 && args.lotId == 72) {
      t[0].MatchState = moment().format("mm");
      //t[0].QcBf = `0-${Math.round(parseInt(moment().format("ss")) / 20)}`;
      t[0].QcBf = `0-${Math.round(moment().minute() % 2)}`;
    }
    if (args.matchState == '未' && t.length > 1 && args.lotId == 72) {
      t[1].MatchState = moment().format("mm");
      //t[0].QcBf = `0-${Math.round(parseInt(moment().format("ss")) / 20)}`;
      t[1].QcBf = `0-${Math.round(moment().add(14, 'second').minute() % 3)}`;
    }
  }

  function initBaseMatchsData(t: any) {
    t = t.map((item: any) => {
      item.Issue = item.T_Issue;
      item.Lottery = item.T_Lottery;
      item.Odds100 = item.T_Odds100;
      if (!item.GameName) {
        item.GameName = '';
      }
      //应对易求页面显示,当未知天气时,天气与温度一起显示出来,天气不显示
      if (!item.Weather || item.Weather == '未知') {
        item.Weather = '';
      }

      try {
        item.MatchTime = moment(item.MatchTime).utc()
      } catch (e) {
        console.info(e);
      }

      try {
        if (item.Temperature && item.Temperature.indexOf('℃') < 0 && item.Temperature.length > 0) {
          item.Temperature = item.Temperature.split('&')[0]
          item.Temperature = `${item.Temperature}℃`
        }
      } catch (e) {
        console.info(e);
      }

      //item.MatchTime = moment(item.MatchTime).add(-8, "hour");
      item.MatchState = item.MatchState.replace('节', '节 ');
      return item;
    });
    let list = [];
    for (let p of t) {
      list.push(p);
    }
    t = _.filter(list, item => {
      if (item)
        return true;
      else
        return false;
    });
    return t;
  }

  async function getMatchCountFromDb(where: any) {
    return await Model.Match.findAll({
      attributes: [[sequelize.fn('COUNT', sequelize.col('Id')), 'count']],
      where: where,
    });
  }

  async function getMatchListFromDb(limit: any, where: any, offset: any, order: any) {
    return await Model.Match.findAll({
      limit: limit || 20,
      // include: [
      //   { model: Model.Issue, },
      //   { model: Model.Lottery, },
      // ],
      where: where,
      offset: offset,
      order: order,
    });
  }

  async function getMatchCountFromOldDb(where: any) {
    // return await OldModel.Match.findAll({
    //   attributes: [[sequelize.fn('COUNT', sequelize.col('Id')), 'count']],
    //   where: where,
    // });
  }

  async function getMatchListFromOldDb(limit: any, where: any, offset: any, order: any) {
    // return await OldModel.Match.findAll({
    //   limit: limit || 20,
    //   include: [
    //     { model: OldModel.Issue, },
    //     { model: OldModel.Lottery, },
    //   ],
    //   where: where,
    //   offset: offset,
    //   order: order,
    // });
  }

  function checkPages(args:any) {
    // console.info(args,`check pages args`);
    let offset = 0;
    if (args.offset) {
      offset = args.offset;
    }
    let limit = 20;
    if (args.limit && args.limit <= 500 && args.limit > 0) {
      limit = args.limit;
    }
    let order: any = [["MatchTime", "asc"], ["Id", "asc"]];
    //let order = [['Id', 'DESC']];
    // ("LotteryId", "IssueName", "MatchNumber");
    //let order = [["LotteryId","ASC"],["IssueName","ASC"],["MatchNumber","ASC"]]
  
    if ((args.lotId == 45 || args.lotId == 74) && args.matchState == '未') {
      order = [["MatchTime", "asc"]];
      //[sequelize.fn('max', sequelize.col('age')), 'DESC'],
    }
    if ((args.lotId == 45 || args.lotId == 74) && args.matchState == '完') {
      order = [["IssueName", "asc"]];
    }
    if (args.lotId == 72 && args.matchState == '未') {
      order = [["MatchTime", "asc"], ["MatchNumber", "asc"]];
    }
    if (args.lotId == 72 && args.matchState == '完') {
      order = [["IssueName", "asc"], ["MatchNumber", "asc"]];
    }
    if (args.infoId) {
      limit = 10;
      order = [["MatchTime", "desc"]];
    }

    if (args.order&&args.order[0]?.length==2) {
      order = args.order;
    }
    return { limit, offset, order };
  }
}

function getSportsInfoCount(list: any) {
  return _.map(list, (item) => {
    if(item==null){
      return item
    }
    //情报
    item.SportsInfoCount = 0
    if (item.SportsInfo) {
      if (!item.SportsInfo.HostBad)
        item.SportsInfo = JSON.parse(item.SportsInfo)
      item.SportsInfoCount = item.SportsInfoCount + item.SportsInfo.HostBad.length
      item.SportsInfoCount = item.SportsInfoCount + item.SportsInfo.GuestBad.length
      item.SportsInfoCount = item.SportsInfoCount + item.SportsInfo.HostGood.length
      item.SportsInfoCount = item.SportsInfoCount + item.SportsInfo.GuestGood.length
      if (item.SportsInfo.PredictionDesc) {
        item.SportsInfoCount = item.SportsInfoCount + 1
      }
    } else {
      item.SportsInfo = {
        GuestBad: [],
        GuestGood: [],
        HostBad: [],
        HostGood: [],
        PredictionDesc: ''
      }
    }
    if (item.JcInfo) {
      try {
        let jcInfo = item.JcInfo
        if (!item.JcInfo.HostBad)
          jcInfo = JSON.parse(item.JcInfo)
        item.SportsInfoCount = item.SportsInfoCount + jcInfo.HostBad.length
        item.SportsInfoCount = item.SportsInfoCount + jcInfo.GuestBad.length
        item.SportsInfoCount = item.SportsInfoCount + jcInfo.HostGood.length
        item.SportsInfoCount = item.SportsInfoCount + jcInfo.GuestGood.length
        if (jcInfo.PredictionDesc) {
          item.SportsInfoCount = item.SportsInfoCount + 1
        }
      } catch (e) {
        console.info(e);
      }
    }

    //情报价格
    item.JcInfoPrice = 500

    return item
  })
}

async function getWheres(args: any) {
  let where: any = {}
  where.MatchTime = {
    $gt: moment().subtract(120, 'day').format('YYYY-MM-DD')
  }
  if (args.sportsdtId) {
    //let ms_schedules = await ms_schedule.getMsSchedulesByCoreIds({CoreIds:_.map(t, o => o.Id)});
    let ms_schedules_item = await info_db.ms_schedule.findOne({
      where: { sportsdt_match_id: args.sportsdtId }
    })

    if (ms_schedules_item != null) {
      where.InfoId = args.info_match_id
      where.LotteryId = { $in: [72, 45, 73, 74] }
    }
  }
  if (args.matchIds) {
    where.Id = { $in: args.matchIds }
  }
  if (args.lotId) {
    where.LotteryId = args.lotId
  } else {
    where.LotteryId = { $in: [72, 45, 73, 74] }
  }
  if (args.lotIds) {
    where.LotteryId = { $in: args.lotIds }
  }
  if (args.issueId) {
    where.IssueId = args.issueId
  }
  if (args.infoId) {
    where.InfoId = args.infoId
    where.LotteryId = { $in: [72, 45, 73, 74] }
  }

  if (args.matchDay) {
    try {
      where.MatchTime = {
        $between: [moment(args.matchDay).format('YYYY-MM-DD'),
        moment(args.matchDay).add(1, 'day').format('YYYY-MM-DD')]
      }
    } catch (e:any) { }
  }

  if (args.matchState) {
    if (args.matchState == '完') {
      where.MatchState = { $in: ['完', '取消', '中断', '推迟', '改期'] }
    } else if (args.matchState == '未') {
      where.MatchTime = {
        $gt: moment().add(-150, 'minute').format('YYYY-MM-DD HH:mm')
      }
      where.MatchState = { $notIn: ['取消', '中断', '推迟', '腰斩', '改期'] }
    } else if (args.matchState == '进行中')
      where.MatchState = { $notIn: ['完', '取消', '中断', '推迟', '腰斩', '改期'] }
    else
      where.MatchState = args.matchState
  } else {
    where.MatchState = { $notIn: ['腰斩'] }
  }
  if (args.type) {

  }
  if (args.userId) {

  }
  if (args.issueName && args.issueName != null) {
    //where.IssueName = {$in:[args.issueName]}
    where.IssueName = args.issueName
  }
  if (args.isContainSportsInfo == 1) {
    where.SportsInfo = { $not: null }
  }
  if (args.isContainSportsInfo == 0) {
    where.SportsInfo = null
  }

  return where
}

async function get10SecondsCache(key: any, keyCount: any) {
  let reply:any = await client.get(`${key}_${moment().format('YYYYMMDDHH')}`);
  if (reply && reply.length > 0) {
    let replyCount:any = await client.get(`${keyCount}_${moment().format('YYYYMMDDHH')}`);
    const buffer = Buffer.from(reply, 'base64');
    let str_json_result = (await zlib.unzipSync(buffer)).toString();
    reply = JSON.parse(str_json_result)
    reply = getSportsInfoCount(reply)
    let result = { matchs: reply, count: JSON.parse(replyCount) };
    return result
  }
  return null
}

async function get24HoursCache(key: any, keyCount: any) {
  let time24 = 'time24'
  key = key + time24
  let reply:any = await client.get(`${key}`);
  if (reply && reply.length > 0) {
    let replyCount:any = await client.get(`${keyCount}`);
    const buffer = Buffer.from(reply, 'base64');
    let str_json_result = (await zlib.unzipSync(buffer)).toString();
    reply = JSON.parse(str_json_result)
    reply = getSportsInfoCount(reply)
    let result = { matchs: reply, count: JSON.parse(replyCount) };
    return result
  }
  return null
}

async function setMatchs(key: any, keyCount: any, result: any, args: any) {
  let buffer = await zlib.gzipSync(JSON.stringify(result.matchs))
  let z_result = buffer.toString("base64");
  await client.setex(`${key}_${moment().format('YYYYMMDDHH')}`, 20, z_result)
  //更新为5秒
  client.expire(`${key}_${moment().format('YYYYMMDDHH')}`, 20)
  await client.setex(`${keyCount}_${moment().format('YYYYMMDDHH')}`, 20, JSON.stringify(result.count))
  //更新为5秒
  client.expire(`${keyCount}_${moment().format('YYYYMMDDHH')}`, 20)

  let time24 = 'time24'
  await client.setex(key + time24, 60 * 60 * 24 * 7, z_result)
  client.expire(key + time24, 60 * 60 * 24 * 7)
  await client.setex(keyCount + time24, 60 * 60 * 24 * 7, JSON.stringify(result.count))
  client.expire(keyCount + time24, 60 * 60 * 24 * 7)
}

//计算概率
const statProbability = async (match: any) => {

  let oddsList = []
  if (match.InfoId && match.LotteryId != 73) {
    oddsList = await Model.Odds100.findAll({ where: { MatchId: match.InfoId } })
  } else if (match.InfoId && match.LotteryId == 73) {
    //oddsList = await Model.NBAOdds100.findAll({where: { MatchId: match.InfoId }})
  }

  return {
    HostProbability: String,
    FlatProbability: String,
    GuestProbability: String,
    MaxProbabilityName: String,
    FirstProbability: String,
    LastProbability: String,
  }
}

// 获取足球概率战力值
function ZqSpPercent(match: any) {

  try {
    let sp = JSON.parse(match.BetSps)["7206"]
    if (!sp || sp.length < 0) {
      return [0, 0]
    }
    let pavg = sp[1] / 2;
    let v1 = [sp[0] + pavg, sp[2] + pavg];
    let sum = v1[0] + v1[1];
    let r = [Math.round(v1[0] / sum * 100), Math.round(v1[1] / sum * 100)];
    let sy = 100 - _.sum(r);
    if (r[0] > r[1]) {
      r[1] += sy;
    }
    else {
      r[0] += sy;
    }
    return r;
  } catch (e:any) {
    return [0, 0]
  }

}



const CompetitionResult = async () => {
  let sql = `SELECT * FROM core_match WHERE \`InfoState\`=true ORDER BY \`LotteryId\` DESC`
  let result = await Core.sequelize.query(sql)
  return result;
}

export async function get_core_match({ lotteryId }: any) {
  try{
    if (!_.includes([72, 74, 75, 45], lotteryId)) {
      return null
    }
    let where:any = {
      MatchState: '未',
      LotteryId: lotteryId,
      MatchTime: { $gte: moment().add(-1,'day').format("YYYY-MM-DD") }
    };

    if(lotteryId == 74){
      where = {
        // MatchState: [null,'未'],
        LotteryId: lotteryId,
        MatchTime: { $gte: moment().add(-1,'day').format("YYYY-MM-DD") }
      };
    }

    let result: any = await Core.core_match.findAll({
      where: where,
      order: [["MatchTime", "asc"], ["MatchNumber", "asc"]],
      limit: 500,
      attributes: [`Id`, `updateflag`, `LotteryId`, `IssueId`, `IssueName`, `BdGameType`,
        `BdGameTypeColor`, `GameName`, `GameColor`, `BdMatchDay`, `MatchNumber`,
        `MatchRound`, `MatchTime`, `StopSellTime`, `PrintEndTime`,
        `InfoId`, `HostId`, `HostName`, `HostRank`, `HostRed`, `HostYellow`,
        `LetScore`, `PreTotalScore`, `GuestId`, `GuestName`, `GuestRank`,
        `GuestRed`, `GuestYellow`, `MatchState`, `ResultState`, `Results`,
        `BetSps`, `Commends`, `AvgOdds`, `GgStopPlayIds`, `DgStopPlayIds`,
        `IsAutoUpdate`, `BcBf`, `QcBf`, `ResultSps`,
        //`OkoooId`, `BetradarId`, 
        //`IsTextLive`, `PlayerData`, `TimeData`, `LiveData`, `TechnicalStatistics`, 
        `Stoppage`, `Weather`, `Temperature`, `SportsInfo`, `SportsLive`,
        // `SportsLineup`, `SportsStatistics`, `SportsInjury`, `SportteryMatchId`, `JcInfo`, 
        `DfcpImgUrl`,
        `VideoUrl`,
        // `CreatedAt`, `UpdatedAt`, 
        `InfoState`, `WinLoseRate`, `WinLoseCount`,
        `RangQiuWinLoseRate`, `RangQiuWinLoseCount`, `SportteryTempId`, `SportteryHostId`,
        //`SportteryGuestId`, `SportteryHostName`, `SportteryGuestName`, `TempId`, `GuessRate`, 
        //`GuessTotal`, `GuessJoinTotal`, `GuessWinTotal`, `GuessEquelTotal`, `GuessLoseTotal`
      ]
    })
  
    let ms_schedule_data_list:any = await Core.ms_schedule.findAll({
      where:{
        core_match_time: { $gte: moment().format("YYYY-MM-DD") }
      }
    })
  
    result = JSON.parse(JSON.stringify(result));
  
    result = _.map(result, (o) => {
      
      if(o.InfoId==null||o.InfoId==0){
        o.InfoId = (_.find(ms_schedule_data_list,(m)=>{
          return m.core_match_id==o.Id
        })||{} as any).info_match_id;
      }
  
      let ms_item = _.find(ms_schedule_data_list,(m)=>{
        return m.core_match_id==o.Id
      })
      if(ms_item){
        // console.info(`ms_item.yiqiu_match_id`,ms_item.yiqiu_match_id)
        o.YiqiuMatchId = ms_item.yiqiu_match_id;
      }
      
      if (o) {
        delete o.JcInfo;
        delete o.SportsInfo;
        delete o.CreatedAt;
        delete o.UpdatedAt;
        delete o.updateflag;
        delete o.IssueId;
        delete o.SportsLive;
        delete o.SportsLineup;
        delete o.SportsStatistics;
        delete o.SportsInjury;
        delete o.GuessRate;
        delete o.GuessTotal;
        delete o.GuessJoinTotal;
        delete o.GuessWinTotal;
        delete o.GuessEquelTotal;
        delete o.GuessLoseTotal;
  
        delete o.OkoooId;
        delete o.BetradarId;
        delete o.IsTextLive;
        delete o.PlayerData;
        delete o.TimeData;
        delete o.TechnicalStatistics;
      }
      return o;
    });

    // console.info(`result`,result);
    if(lotteryId == 74){
      let game_list = (await info_db.ms_soccer_game.findAll(
        {
          limit:100,
          // `id`, `match_time`,`zucai_issue_name`, `zucai_number`, info_match_id, status, odds 
          attributes: [`id`, `match_time`,`zucai_issue_name`, `zucai_number`, `info_match_id`, `status`, `odds`],
          where:{
            is_zucai:1,
            match_time: { $gte: moment().format("YYYY-MM-DD") },
          }
        }
      ))?.map((a:any) => a.dataValues) ?? [];

      // 通过zucai_issue_name与zucai_number找到对应比赛
      result = _.map(result, (o) => {
        let game = _.find(game_list,(g)=>{
          return g.zucai_issue_name==o.IssueName&&g.zucai_number==o.MatchNumber
        });
        if(game){
          o.odds = game.odds;
          o.YiqiuMatchId = o.YiqiuMatchId || game.id;
          o.MatchState = o.MatchState||'未';
          if(moment(o.MatchTime)<moment()&&o.MatchState=="未"){
            o.MatchState="";
          }
          if(o.odds?.['3000181']?.eu){
            o.AvgOdds = o.AvgOdds || _.map(o.odds?.['3000181'].eu,(n:any)=>Number(n).toFixed(2)).join(",");
          }else{
            o.AvgOdds='--,--,--';
          }
          //测试的时候可以留下odds
          delete o.odds;
        }
        return o
      })
    }
  
    result = _.filter(result,(o)=>{
      if(o.MatchState!="未"){
        return false;
      }
      return o.BetSps!="{\"7201\":[0.0,0.0,0.0],\"7202\":[0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0],\"7203\":[0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0],\"7204\":[0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0],\"7206\":[0.0,0.0,0.0]}"
    })
  
    return result
  }catch(e:any){
    console.info(`lottery_get_matchs 获取比赛数据异常:${e.message}`)
  }

}


export { liveScore, statProbability, ZqSpPercent, CompetitionResult }