import { Inject, Logger, Provide } from '@midwayjs/decorator';
import { BaseService } from 'midwayjs-cool-core';
import { ILogger } from '@midwayjs/logger';
import { Utils } from '../../../comm/utils';
import * as _ from 'lodash';
import { ShuyouGameTargetEntity } from '../../shuyou/entity/game_target';
import { ShuyouGameCompleteEntity } from '../../shuyou/entity/game_complete';
import { ShuyouGameTaskEntity } from '../../shuyou/entity/game_task';
import { InjectEntityModel } from '@midwayjs/orm';
import { Repository } from 'typeorm';
import { ShuyouReasonIncompleteEntity } from '../../shuyou/entity/reason_incomplete';
import { ShuyouDataActiveEntity } from '../../shuyou/entity/data_active';
import { ShuyouUtilsService } from '../../shuyou/service/utils';
import { ShuyouGameAccountEntity } from '../../shuyou/entity/game_account';
import { ShuyouGameAccountRecordEntity } from '../../shuyou/entity/game_account_record';
import { ShuyouTaskAccountRecordEntity } from '../../shuyou/entity/task_account_record';
import { ShuyouTargetFlagService } from './flag';
import { ShuyouTargetFlagEntity } from '../entity/flag';
import { ShuyouGameCompleteHandEntity } from '../../shuyou/entity/game_complete_hand';
import { ShuyouData23Entity } from '../../shuyou/entity/data_23';
// import { parse } from 'path';

/**
 * 描述
 */
@Provide()
export class TaskShuyouService extends BaseService {
  @Logger()
  logger: ILogger;

  @Inject()
  utils: Utils;

  @InjectEntityModel(ShuyouGameTargetEntity)
  ShuyouGameTargetEntity: Repository<ShuyouGameTargetEntity>;

  @InjectEntityModel(ShuyouGameAccountEntity)
  ShuyouGameAccountEntity: Repository<ShuyouGameAccountEntity>;

  @InjectEntityModel(ShuyouGameCompleteEntity)
  ShuyouGameCompleteEntity: Repository<ShuyouGameCompleteEntity>;

  @InjectEntityModel(ShuyouGameTaskEntity)
  ShuyouGameTaskEntity: Repository<ShuyouGameTaskEntity>;

  @InjectEntityModel(ShuyouReasonIncompleteEntity)
  ShuyouReasonIncompleteEntity: Repository<ShuyouReasonIncompleteEntity>;

  @InjectEntityModel(ShuyouDataActiveEntity)
  ShuyouDataActiveEntity: Repository<ShuyouDataActiveEntity>;

  @Inject()
  shuyouUtilsService: ShuyouUtilsService;

  @InjectEntityModel(ShuyouGameAccountRecordEntity)
  ShuyouGameAccountRecordEntity: Repository<ShuyouGameAccountRecordEntity>;

  @InjectEntityModel(ShuyouTaskAccountRecordEntity)
  ShuyouTaskAccountRecordEntity: Repository<ShuyouTaskAccountRecordEntity>;

  @Inject()
  ShuyouTargetFlagService: ShuyouTargetFlagService;

  @InjectEntityModel(ShuyouTargetFlagEntity)
  ShuyouTargetFlagEntity: Repository<ShuyouTargetFlagEntity>;

  @InjectEntityModel(ShuyouGameCompleteHandEntity)
  ShuyouGameCompleteHandEntity: Repository<ShuyouGameCompleteHandEntity>;

  @InjectEntityModel(ShuyouData23Entity)
  ShuyouData23Entity: Repository<ShuyouData23Entity>;

  /**
   * 定时提醒未完成
   * @memberof TaskShuyouService
   */
  async sendUnfinishToDing() {
    let updateTime = new Date();

    // 0—9点不报数据
    if (updateTime.getHours() >= 0 && updateTime.getHours() < 9) {
      return 'sendUnfinishToDing  0—9 no send>>>' + updateTime;
    }
    const sql = `
            SELECT
              a.id,a.task_id,a.task_name,DATE_FORMAT(a.new_date,'%Y-%m-%d') AS new_date,a.target_new,a.target_pay,a.target_active,
              IFNULL(c.complete_new, 0) AS complete_new,IFNULL(c.complete_pay, 0) AS complete_pay,game_rate,game_rate_xmy,
              IFNULL(c.complete_active,0) AS complete_active,c.updateTime,c.is_complete,c.amount,
              b.name AS directorName,b.id AS directorId,
              d.type_id AS type_id,d.reason AS reason,d.solution AS solution,
              if(a.target_new - complete_new < 0, 0, a.target_new-complete_new) AS incomplete_new,
              if(a.target_pay - complete_pay < 0, 0, a.target_pay-complete_pay) AS incomplete_pay,
              if(a.target_active - complete_active < 0, 0, a.target_active-complete_active) AS incomplete_active
            FROM
              shuyou_game_target a
              LEFT JOIN shuyou_game_director b ON a.directorId = b.id
              LEFT JOIN shuyou_game_complete c ON a.task_id = c.task_id AND a.new_date = c.new_date 
              LEFT JOIN shuyou_reason_incomplete d ON a.task_id = d.task_id AND a.new_date = d.new_date 
            WHERE
              c.is_complete = 0
            ${this.setSql(updateTime, 'and a.new_date = ?', [
              this.utils.formatDate(new Date(updateTime)),
            ])}
            ORDER BY b.name
        `;
    let returnUnfinish = await this.nativeQuery(sql);
    let text = '';
    let name = '';
    returnUnfinish.forEach(e => {
      let keyword = e.task_name + ',';
      if (parseInt(e.incomplete_new) > 0) {
        keyword = keyword + '新增差' + e.incomplete_new + ' ';
      }
      if (parseInt(e.incomplete_pay) > 0) {
        keyword = keyword + '付费差' + e.incomplete_pay + ' ';
      }
      if (parseInt(e.incomplete_active) > 0) {
        keyword = keyword + '活跃差' + e.incomplete_active + ' ';
      }
      if (name != e.directorName) {
        text =
          text + '+ **' + e.directorName + ' ↓↓↓**\n>##### ' + keyword + '\n';
      } else {
        text = text + '>##### ' + keyword + '\n';
      }
      name = e.directorName;
    });
    // console.log(text)
    await this.shuyouUtilsService.postRobot(text, '');
    await this.shuyouUtilsService.postRobotEnterpriseWeChat(text);
    // console.log(res)
    return 'sendUnfinishToDing  SUCCESS>>>' + updateTime;
  }

