import * as Core from '../table';
import Model = require('../model');
import moment = require('moment');
import _ = require('lodash');

const config = require("../../../../config");

import { cache,redis as client, redis, task_lock } from '../../../cache'

async function Issue(issueId: any) {
  let t = await Model.Issue.findOne({
    where: {
      Id: issueId
    }
  });
  return t;
};

const Issues = async (root: any, args: any, context: any, isUpdateCache: any = false) => {
  let lotId = 72
  if (parseInt(args.lotId) > 0) {
    lotId = parseInt(args.lotId)
  }
  // console.info(args);

  return cache(async ({lotId,limit}: any) => {
    let sql = `select * from core_issue where LotteryId=${lotId} 
  and  (EndTime<'${moment().add(3, `hour`).format(`YYYY-MM-DD HH:mm:ss`)}')
  order by Name desc limit ${args.limit||30}
  `

    if([45,73,72,74,75].includes(lotId)&&(args.is_end==null||args.is_end==1)){
      let old_match: any = await Core.Match.findOne({
        where: {
          //MatchTime:{$lt:`${moment().add(-118,"minute").format(`YYYY-MM-DD HH:mm:ss`)}`},
          //IssueName:`${moment().format(`YYYY-MM-DD HH:mm:ss`)}`,
          LotteryId: lotId,
          MatchState: '完',
        },
        limit: 1,
        order: [["MatchTime", "desc"]]
      })
     
      if (old_match != null) {
        if(lotId==72&&old_match.IssueName!=moment().format(`YYYY-MM-DD`)){
          sql = `select * from core_issue where LotteryId=${lotId} 
  and  (EndTime<'${moment().add(3, `hour`).format(`YYYY-MM-DD HH:mm:ss`)}')
  order by Name desc limit ${args.limit||30}
  `
        }else{
          sql = `select * from core_issue where LotteryId=${lotId} 
      and Name<='${old_match.IssueName}'
      order by StartTime desc limit  ${args.limit||30}
      `
        }
        
      }
    }
    else if([45,72,73,74,75].includes(lotId)){ 
      // 1 完场的期号 2 是未完场的期号 3不限制是否完场 0 代表当前期号
      switch(args.is_end){
         case 2:
          sql = `select * from core_issue where LotteryId=${lotId} 
          and  EndTime>'${moment().format(`YYYY-MM-DD HH:mm`)}'
          order by Name desc limit  ${args.limit||30}
          `;
          break;
         case 3:
          sql = `select * from core_issue where LotteryId=${lotId} 
          and  StartTime>'${moment().add(-100,`day`).format(`YYYY-MM-DD HH:mm:ss`)}'
          order by Name desc limit  ${args.limit||30}
          `;
          break;
          case 0:
            sql = `select * from core_issue where LotteryId=${lotId} 
            and  StartTime>'${moment().add(-3,`hour`).format(`YYYY-MM-DD HH:mm:ss`)}'
            order by Name asc limit 1
            `;
          break;
      }
     
    }

    // console.info(sql);
    let t = await Core.sequelize.query(sql)

    t = checkList(t);

    return t;
  }, {lotId,is_end:args.is_end}, 5, "pginfo_issue:vy5", 60, 100)

};

const MatchTimes = async (root: any, args: any, context: any, isUpdateCache: any = false) => {
  let lotId = 72
  if (parseInt(args.lotId) > 0) {
    lotId = parseInt(args.lotId)
  }
  let key = `${config.CachePrefix}match:matchMatchDates:v1_${args.lotId}`
  let reply = await client.get(key);
  try {
    if (reply && reply.length > 0 && !isUpdateCache) {
      return JSON.parse(reply)
    }
  } catch (e:any) {
    console.info(e)
  }
  let sql = `
  select distinct to_char("MatchTime",'YYYY-MM-DD') as "MatchTime"
from core_match
where "LotteryId"=${lotId}  and "MatchTime">'${moment().add(-20, 'day').format('YYYY-MM-DD')}'
ORDER BY "MatchTime" desc limit 13
  `

  let t = await Core.sequelize.query(sql)

  t = checkList(t)
  t = _.map(t, o => o.MatchTime)

  await client.set(key, JSON.stringify(t))
  client.expire(key, 60)

  return t;
};

function checkList(list: any) {
  if (list && list.length > 0) {
    return list[0]
  }
  return []
}

export { Issue, Issues, MatchTimes }