  /**
   * 获取23点10分以后还有付费的游戏
   * @return {*}
   * @memberof TaskShuyouService
   */
  async recordData23() {
    const updateTime = new Date();
    const date = this.utils.formatDate(new Date(updateTime));
    // this.logger.info('recordData23  START>>>' + updateTime)
    const sql = `
        SELECT
          a.task_id,a.task_name,
          b.id AS directorId,
          if(a.target_new - complete_new < 0, 0, a.target_new-complete_new) AS incomplete_new,
          if(a.target_pay - complete_pay < 0, 0, a.target_pay-complete_pay) AS incomplete_pay,
          if(a.target_active - complete_active < 0, 0, a.target_active-complete_active) AS incomplete_active
        FROM
          shuyou_game_target a
          LEFT JOIN shuyou_game_director b ON a.directorId = b.id
          LEFT JOIN shuyou_game_complete c ON a.task_id = c.task_id AND a.new_date = c.new_date 
        WHERE
          c.is_complete = 0
        ${this.setSql(date, 'and a.new_date = ?', [date])}
        ORDER BY b.name
        `;
    let returnUnfinish = await this.nativeQuery(sql);
    await ykhForeach(returnUnfinish, async e => {
      let obj = {
        task_id: e.task_id,
        task_name: e.task_name,
        directorId: e.directorId,
        new_date: date,
        incomplete_new: e.incomplete_new,
        incomplete_pay: e.incomplete_pay,
        incomplete_active: e.incomplete_active,
      };
      // this.logger.warn(obj)
      const resEntity = await this.ShuyouData23Entity.findOne({
        new_date: date,
        task_id: e.task_id,
      });
      if (resEntity) {
        await this.ShuyouData23Entity.createQueryBuilder()
          .update()
          .set(obj)
          .where('new_date = :new_date and task_id = :task_id', {
            new_date: date,
            task_id: e.task_id,
          })
          .execute();
      } else {
        await this.ShuyouData23Entity.createQueryBuilder()
          .insert()
          .into(ShuyouData23Entity)
          .values(obj)
          .execute();
      }
    });
    return 'recordData23  SUCCESS>>>' + updateTime;
  }
  /**
   *
   * 定时更新游戏目标完成
   * @return {*}
   * @memberof TaskShuyouService
   */
  async syncTargetAndComplete() {
    let new_date = this.utils.formatDate(new Date());
    let updateTime = new Date();
    this.logger.info('syncTargetAndComplete>>>' + updateTime);
    let sheepData = [];
    let wslData = [];
    let computerRoomData = [];
    let newComputerRoomData = [];
    // let oldService = []
    let flag = {
      name: 'todayFlag',
      status: 0,
      detail: '',
      time: new Date(),
    };
    // flag.detail = 'syncTargetAndComplete Fail'
    // flag.status = 0
    // await this.ShuyouTargetFlagService.add(flag)

    const sql = `
      SELECT 
        a.*,
        b.xmy_id AS xmy_id,b.unit_price_low AS unit_price_low,b.unit_price_high AS unit_price_high,
        b.game_agentId,b.login_modeId,b.mz_channel, b.mz_id,b.xjf_id
      from 
        shuyou_game_target a
        LEFT JOIN shuyou_game_task b ON a.task_id = b.id
      where 1 = 1 
      ${this.setSql(new_date, 'and a.new_date = ? ORDER BY a.task_id', [
        new_date,
      ])}
    `;
    // console.log(sql)
    const targetList = await this.nativeQuery(sql);
    if (_.isEmpty(targetList)) {
      flag.detail = 'shuyou_game_target is null';
      flag.status = 0;
      await this.ShuyouTargetFlagService.add(flag);
      return (
        'syncTargetAndComplete >>> shuyou_game_target is null >>> ' + updateTime
      );
    }
    //
    const data1 = await queryXMY(new_date, new_date);
    if (_.isEmpty(data1) || data1 == -1) {
      // this.logger.warn('小绵羊后台数据错误')
      flag.detail = '小绵羊后台数据错误';
      flag.status = 0;
      await this.ShuyouTargetFlagService.add(flag);
      // return 'syncTargetAndComplete >>> 小绵羊后台数据错误 >>> ' + updateTime;
    }
    let xmyData = JSON.parse(data1 + '');
    if (xmyData.status == true) {
      sheepData = xmyData.data.list;
      // this.logger.info(sheepData)
      // this.logger.info('获取小绵羊后台数据成功')
    } else {
      sheepData = [];
    }
    let data2 = await queryComputerRoom(new_date);
    console.log(data2);
    if (_.isEmpty(data2) || data2 == -1) {
      // this.logger.warn('老机房后台数据错误')
      flag.detail = '老机房后台数据错误';
      flag.status = 0;
      await this.ShuyouTargetFlagService.add(flag);
      // return 'syncTargetAndComplete >>> 老机房后台数据错误 >>> ' + updateTime;
      computerRoomData = [];
    } else {
      computerRoomData = JSON.parse(data2 + '');
    }
    let data3 = await queryNewComputerRoom(new_date);
    // console.log(data3)
    if (_.isEmpty(data3) || data3 == -1) {
      // this.logger.warn('新机房后台数据错误')
      flag.detail = '新机房后台数据错误';
      flag.status = 0;
      await this.ShuyouTargetFlagService.add(flag);
      // return 'syncTargetAndComplete >>> 新机房后台数据错误 >>> ' + updateTime;
      newComputerRoomData = [];
    } else {
      newComputerRoomData = JSON.parse(data3 + '');
    }

    let data4 = await queryWSL(new_date);
    let wslErr = false;
    // this.logger.warn(data4)
    if (
      _.isEmpty(data4) ||
      data4 == -1 ||
      (data4 + '').indexOf('gameid') == -1
    ) {
      wslErr = true;
      // this.logger.warn('王淑霖付费目标接口数据错误')
      flag.detail = '王淑霖付费目标接口数据错误';
      flag.status = 0;
      await this.ShuyouTargetFlagService.add(flag);
      wslData = [];
      // return 'syncTargetAndComplete >>> 王淑霖付费目标接口数据错误 >>> ' + updateTime;
    } else {
      wslData = JSON.parse(data4 + '');
    }

    //获取用户自己上传的数据（81.70.79.43）
    // const data5 = await queryOldService(new_date)
    // let oldServiceErr = false
    // if (_.isEmpty(data5) || data5 == -1) {
    //   oldServiceErr = true
    //   this.logger.warn('OldService is err')
    //   flag.detail = 'OldService is err'
    //   flag.status = 0
    //   await this.ShuyouTargetFlagService.add(flag)
    //   // return 'syncTargetAndComplete >>> OldService is err >>> ' + updateTime;
    // }
    // let data6 = JSON.parse(data5 + '')
    // if (data6.code == 1) {
    //   oldService = data6.data
    // }
    // console.log(oldService)
    //
    // console.log('开始循环')
    targetList.forEach(async e => {
      var task_id = e.task_id;
      var task_name = e.task_name;
      var new_date = e.new_date;
      var target_pay = 0;
      var complete_new = 0;
      var complete_pay = 0;
      var complete_active = 0;
      var is_complete = 0;
      var amount = 0;
      var game_rate = '0/0/0';
      var game_rate_xmy = '0/0/0';
      if (e.xmy_id != null && e.xmy_id != '' && e.xmy_id != 'null') {
        // 小绵羊游戏处理
        var ifFlag = false;
        if (wslErr == false) {
          for (let sheep of sheepData) {
            // console.log(sheep.game_id)
            if (e.xmy_id == sheep.game_id) {
              ifFlag = true;
              //从wsl接口获取小绵羊付费目标
              for (let wslvalue of wslData) {
                if (wslvalue.gameid == sheep.game_id) {
                  target_pay = wslvalue.money;
                  break;
                }
              }
              complete_new = sheep.user_num;
              complete_pay = sheep.cnt;
              complete_active = sheep.active_user_num;
              amount = sheep.amount;
              break;
            }
          }
          if (ifFlag == false) {
            for (let wslvalue of wslData) {
              if (e.xmy_id == wslvalue.gameid) {
                target_pay = wslvalue.money;
                break;
              }
            }
          }
        } else {
          for (let sheep of sheepData) {
            // console.log(sheep.game_id)
            if (e.xmy_id == sheep.game_id) {
              complete_new = sheep.user_num;
              complete_pay = sheep.cnt;
              complete_active = sheep.active_user_num;
              amount = sheep.amount;
              break;
            }
          }
          // let resXmy = await queryXmyPay(this.utils.formatDate(new_date), e.xmy_id)
          // // {"code":0,"msg":"success","data":[{"amount":"6.00","num":"10","use_num":"0"}]}
          // // console.log(resXmy)
          // let xmyPay = JSON.parse(resXmy + '')
          // if (xmyPay.code == 0 && !_.isEmpty(xmyPay.data)) {
          //   // console.log(xmyPay.data)
          //   target_pay = xmyPay.data[0].num
          // }
        }
        //查询小绵羊付费目标
        let resXmy = await queryXmyPay(
          this.utils.formatDate(new_date),
          e.xmy_id
        );
        // {"code":0,"msg":"success","data":[{"amount":"6.00","num":"10","use_num":"0"}]}
        // console.log(resXmy)
        let xmyPay = JSON.parse(resXmy + '');
        if (xmyPay.code == 0 && !_.isEmpty(xmyPay.data)) {
          // console.log(xmyPay.data)
          target_pay = xmyPay.data[0].num;
        }

        // 执行目标查找和修改开始（只修改小绵羊游戏的付费目标）========================
        let targetObj = {
          task_id: task_id,
          task_name: task_name,
          new_date: new_date,
          directorId: e.directorId,
          target_pay: target_pay,
          updateTime: updateTime,
        };
        const targetEntity = await this.ShuyouGameTargetEntity.findOne({
          task_id: task_id,
          new_date: new_date,
        });
        // console.log(targetEntity)
        if (targetEntity) {
          await this.ShuyouGameTargetEntity.createQueryBuilder()
            .update()
            .set(targetObj)
            .where('task_id = :task_id and new_date = :new_date', {
              task_id: task_id,
              new_date: new_date,
            })
            .execute();
          // this.logger.warn(updateResult)
        }
        // 执行目标查找和修改结束========================
      } else {
        // 非小绵羊游戏处理
        var flag4 = 0;
        // var flag5 = 0
        // for (let oldvalue of computerRoomData) {
        //   if (task_name == oldvalue.game_name) {
        //     flag4 = 1
        //     for (let newvalue of newComputerRoomData) {
        //       if (newvalue.game_name == task_name) {
        //         flag5 = 1
        //         complete_new += newvalue.new_complete_local
        //         complete_pay += newvalue.pay_complete_local
        //         complete_active = complete_active + newvalue.retained_complete_local + newvalue.new_complete_local
        //         break;
        //       }
        //     }
        //     if (flag5 == 0) {
        //       complete_new += oldvalue.new_complete_local
        //       complete_pay += oldvalue.pay_complete_local
        //       complete_active = complete_active + oldvalue.retained_complete_local + oldvalue.new_complete_local
        //     }
        //     break;
        //   }
        // }
        for (let oldvalue of computerRoomData) {
          if (task_name == oldvalue.game_name) {
            complete_new += oldvalue.new_complete_local;
            complete_pay += oldvalue.pay_complete_local;
            complete_active =
              complete_active +
              oldvalue.retained_complete_local +
              oldvalue.new_complete_local;
            break;
          }
        }
        if (flag4 == 0) {
          let flag10 = 0;
          // if (oldServiceErr == false) {
          //   for (let value of oldService) {
          //     if (value.game_name == task_name) {
          //       flag10 = 1
          //       complete_new += value.complete_new
          //       complete_pay += value.complete_pay
          //       complete_active = complete_active + value.complete_active
          //       break;
          //     }
          //   }
          // }
          if (flag10 == 0) {
            for (let newvalue of newComputerRoomData) {
              if (newvalue.game_name == task_name) {
                complete_new += newvalue.new_complete_local;
                complete_pay += newvalue.pay_complete_local;
                complete_active =
                  complete_active +
                  newvalue.retained_complete_local +
                  newvalue.new_complete_local;
                break;
              }
            }
          }
        }
        amount =
          (parseInt(e.unit_price_high) + parseInt(e.unit_price_low)) *
          0.5 *
          complete_pay;
      }
      //魅族游戏付费目标处理
      if (e.game_agentId == 5 && e.login_modeId == 2) {
        //b.mz_channel, b.mz_id
        var checkedMz = false;
        if (wslErr == false) {
          for (let wslvalue of wslData) {
            if (e.mz_id + '-' + e.mz_channel == wslvalue.gameid) {
              target_pay = wslvalue.money;
              checkedMz = true;
              break;
            }
          }
        }
        // 执行目标查找和修改开始（只修改魅族游戏的付费目标）========================
        if (checkedMz == true) {
          let targetObj = {
            task_id: task_id,
            task_name: task_name,
            new_date: new_date,
            directorId: e.directorId,
            target_pay: target_pay,
            updateTime: updateTime,
          };
          const targetEntity = await this.ShuyouGameTargetEntity.findOne({
            task_id: task_id,
            new_date: new_date,
          });
          // console.log(targetEntity)
          if (targetEntity) {
            await this.ShuyouGameTargetEntity.createQueryBuilder()
              .update()
              .set(targetObj)
              .where('task_id = :task_id and new_date = :new_date', {
                task_id: task_id,
                new_date: new_date,
              })
              .execute();
            // this.logger.warn(updateResult)
          }
        }
        // 执行魅族游戏目标查找和修改结束========================
      }
      //======================================================

      // for (let oldvalue of computerRoomData) {
      //   if (task_name == oldvalue.game_name || e.xmy_id == oldvalue.game_id_xmy) {
      //     if (typeof (oldvalue.game_rate_xmy) == "undefined") {
      //       game_rate_xmy = '0/0/0'
      //     } else {
      //       game_rate_xmy = oldvalue.game_rate_xmy
      //     }
      //     game_rate = oldvalue.game_rate
      //     break;
      //   }
      // }
      if (game_rate == '0/0/0') {
        for (let newvalue of newComputerRoomData) {
          if (
            task_name == newvalue.game_name ||
            e.xmy_id == newvalue.game_id_xmy
          ) {
            if (typeof newvalue.game_rate_xmy == 'undefined') {
              game_rate_xmy = '0/0/0';
            } else {
              game_rate_xmy = newvalue.game_rate_xmy;
            }
            game_rate = newvalue.game_rate;
            break;
          }
        }
      }

      //查询手动完成start=========================================
      const completeHand = await this.ShuyouGameCompleteHandEntity.findOne({
        task_id: task_id,
        new_date: new_date,
      });
      if (completeHand) {
        if (e.xjf_id == 0) {
          complete_pay =
            parseInt(complete_pay + '') +
            parseInt(completeHand.complete_pay_hand + '');
          amount =
            parseFloat(amount + '') + parseFloat(completeHand.amount_hand + '');
        }
        complete_new =
          parseInt(complete_new + '') +
          parseInt(completeHand.complete_new_hand + '');
        complete_active =
          parseInt(complete_active + '') +
          parseInt(completeHand.complete_new_hand + '') +
          parseInt(completeHand.complete_lc_hand + '');
      }
      //查询手动完成end=========================================
      if (
        complete_new >= parseInt(e.target_new) &&
        complete_pay >= parseInt(e.target_pay) &&
        complete_active >= parseInt(e.target_active)
      ) {
        is_complete = 1;
      }
      //此处添加新功能：
      //如果检查到完成结果全是0，那么就查询数据库之前记录是否为0，若不为0，则此次完成情况数据不覆盖
      //************************************************** */
      let noCover = false; //数据是否覆盖标识
      if (complete_new == 0 && complete_pay == 0 && complete_active == 0) {
        const comEntityTD = await this.ShuyouGameCompleteEntity.findOne({
          task_id: task_id,
          new_date: new_date,
        });
        if (comEntityTD) {
          if (
            comEntityTD.complete_active != 0 ||
            comEntityTD.complete_new != 0
          ) {
            noCover = true;
          }
        }
      }
      //************************************************** */
      if (noCover == false) {
        // 执行完成查找和修改========================
        let comObj = {
          task_id: task_id,
          task_name: task_name,
          new_date: new_date,
          complete_new: complete_new,
          complete_pay: complete_pay,
          complete_active: complete_active,
          is_complete: is_complete,
          amount: amount,
          game_rate: game_rate,
          game_rate_xmy: game_rate_xmy,
          updateTime: updateTime,
        };
        const comEntity = await this.ShuyouGameCompleteEntity.findOne({
          task_id: task_id,
          new_date: new_date,
        });
        if (comEntity) {
          await this.ShuyouGameCompleteEntity.createQueryBuilder()
            .update()
            .set(comObj)
            .where('task_id = :task_id and new_date = :new_date', {
              task_id: task_id,
              new_date: new_date,
            })
            .execute();
          // this.logger.warn(updateCom)
        }
        //
      }
    });
    // 查询当前总数据start====================================
    const sql2 = `
        SELECT 
          SUM(a.target_new) as sum_target_new,SUM(a.target_pay) as sum_target_pay,SUM(a.target_active) as sum_target_active,
          SUM(b.complete_new) as sum_new,SUM(b.complete_pay) as sum_pay,SUM(b.complete_active) as sum_active,a.new_date 
        FROM 
          shuyou_game_target a
          LEFT JOIN shuyou_game_complete b ON a.task_id = b.task_id and a.new_date = b.new_date
        where 1 = 1 
        ${this.setSql(new_date, 'and a.new_date = ?', [new_date])}
    `;
    const sumList = await this.nativeQuery(sql2);
    let sumObj = {
      new_date: sumList[0].new_date,
      target_new: sumList[0].sum_target_new,
      target_pay: sumList[0].sum_target_pay,
      target_active: sumList[0].sum_target_active,
      sum_new: sumList[0].sum_new,
      sum_active: sumList[0].sum_active,
      sum_pay: sumList[0].sum_pay,
      createTime: updateTime,
      updateTime: updateTime,
    };
    const sumEntity = await this.ShuyouDataActiveEntity.findOne({
      new_date: new_date,
      game_agent: '合计',
      game_director: '合计',
    });
    if (sumEntity) {
      await this.ShuyouDataActiveEntity.createQueryBuilder()
        .update()
        .set(sumObj)
        .where(
          'new_date = :new_date and game_agent = :game_agent and game_director = :game_director',
          {
            new_date: new_date,
            game_agent: '合计',
            game_director: '合计',
          }
        )
        .execute();
      // this.logger.warn(updateCom)
    } else {
      await this.ShuyouDataActiveEntity.createQueryBuilder()
        .insert()
        .into(ShuyouDataActiveEntity)
        .values(sumObj)
        .execute();
      // this.logger.warn(updateCom)
    }
    // 查询当前总数据end====================================
    // 按渠道查询当前总数据start====================================
    const sql3 = `
        SELECT 
            SUM(a.target_new) as sum_target_new,SUM(a.target_pay) as sum_target_pay,SUM(a.target_active) as sum_target_active,
            c.name,SUM(complete_new) as sum_new,SUM(complete_pay) as sum_pay,SUM(complete_active) as sum_active,a.new_date 
        FROM 
            shuyou_game_target a
            LEFT JOIN shuyou_game_complete s ON a.task_id = s.task_id and a.new_date = s.new_date
            LEFT JOIN shuyou_game_task b ON a.task_id = b.id
            LEFT JOIN shuyou_game_agent c ON c.id = b.game_agentId
        where 1 = 1 
            ${this.setSql(new_date, 'and a.new_date =  ?', [new_date])}
        GROUP BY b.game_agentId
    `;
    const sumAgent = await this.nativeQuery(sql3);
    await ykhForeach(sumAgent, async (item, index) => {
      let agentObj = {
        new_date: item.new_date,
        game_agent: item.name,
        target_new: item.sum_target_new,
        target_pay: item.sum_target_pay,
        target_active: item.sum_target_active,
        sum_new: item.sum_new,
        sum_active: item.sum_active,
        sum_pay: item.sum_pay,
        createTime: updateTime,
        updateTime: updateTime,
      };
      const agentEntity = await this.ShuyouDataActiveEntity.findOne({
        new_date: new_date,
        game_agent: item.name,
      });
      if (agentEntity) {
        await this.ShuyouDataActiveEntity.createQueryBuilder()
          .update()
          .set(agentObj)
          .where('new_date = :new_date and game_agent = :game_agent', {
            new_date: new_date,
            game_agent: item.name,
          })
          .execute();
      } else {
        await this.ShuyouDataActiveEntity.createQueryBuilder()
          .insert()
          .into(ShuyouDataActiveEntity)
          .values(agentObj)
          .execute();
      }
    });
    // 按渠道查询当前总数据end====================================
    // 按负责人查询当前总数据start====================================
    const sql4 = `
        SELECT 
            SUM(a.target_new) as sum_target_new,SUM(a.target_pay) as sum_target_pay,SUM(a.target_active) as sum_target_active,
            c.name,SUM(complete_new) as sum_new,SUM(complete_pay) as sum_pay,SUM(complete_active) as sum_active,a.new_date 
        FROM 
            shuyou_game_target a
            LEFT JOIN shuyou_game_complete s ON a.task_id = s.task_id and a.new_date = s.new_date
            LEFT JOIN shuyou_game_task b ON a.task_id = b.id
            LEFT JOIN shuyou_game_director c ON c.id = b.directorId
        where 1 = 1 
          ${this.setSql(new_date, 'and a.new_date =  ?', [new_date])}
        GROUP BY b.directorId
    `;
    const sumDirector = await this.nativeQuery(sql4);
    await ykhForeach(sumDirector, async (item, index) => {
      let directortObj = {
        new_date: item.new_date,
        game_director: item.name,
        target_new: item.sum_target_new,
        target_pay: item.sum_target_pay,
        target_active: item.sum_target_active,
        sum_new: item.sum_new,
        sum_active: item.sum_active,
        sum_pay: item.sum_pay,
        createTime: updateTime,
        updateTime: updateTime,
      };
      const directorEntity = await this.ShuyouDataActiveEntity.findOne({
        new_date: new_date,
        game_director: item.name,
      });
      if (directorEntity) {
        await this.ShuyouDataActiveEntity.createQueryBuilder()
          .update()
          .set(directortObj)
          .where('new_date = :new_date and game_director = :game_director', {
            new_date: new_date,
            game_director: item.name,
          })
          .execute();
      } else {
        await this.ShuyouDataActiveEntity.createQueryBuilder()
          .insert()
          .into(ShuyouDataActiveEntity)
          .values(directortObj)
          .execute();
      }
    });
    // 按负责人查询当前总数据end====================================
    flag.detail = 'syncTargetAndComplete  SUCCESS';
    flag.status = 1;
    await this.ShuyouTargetFlagService.add(flag);
    return 'syncTargetAndComplete  SUCCESS>>>' + updateTime;
  }
  /**
   * 第二天更新前一天的目标完成，按最低目标更新，并生成未完成原因
   * TODO
   * @memberof TaskShuyouService
   */
  async suncYesterdayAll() {
    let yest_date = this.utils.formatDate(
      new Date().getTime() - 24 * 60 * 60 * 1000
    );
    let updateTime = new Date();
    this.logger.info('suncYesterdayAll>>>' + updateTime);
    let sheepData = [];
    let wslData = [];
    let computerRoomData = [];
    let newComputerRoomData = [];
    // let oldService = []
    // 先删除reason_incomplete表中昨日所有未完成数据，下面会重新添加
    await this.ShuyouReasonIncompleteEntity.createQueryBuilder()
      .delete()
      .where('new_date = :new_date', {
        new_date: yest_date,
      })
      .execute();
    // 删除完毕
    const sql = `
      SELECT 
        a.*,
        b.xmy_id AS xmy_id,b.unit_price_low AS unit_price_low,b.unit_price_high AS unit_price_high,
        b.game_agentId,b.login_modeId,b.mz_channel, b.mz_id,b.xjf_id,
        c.name AS directorName
      from 
        shuyou_game_target a
        LEFT JOIN shuyou_game_task b ON a.task_id = b.id
        LEFT JOIN shuyou_game_director c ON a.directorId = c.id
      where 1 = 1 
      ${this.setSql(yest_date, 'and a.new_date = ? ORDER BY a.task_id', [
        yest_date,
      ])}
    `;
    // console.log(sql)
    const targetList = await this.nativeQuery(sql);
    if (_.isEmpty(targetList)) {
      return (
        'suncYesterdayAll >>> shuyou_game_target is null >>> ' + updateTime
      );
    }
    //
    const data1 = await queryXMY(yest_date, yest_date);
    let xmyData = JSON.parse(data1 + '');
    if (xmyData.status == true) {
      sheepData = xmyData.data.list;
      // this.logger.info(sheepData)
      // this.logger.info('获取小绵羊后台数据成功')
    }
    let data2 = await queryComputerRoom(yest_date);
    if (_.isEmpty(data2) || data2 == -1) {
      computerRoomData = [];
    } else {
      computerRoomData = JSON.parse(data2 + '');
    }
    let data3 = await queryNewComputerRoom(yest_date);
    if (_.isEmpty(data3) || data3 == -1) {
      newComputerRoomData = [];
    } else {
      newComputerRoomData = JSON.parse(data3 + '');
    }
    let data4 = await queryWSL(yest_date);
    let wslErr = false;
    // console.log(data4)
    if (
      _.isEmpty(data4) ||
      data4 == -1 ||
      (data4 + '').indexOf('gameid') == -1
    ) {
      wslErr = true;
      // this.logger.warn('王淑霖付费目标接口数据错误')
      wslData = [];
    } else {
      wslData = JSON.parse(data4 + '');
    }

    //获取用户自己上传的数据（81.70.79.43）
    // const data5 = await queryOldService(yest_date)
    // let data6 = JSON.parse(data5 + '')
    // if (data6.code == 1) {
    //   oldService = data6.data
    // }
    //
    await ykhForeach(targetList, async (e, index) => {
      // targetList.forEach(async e => {
      var task_id = e.task_id;
      var task_name = e.task_name;
      var new_date = e.new_date;
      var target_pay = e.target_pay;
      e.target_pay_low = target_pay;
      var complete_new = 0;
      var complete_pay = 0;
      var complete_active = 0;
      var is_complete = 0;
      var amount = 0;
      var game_rate = '0/0/0';
      var game_rate_xmy = '0/0/0';
      if (e.xmy_id != null && e.xmy_id != '' && e.xmy_id != 'null') {
        // 小绵羊游戏处理
        // console.log(e.xmy_id)
        for (let sheep of sheepData) {
          // console.log(sheep.game_id)
          if (e.xmy_id == sheep.game_id) {
            // if (wslErr == false) {
            //   //从wsl接口获取小绵羊付费目标
            //   for (let wslvalue of wslData) {
            //     if (wslvalue.gameid == sheep.game_id) {
            //       target_pay = wslvalue.money
            //       e.target_pay_low = target_pay
            //       break;
            //     }
            //   }
            // } else {
            // let resXmy = await queryXmyPay(this.utils.formatDate(new_date), e.xmy_id)
            // // {"code":0,"msg":"success","data":[{"amount":"6.00","num":"10","use_num":"0"}]}
            // // console.log(resXmy)
            // let xmyPay = JSON.parse(resXmy + '')
            // if (xmyPay.code == 0 && !_.isEmpty(xmyPay.data)) {
            //   // console.log(xmyPay.data)
            //   target_pay = xmyPay.data[0].num
            // }
            // }

            //查询小绵羊付费目标
            let resXmy = await queryXmyPay(
              this.utils.formatDate(new_date),
              e.xmy_id
            );
            // {"code":0,"msg":"success","data":[{"amount":"6.00","num":"10","use_num":"0"}]}
            // console.log(resXmy)
            let xmyPay = JSON.parse(resXmy + '');
            if (xmyPay.code == 0 && !_.isEmpty(xmyPay.data)) {
              // console.log(xmyPay.data)
              target_pay = xmyPay.data[0].num;
              e.target_pay_low = target_pay;
            }

            complete_new = sheep.user_num;
            complete_pay = sheep.cnt;
            complete_active = sheep.active_user_num;
            amount = sheep.amount;
            break;
          }
        }
      } else {
        // 非小绵羊游戏处理
        var flag4 = 0;
        // var flag5 = 0
        // for (let oldvalue of computerRoomData) {
        //   if (oldvalue.game_name == task_name) {
        //     flag4 = 1
        //     for (let newvalue of newComputerRoomData) {
        //       if (newvalue.game_name == task_name) {
        //         flag5 = 1
        //         complete_new += newvalue.new_complete_local
        //         complete_pay += newvalue.pay_complete_local
        //         complete_active = complete_active + newvalue.retained_complete_local + newvalue.new_complete_local
        //         break;
        //       }
        //     }
        //     if (flag5 == 0) {
        //       complete_new += oldvalue.new_complete_local
        //       complete_pay += oldvalue.pay_complete_local
        //       complete_active = complete_active + oldvalue.retained_complete_local + oldvalue.new_complete_local
        //     }
        //     break;
        //   }
        // }
        for (let oldvalue of computerRoomData) {
          if (oldvalue.game_name == task_name) {
            complete_new += oldvalue.new_complete_local;
            complete_pay += oldvalue.pay_complete_local;
            complete_active =
              complete_active +
              oldvalue.retained_complete_local +
              oldvalue.new_complete_local;
            break;
          }
        }
        if (flag4 == 0) {
          var flag6 = 0;
          // for (let value of oldService) {
          //   if (value.game_name == task_name) {
          //     flag6 = 1
          //     complete_new += value.complete_new
          //     complete_pay += value.complete_pay
          //     complete_active = complete_active + value.complete_active
          //     break;
          //   }
          // }
          if (flag6 == 0) {
            for (let newvalue of newComputerRoomData) {
              if (newvalue.game_name == task_name) {
                complete_new += newvalue.new_complete_local;
                complete_pay += newvalue.pay_complete_local;
                complete_active =
                  complete_active +
                  newvalue.retained_complete_local +
                  newvalue.new_complete_local;
                break;
              }
            }
          }
        }
        amount =
          (parseInt(e.unit_price_high) + parseInt(e.unit_price_low)) *
          0.5 *
          complete_pay;
        // amount = 6 * complete_pay
      }
      //======================================================
      //魅族游戏付费目标处理
      if (e.game_agentId == 5 && e.login_modeId == 2) {
        //b.mz_channel, b.mz_id
        if (wslErr == false) {
          for (let wslvalue of wslData) {
            if (e.mz_id + '-' + e.mz_channel == wslvalue.gameid) {
              target_pay = wslvalue.money;
              e.target_pay_low = target_pay;
              break;
            }
          }
        }
      }
      //======================================================
      // for (let oldvalue of computerRoomData) {
      //   if (oldvalue.game_name == task_name || e.xmy_id == oldvalue.game_id_xmy) {
      //     if (typeof (oldvalue.game_rate_xmy) == "undefined") {
      //       game_rate_xmy = '0/0/0'
      //     } else {
      //       game_rate_xmy = oldvalue.game_rate_xmy
      //     }
      //     game_rate = oldvalue.game_rate
      //     break;
      //   }
      // }
      if (game_rate == '0/0/0') {
        for (let newvalue of newComputerRoomData) {
          if (
            newvalue.game_name == task_name ||
            e.xmy_id == newvalue.game_id_xmy
          ) {
            if (typeof newvalue.game_rate_xmy == 'undefined') {
              game_rate_xmy = '0/0/0';
            } else {
              game_rate_xmy = newvalue.game_rate_xmy;
            }
            game_rate = newvalue.game_rate;
            break;
          }
        }
      }
      //查询手动完成start=========================================
      const completeHand = await this.ShuyouGameCompleteHandEntity.findOne({
        task_id: task_id,
        new_date: new_date,
      });
      if (completeHand) {
        if (e.xjf_id == 0) {
          complete_pay =
            parseInt(complete_pay + '') +
            parseInt(completeHand.complete_pay_hand + '');
          amount =
            parseFloat(amount + '') + parseFloat(completeHand.amount_hand + '');
        }
        complete_new =
          parseInt(complete_new + '') +
          parseInt(completeHand.complete_new_hand + '');
        complete_active =
          parseInt(complete_active + '') +
          parseInt(completeHand.complete_new_hand + '') +
          parseInt(completeHand.complete_lc_hand + '');
      }
      //查询手动完成end=========================================
      //变更最小目标
      if (e.target_new_low > e.target_new) {
        e.target_new_low = e.target_new;
      }
      if (e.target_active_low > e.target_active) {
        e.target_active_low = e.target_active;
      }
      //=======================================================
      let incomplete_new = parseInt(e.target_new_low) - complete_new;
      let incomplete_pay = parseInt(e.target_pay_low) - complete_pay;
      let incomplete_active = parseInt(e.target_active_low) - complete_active;
      if (incomplete_new < 0) {
        incomplete_new = 0;
      }
      if (incomplete_pay < 0) {
        incomplete_pay = 0;
      }
      if (incomplete_active < 0) {
        incomplete_active = 0;
      }
      if (
        complete_new >= parseInt(e.target_new_low) &&
        complete_pay >= parseInt(e.target_pay_low) &&
        complete_active >= parseInt(e.target_active_low)
      ) {
        is_complete = 1;
      } else {
        is_complete = 0;
      }
      //===========
      //此处添加新功能：
      //如果检查到完成结果全是0，那么就查询数据库之前记录是否为0，若不为0，则此次完成情况数据不覆盖
      //************************************************** */
      // console.log(task_name)
      let noCover = false; //数据是否覆盖标识
      if (complete_new == 0 && complete_pay == 0 && complete_active == 0) {
        const comEntityYet = await this.ShuyouGameCompleteEntity.findOne({
          task_id: task_id,
          new_date: new_date,
        });
        if (comEntityYet) {
          if (
            comEntityYet.complete_active != 0 ||
            comEntityYet.complete_new != 0
          ) {
            noCover = true;
          }
        }
      }
      //************************************************** */
      if (noCover == false) {
        if (is_complete == 0) {
          // 未完成添加进reason_incomplete表中
          const exists = await this.ShuyouReasonIncompleteEntity.findOne({
            task_id: task_id,
            new_date: new_date,
          });
          if (!_.isEmpty(exists)) {
            let addObj = {
              task_name: task_name,
              directorName: e.directorName,
              incomplete_new: incomplete_new,
              incomplete_pay: incomplete_pay,
              incomplete_active: incomplete_active,
              type_id: 0,
              reason: '',
              solution: '',
              is_write: 0,
            };
            const updateResult =
              await this.ShuyouReasonIncompleteEntity.createQueryBuilder()
                .update()
                .set(addObj)
                .where('task_id = :task_id and new_date = :new_date', {
                  task_id: task_id,
                  new_date: new_date,
                })
                .execute();
            if (updateResult.affected >= 1) {
              this.logger.warn('修改成功!');
            } else {
              this.logger.warn('修改失败!');
            }
          } else {
            await this.ShuyouReasonIncompleteEntity.insert({
              task_id: task_id,
              task_name: task_name,
              directorName: e.directorName,
              new_date: new_date,
              incomplete_new: incomplete_new,
              incomplete_pay: incomplete_pay,
              incomplete_active: incomplete_active,
              type_id: 0,
              reason: '',
              solution: '',
              is_write: 0,
              createTime: new Date(),
              updateTime: new Date(),
            });
            // this.logger.warn('添加成功!')
          }
        }

        let targetObj = {
          task_id: task_id,
          task_name: task_name,
          new_date: new_date,
          directorId: e.directorId,
          target_pay: target_pay,
          updateTime: updateTime,
        };
        // 执行目标查找和修改========================
        const targetEntity = await this.ShuyouGameTargetEntity.findOne({
          task_id: task_id,
          new_date: new_date,
        });
        // console.log(targetEntity)
        if (targetEntity) {
          await this.ShuyouGameTargetEntity.createQueryBuilder()
            .update()
            .set(targetObj)
            .where('task_id = :task_id and new_date = :new_date', {
              task_id: task_id,
              new_date: new_date,
            })
            .execute();
          // this.logger.warn(updateResult)
        }
        // 执行完成查找和修改========================
        let comObj = {
          task_id: task_id,
          task_name: task_name,
          new_date: new_date,
          complete_new: complete_new,
          complete_pay: complete_pay,
          complete_active: complete_active,
          is_complete: is_complete,
          amount: amount,
          game_rate: game_rate,
          game_rate_xmy: game_rate_xmy,
          updateTime: updateTime,
        };
        const comEntity = await this.ShuyouGameCompleteEntity.findOne({
          task_id: task_id,
          new_date: new_date,
        });
        if (comEntity) {
          await this.ShuyouGameCompleteEntity.createQueryBuilder()
            .update()
            .set(comObj)
            .where('task_id = :task_id and new_date = :new_date', {
              task_id: task_id,
              new_date: new_date,
            })
            .execute();
          // this.logger.warn(updateCom)
        }
      }
    });
    // 查询当前总数据start====================================
    const sql2 = `
        SELECT 
          SUM(a.target_new) as sum_target_new,SUM(a.target_pay) as sum_target_pay,SUM(a.target_active) as sum_target_active,
          SUM(b.complete_new) as sum_new,SUM(b.complete_pay) as sum_pay,SUM(b.complete_active) as sum_active,a.new_date 
        FROM 
          shuyou_game_target a
          LEFT JOIN shuyou_game_complete b ON a.task_id = b.task_id and a.new_date = b.new_date
        where 1 = 1 
        ${this.setSql(yest_date, 'and a.new_date = ?', [yest_date])}
    `;
    const sumList = await this.nativeQuery(sql2);
    let sumObj = {
      new_date: sumList[0].new_date,
      target_new: sumList[0].sum_target_new,
      target_pay: sumList[0].sum_target_pay,
      target_active: sumList[0].sum_target_active,
      sum_new: sumList[0].sum_new,
      sum_active: sumList[0].sum_active,
      sum_pay: sumList[0].sum_pay,
      createTime: updateTime,
      updateTime: updateTime,
    };
    const sumEntity = await this.ShuyouDataActiveEntity.findOne({
      new_date: yest_date,
      game_agent: '合计',
      game_director: '合计',
    });
    if (sumEntity) {
      await this.ShuyouDataActiveEntity.createQueryBuilder()
        .update()
        .set(sumObj)
        .where(
          'new_date = :new_date and game_agent = :game_agent and game_director = :game_director',
          {
            new_date: yest_date,
            game_agent: '合计',
            game_director: '合计',
          }
        )
        .execute();
      // this.logger.warn(updateCom)
    } else {
      await this.ShuyouDataActiveEntity.createQueryBuilder()
        .insert()
        .into(ShuyouDataActiveEntity)
        .values(sumObj)
        .execute();
      // this.logger.warn(updateCom)
    }
    // 查询当前总数据end====================================
    // 按渠道查询当前总数据start====================================
    const sql3 = `
        SELECT 
            SUM(a.target_new) as sum_target_new,SUM(a.target_pay) as sum_target_pay,SUM(a.target_active) as sum_target_active,
            c.name,SUM(complete_new) as sum_new,SUM(complete_pay) as sum_pay,SUM(complete_active) as sum_active,a.new_date 
        FROM 
            shuyou_game_target a
            LEFT JOIN shuyou_game_complete s ON a.task_id = s.task_id and a.new_date = s.new_date
            LEFT JOIN shuyou_game_task b ON a.task_id = b.id
            LEFT JOIN shuyou_game_agent c ON c.id = b.game_agentId
        where 1 = 1 
            ${this.setSql(yest_date, 'and a.new_date =  ?', [yest_date])}
        GROUP BY b.game_agentId
    `;
    const sumAgent = await this.nativeQuery(sql3);
    await ykhForeach(sumAgent, async (item, index) => {
      let agentObj = {
        new_date: item.new_date,
        game_agent: item.name,
        target_new: item.sum_target_new,
        target_pay: item.sum_target_pay,
        target_active: item.sum_target_active,
        sum_new: item.sum_new,
        sum_active: item.sum_active,
        sum_pay: item.sum_pay,
        createTime: updateTime,
        updateTime: updateTime,
      };
      const agentEntity = await this.ShuyouDataActiveEntity.findOne({
        new_date: yest_date,
        game_agent: item.name,
      });
      if (agentEntity) {
        await this.ShuyouDataActiveEntity.createQueryBuilder()
          .update()
          .set(agentObj)
          .where('new_date = :new_date and game_agent = :game_agent', {
            new_date: yest_date,
            game_agent: item.name,
          })
          .execute();
      } else {
        await this.ShuyouDataActiveEntity.createQueryBuilder()
          .insert()
          .into(ShuyouDataActiveEntity)
          .values(agentObj)
          .execute();
      }
    });
    // 按渠道查询当前总数据end====================================
    // 按负责人查询当前总数据start====================================
    const sql4 = `
        SELECT 
            SUM(a.target_new) as sum_target_new,SUM(a.target_pay) as sum_target_pay,SUM(a.target_active) as sum_target_active,
            c.name,SUM(complete_new) as sum_new,SUM(complete_pay) as sum_pay,SUM(complete_active) as sum_active,a.new_date 
        FROM 
            shuyou_game_target a
            LEFT JOIN shuyou_game_complete s ON a.task_id = s.task_id and a.new_date = s.new_date
            LEFT JOIN shuyou_game_task b ON a.task_id = b.id
            LEFT JOIN shuyou_game_director c ON c.id = b.directorId
        where 1 = 1 
          ${this.setSql(yest_date, 'and a.new_date =  ?', [yest_date])}
        GROUP BY b.directorId
    `;
    const sumDirector = await this.nativeQuery(sql4);
    await ykhForeach(sumDirector, async (item, index) => {
      let directortObj = {
        new_date: item.new_date,
        game_director: item.name,
        target_new: item.sum_target_new,
        target_pay: item.sum_target_pay,
        target_active: item.sum_target_active,
        sum_new: item.sum_new,
        sum_active: item.sum_active,
        sum_pay: item.sum_pay,
        createTime: updateTime,
        updateTime: updateTime,
      };
      const directorEntity = await this.ShuyouDataActiveEntity.findOne({
        new_date: yest_date,
        game_director: item.name,
      });
      if (directorEntity) {
        await this.ShuyouDataActiveEntity.createQueryBuilder()
          .update()
          .set(directortObj)
          .where('new_date = :new_date and game_director = :game_director', {
            new_date: yest_date,
            game_director: item.name,
          })
          .execute();
      } else {
        await this.ShuyouDataActiveEntity.createQueryBuilder()
          .insert()
          .into(ShuyouDataActiveEntity)
          .values(directortObj)
          .execute();
      }
    });
    // 按负责人查询当前总数据end====================================
    return 'suncYesterdayAll  SUCCESS>>>' + updateTime;
  }
  /**
   * 更新明日目标以及初始化明日完成情况
   * @memberof TaskShuyouService
   */
  async syncNextTargetInitComplete() {
    let next_date = this.utils.formatDate(
      new Date().getTime() + 24 * 60 * 60 * 1000
    );
    let updateTime = new Date();
    this.logger.info('syncNextTargetInitComplete>>>' + updateTime);
    const sql = `
      SELECT 
        id,task_name,target_new_low,target_new_high,target_pay_low,target_pay_high,target_active_low,target_active_high,
        lc_two_ratio,lc_three_ratio,lc_four_ratio,lc_five_ratio,lc_six_ratio,lc_seven_ratio,lc_eight_ratio,lc_fifteen_ratio,lc_thirty_ratio,
        directorId
      from 
        shuyou_game_task
      where is_run = 1
    `;
    // console.log(sql)
    const taskList = await this.nativeQuery(sql);
    if (_.isEmpty(taskList)) {
      return (
        'syncNextTargetInitComplete >>> shuyou_game_task is null >>> ' +
        updateTime
      );
    }
    taskList.forEach(async e => {
      // 添加游戏或修改目标start==========================
      const gameTargetEntity = await this.ShuyouGameTargetEntity.findOne({
        task_id: e.id,
        new_date: next_date,
      });
      let target_new = 0;
      let target_pay = 0;
      let target_active = 0;
      target_new = Math.floor(
        Math.random() *
          (parseInt(e.target_new_high) - parseInt(e.target_new_low) + 1) +
          parseInt(e.target_new_low)
      );
      target_pay = Math.floor(
        Math.random() *
          (parseInt(e.target_pay_high) - parseInt(e.target_pay_low) + 1) +
          parseInt(e.target_pay_low)
      );
      target_active = Math.floor(
        Math.random() *
          (parseInt(e.target_active_high) - parseInt(e.target_active_low) + 1) +
          parseInt(e.target_active_low)
      );
      let targetObj = {
        task_id: e.id,
        task_name: e.task_name,
        directorId: e.directorId,
        new_date: next_date,
        updateTime: new Date(),
        target_new: target_new,
        target_pay: target_pay,
        target_active: target_active,
        target_new_low: e.target_new_low,
        target_pay_low: e.target_pay_low,
        target_active_low: e.target_active_low,
      };
      if (gameTargetEntity) {
        //已存在，则更新
        await this.ShuyouGameTargetEntity.createQueryBuilder()
          .update()
          .set(targetObj)
          .where('task_id = :task_id and new_date = :new_date', {
            task_id: e.id,
            new_date: next_date,
          })
          .execute();
        // this.logger.warn(updateResult)
      } else {
        //不存在，则新建
        await this.ShuyouGameTargetEntity.insert(targetObj);
      }
      // 添加游戏或修改目标end==========================
      // 添加初始化完成表start==========================
      const gameCompleteEntity = await this.ShuyouGameCompleteEntity.findOne({
        task_id: e.id,
        new_date: next_date,
      });
      let obj = {
        task_id: e.id,
        task_name: e.task_name,
        new_date: next_date,
        updateTime: updateTime,
      };
      if (!gameCompleteEntity) {
        // 不存在，则新建
        await this.ShuyouGameCompleteEntity.insert(obj);
        // console.log(aa)
      }
      // 添加初始化完成表end==========================
    });
    return 'syncNextTargetInitComplete  SUCCESS>>>' + updateTime;
  }
  /**
   * 定时更新是否有游戏停止或开始数优，因为有些游戏设置了停止时间，到达停止时间后，游戏停止；到达指定时间后开始游戏
   * @memberof TaskShuyouService
   */
  async syncIsRun() {
    // let now_date = this.utils.formatDate(new Date())
    let updateTime = new Date();
    this.logger.info('syncIsRun>>>' + updateTime);
    const sql = `
      SELECT 
        id,is_run,stopTime,new_date
      from 
        shuyou_game_task
      where 1 = 1
    `;
    // console.log(sql)
    const taskList = await this.nativeQuery(sql);
    if (_.isEmpty(taskList)) {
      return 'syncIsRun >>> shuyou_game_task is null >>> ' + updateTime;
    }
    await ykhForeach(taskList, async (e, i) => {
      if (e.is_run == 1) {
        // console.log(Date.parse(e.stopTime))
        // console.log(updateTime.getTime())
        if (Date.parse(e.stopTime) < updateTime.getTime()) {
          // console.log('stop')
          let obj = {
            id: e.id,
          };
          const ShuyouGameTaskEntity = await this.ShuyouGameTaskEntity.findOne(
            obj
          );
          if (ShuyouGameTaskEntity) {
            ShuyouGameTaskEntity.is_run = 0;
            // this.logger.info(ShuyouGameTaskEntity)
            await this.ShuyouGameTaskEntity.save(ShuyouGameTaskEntity);
          }
        }
      }
    });
    return 'syncIsRun  SUCCESS>>>';
  }

  /**
   * 定时任务，定时检查occupy_taskId不为0的账号的取出时间是否超时(超时时间60分钟)，超时则置occupy_taskId为0，还原账号状态
   * @return {*}
   * @memberof TaskShuyouService
   */
  async checkOccupyOverTime() {
    // let now_date = this.utils.formatDate(new Date())
    let updateTime = new Date();
    this.logger.info('checkOccupyOverTime>>>' + updateTime);
    const sql = `
      select 
        a.id, a.getTime,a.occupy_taskId,b.game_id
      from 
        shuyou_game_account a
      LEFT JOIN task_game_record b ON b.task_id = a.occupy_taskId
      where a.occupy_taskId != 0
    `;
    // console.log(sql)
    const accList = await this.nativeQuery(sql);
    // if (_.isEmpty(taskList)) {
    //   return 'syncIsRun >>> shuyou_game_task is null >>> ' + updateTime;
    // }
    const overtime = 60 * 60 * 1000;
    // accList.forEach(async e => {
    await ykhForeach(accList, async (e, i) => {
      if (updateTime.getTime() - Date.parse(e.getTime) > overtime) {
        let obj = {
          id: e.id,
        };
        const ShuyouGameAccountEntity =
          await this.ShuyouGameAccountEntity.findOne(obj);
        if (ShuyouGameAccountEntity) {
          ShuyouGameAccountEntity.occupy_taskId = '0';
          ShuyouGameAccountEntity.getTime = null;
          await this.ShuyouGameAccountEntity.save(ShuyouGameAccountEntity);
        }
        await this.ShuyouGameAccountRecordEntity.createQueryBuilder()
          .delete()
          .where('game_id = :game_id and account_id = :account_id', {
            game_id: e.game_id,
            account_id: e.id,
          })
          .execute();
        await this.ShuyouTaskAccountRecordEntity.createQueryBuilder()
          .delete()
          .where('task_id = :task_id and account_id = :account_id', {
            task_id: e.occupy_taskId,
            account_id: e.id,
          })
          .execute();
      }
    });
    return 'syncIsRun  SUCCESS>>>';
  }
}

//==========================================================================================
// 获取小绵羊后台数据
let queryXMY = function (new_date1, new_date2) {
  var url =
    'http://api.sheepsdk.17xmy.com/foreign/api/get_youhua_data.php?start_day=' +
    new_date1 +
    '&end_day=' +
    new_date2;
  var http = require('http');
  var pm = new Promise(function (resolve, reject) {
    http
      .get(url, function (res) {
        var html = '';
        res.on('data', function (d) {
          html += d.toString();
        });
        res.on('end', function () {
          resolve(html);
        });
      })
      .on('error', function (e) {
        // reject(e)
        resolve(-1);
      });
  });
  return pm;
};
// 获取81.70.79.43的数据
// let queryOldService = function (new_date) {
//   var url = 'http://81.70.79.43:3002/task-sys/back-end/api/gametask/getXMYTarget?new_date=' + new_date
//   var http = require('http');
//   var pm = new Promise(function (resolve, reject) {
//     http.get(url, function (res) {
//       var html = '';
//       res.on('data', function (d) {
//         html += d.toString()
//       });
//       res.on('end', function () {
//         resolve(html);
//       });
//     }).on('error', function (e) {
//       // reject(e)
//       resolve(-1)
//     });
//   });
//   return pm;
// }
// 获取小绵羊后台付费目标
let queryXmyPay = function (new_date, xmy_id) {
  // console.log(new_date + xmy_id)
  var url =
    'http://rtd.kfzs.com/fake.php?day=' + new_date + '&game_id=' + xmy_id;
  var http = require('http');
  var pm = new Promise(function (resolve, reject) {
    http
      .get(url, function (res) {
        var html = '';
        res.on('data', function (d) {
          html += d.toString();
        });
        res.on('end', function () {
          resolve(html);
        });
      })
      .on('error', function (e) {
        // reject(e)
        resolve(-1);
      });
  });
  return pm;
};
// 获取机房游戏数据
let queryComputerRoom = function (new_date) {
  var url =
    'http://182.150.53.148:6007//v1/task_statistics?query=date:' +
    new_date +
    ',type:machine';
  var http = require('http');
  var pm = new Promise(function (resolve, reject) {
    http
      .get(url, function (res) {
        var html = '';
        res.on('data', function (d) {
          html += d.toString();
        });
        res.on('end', function () {
          resolve(html);
        });
      })
      .on('error', function (e) {
        // reject(e)
        resolve(-1);
      });
  });
  return pm;
};
// 获取新机房游戏数据
let queryNewComputerRoom = function (new_date) {
  var url =
    'http://xjf.lianyou.fun:8099/v1/task_statistics?query=date:' +
    new_date +
    ',type:machine';
  var http = require('http');
  var pm = new Promise(function (resolve, reject) {
    http
      .get(url, function (res) {
        var html = '';
        res.on('data', function (d) {
          html += d.toString();
        });
        res.on('end', function () {
          resolve(html);
        });
      })
      .on('error', function (e) {
        // reject(e)
        resolve(-1);
      });
  });
  return pm;
};
// 从王淑霖接口获取小绵羊游戏付费目标-此接口包含魅族付费目标
let queryWSL = function (new_date) {
  var url = 'http://148.70.251.170/wsl-A/get_sheep_pay.php?times=' + new_date;
  var http = require('http');
  var pm = new Promise(function (resolve, reject) {
    http
      .get(url, function (res) {
        var html = '';
        res.on('data', function (d) {
          html += d.toString();
        });
        res.on('end', function () {
          // console.log(html)
          resolve(html);
        });
      })
      .on('error', function (e) {
        // reject(e)
        resolve(-1);
      });
  });
  // console.log(pm)
  return pm;
};
// foreach加上async/await
const ykhForeach = async (arr, callback) => {
  const length = arr.length;
  const O = Object(arr);
  let k = 0;
  while (k < length) {
    if (k in O) {
      // console.log('doing foreach...');
      const kValue = O[k];
      await callback(kValue, k, O);
    }
    k++;
  }
};
