import { Inject, Provide } from '@midwayjs/decorator';
import { BaseService, CoolCommException } from 'midwayjs-cool-core';
import { InjectEntityModel } from '@midwayjs/orm';
import { Repository } from 'typeorm';
import * as _ from 'lodash';
import { ShuyouGameTargetEntity } from '../entity/game_target';
import { ILogger } from '@midwayjs/logger';
import { ShuyouGameTaskEntity } from '../entity/game_task';
import { Utils } from '../../../comm/utils';
import { ShuyouGameCompleteHandService } from './game_complete_hand';
import { ShuyouGameCompleteHandEntity } from '../entity/game_complete_hand';
import { ShuyouXJFUtilsService } from './utils_xjf';
import { ShuyouGameCompleteHandCardEntity } from '../entity/game_complete_hand_card';
import { ShuyouGameCompleteEntity } from '../entity/game_complete';
const axios = require('axios');
/**
 * 游戏目标
 */
@Provide()
export class ShuyouGameTargetService extends BaseService {
  @InjectEntityModel(ShuyouGameTargetEntity)
  ShuyouGameTargetEntity: Repository<ShuyouGameTargetEntity>;

  @Inject()
  logger: ILogger;

  @Inject()
  utils: Utils;

  @Inject()
  ShuyouGameCompleteHandService: ShuyouGameCompleteHandService;

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

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

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

  @Inject()
  ShuyouXJFUtilsService: ShuyouXJFUtilsService;

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

  /**
   * 重载修改接口
   */
  async update(param) {
    // console.log(param)
    const exists = await this.ShuyouGameTargetEntity.findOne({
      id: param.id,
    });
    param.createTime = new Date();
    param.updateTime = new Date();
    if (!_.isEmpty(exists)) {
      if (exists.target_new_low >= param.target_new) {
        param.target_new_low = param.target_new;
      } else {
        param.target_new_low = exists.target_new_low;
      }
      if (exists.target_pay_low >= param.target_pay) {
        param.target_pay_low = param.target_pay;
      } else {
        param.target_pay_low = exists.target_pay_low;
      }
      if (exists.target_active_low >= param.target_active) {
        param.target_active_low = param.target_active;
      } else {
        param.target_active_low = exists.target_active_low;
      }
      let addObj = {
        task_id: param.task_id,
        task_name: param.task_name,
        directorId: param.directorId,
        new_date: param.new_date,
        target_new: param.target_new,
        target_pay: param.target_pay,
        target_active: param.target_active,
        target_new_low: param.target_new_low,
        target_pay_low: param.target_pay_low,
        target_active_low: param.target_active_low,
      };
      const updateResult =
        await this.ShuyouGameTargetEntity.createQueryBuilder()
          .update()
          .set(addObj)
          .where('id = :id', {
            id: param.id,
          })
          .execute();
      if (updateResult.affected >= 1) {
        // throw new CoolCommException('修改成功~');
        // console.log('修改成功~')
      } else {
        // throw new CoolCommException('修改成功~');
        console.log('修改失败~');
      }
      //修改财务备注remark=====
      await this.ShuyouGameCompleteEntity.createQueryBuilder()
        .update()
        .set({ remark: param.remark })
        .where('task_id = :task_id and new_date = :new_date', {
          task_id: param.task_id,
          new_date: param.new_date,
        })
        .execute();
      //==========================
      //修改手动完成情况
      //==================================
      let obj = {
        task_id: param.task_id,
        new_date: param.new_date,
        complete_new_hand: param.complete_new_hand,
        complete_lc_hand: param.complete_lc_hand,
        is_pay_hand: param.is_pay_hand,
        complete_pay_hand: param.complete_pay_hand,
        price_hand: param.price_hand,
        amount_hand: param.amount_hand,
        pay_mode_hand: param.pay_mode_hand,
        other_pay_hand: param.other_pay_hand,
        is_same_hand: param.is_same_hand,
        account_hand: param.account_hand,
        is_wt_hand: param.is_wt_hand,
        is_xjf_hand: param.is_xjf_hand,
      };
      //查询本次修改之前的数据
      const oldCompleteHandEntity =
        await this.ShuyouGameCompleteHandEntity.findOne({
          task_id: param.task_id,
          new_date: param.new_date,
        });
      let old_amount_hand = 0;
      let old_complete_pay_hand = 0;
      if (oldCompleteHandEntity) {
        old_amount_hand = oldCompleteHandEntity.amount_hand;
        old_complete_pay_hand = oldCompleteHandEntity.complete_pay_hand;
      }
      //=============
      await this.ShuyouGameCompleteHandService.addOrUpdate(obj);
      //上传WT start=======================
      if (param.is_wt_hand == 1 || param.is_xjf_hand == 1) {
        const taskInfo = await this.ShuyouGameTaskEntity.findOne({
          id: param.task_id,
        });
        // console.log(taskInfo)
        if (taskInfo) {
          let game_id = '';
          let channel_id = '';
          let url = '';
          let new_amount_hand = 0;
          let new_complete_pay_hand = 0;
          if (param.is_wt_hand == 1) {
            if (param.is_same_hand == 0) {
              new_amount_hand =
                parseFloat(param.price_hand) *
                  parseFloat(param.complete_pay_hand) -
                parseFloat(old_amount_hand + '');
            } else {
              new_amount_hand =
                parseFloat(param.amount_hand) -
                parseFloat(old_amount_hand + '');
            }
            if (taskInfo.game_agentId == 5) {
              //魅族
              game_id = taskInfo.mz_id;
              channel_id = taskInfo.mz_channel;
              url =
                'https://sy.nkfzs.com/v2/data_collect/game_task_report_meizu?channel_id=' +
                channel_id +
                '&game_id=' +
                game_id +
                '&type=3&account=hand_' +
                new Date().getTime() +
                '&money=' +
                new_amount_hand;
            } else if (taskInfo.game_agentId == 1) {
              //腾讯
              game_id = taskInfo.qq_id;
              channel_id = taskInfo.qq_channel;
              url =
                'https://sy.nkfzs.com/v2/data_collect/game_task_report?channel_id=' +
                channel_id +
                '&game_id=' +
                game_id +
                '&type=3&account=hand_' +
                new Date().getTime() +
                '&money=' +
                new_amount_hand;
            }
            // console.log(url)
            new Promise(function (resolve, reject) {
              axios
                .get(url)
                .then((res: string) => {
                  // console.log(res)
                  resolve(res);
                })
                .catch((error: any) => {
                  // console.log(error)
                  resolve(error);
                  // reject(error)
                });
            });
          }
          if (param.is_xjf_hand == 1) {
            new_complete_pay_hand =
              parseInt(param.complete_pay_hand) -
              parseInt(old_complete_pay_hand + '');
            //上传手动付费到xjf后台
            game_id = taskInfo.xjf_id + '';
            for (var i = 0; i < new_complete_pay_hand; i++) {
              await this.ShuyouXJFUtilsService.uploadLog(
                game_id,
                'hand' + i + '_' + new Date().getTime(),
                '付费充值',
                '付费成功',
                ''
              );
            }

            //记录 QQ卡消耗 start=========================
            const card_list = param.card_list;
            if (card_list && param.pay_mode_hand == 0) {
              //删除之前该游戏该日期的QQ卡记录
              await this.ShuyouGameCompleteHandCardEntity.delete({
                task_id: param.task_id,
                new_date: param.new_date,
              });
              for (const item of card_list) {
                if (item.card_account != '' || item.card_balance != '') {
                  // console.log(item)
                  // 上传手动做付费的QQ卡，game_id,card_account,card_balance
                  let qqConsume;
                  // console.log(game_id + '----' + item.card_account + '----' + item.card_balance)
                  qqConsume = await this.ShuyouXJFUtilsService.uploadQQconsume(
                    game_id,
                    item.card_account,
                    item.card_balance
                  );
                  // console.log(qqConsume)
                  if (qqConsume.data == 'ok') {
                    await this.ShuyouGameCompleteHandCardEntity.save({
                      task_id: param.task_id,
                      new_date: param.new_date,
                      card_account: item.card_account,
                      card_balance: item.card_balance,
                    });
                  } else {
                    throw new CoolCommException(qqConsume.data);
                  }
                } else {
                  throw new CoolCommException('添加的qq卡信息不能为空');
                }
              }
            }
            //记录 QQ卡消耗 end=========================
          }
        }
      }
      //上传WT end=======================
      //==================================
    } else {
      throw new CoolCommException('未查询到数据，无法修改~');
    }
  }
  /**
   * 修改目标
   */
  async updateTarget(task_id: string, new_date: Date) {
    const gameTargetEntity = await this.ShuyouGameTargetEntity.findOne({
      task_id: task_id,
      new_date: new_date,
    });
    // this.logger.warn(task_id)
    // this.logger.warn(new_date)
    // this.logger.warn(gameTargetEntity)
    if (gameTargetEntity) {
      let targetValue = {
        updateTime: new Date(),
        target_new: 0,
        target_pay: 0,
        target_active: 0,
        lc_two: 0,
        lc_three: 0,
        lc_four: 0,
        lc_five: 0,
        lc_six: 0,
        lc_seven: 0,
        lc_eight: 0,
        lc_nine: 0,
        lc_ten: 0,
        lc_eleven: 0,
        lc_twelve: 0,
        lc_thirteen: 0,
        lc_fourteen: 0,
        lc_fifteen: 0,
        lc_sixteen: 0,
        lc_seventeen: 0,
        lc_eighteen: 0,
        lc_nineteen: 0,
        lc_twenty: 0,
        lc_twentyone: 0,
        lc_twentytwo: 0,
        lc_twentythree: 0,
        lc_twentyfour: 0,
        lc_twentyfive: 0,
        lc_twentysix: 0,
        lc_twentyseven: 0,
        lc_twentyeight: 0,
        lc_twentynine: 0,
        lc_thirty: 0,
      };
      const updateResult =
        await this.ShuyouGameTargetEntity.createQueryBuilder()
          .update()
          .set(targetValue)
          .where('task_id = :task_id and new_date = :new_date', {
            task_id: task_id,
            new_date: new_date,
          })
          .execute();
      // this.logger.warn(updateResult)
      const deleteResult =
        await this.ShuyouGameTargetEntity.createQueryBuilder()
          .delete()
          .where('task_id = :task_id and new_date > :new_date', {
            task_id: task_id,
            new_date: new_date,
          })
          .execute();
      // this.logger.warn(deleteResult)
      if (updateResult.affected >= 1 && deleteResult.affected >= 0) {
        return 1000;
      } else {
        return -1;
      }
    } else {
      return -1;
    }
  }
  /**
   * 添加指定任务目标
   */
  async addTarget(queryObject: ShuyouGameTaskEntity) {
    const gameTargetEntity = await this.ShuyouGameTargetEntity.findOne({
      task_id: queryObject.id,
      new_date: this.utils.formatDate(new Date()),
    });
    // this.logger.warn(gameTargetEntity)
    let target_new = 0;
    let target_pay = 0;
    let target_active = 0;
    target_new = Math.floor(
      Math.random() *
        (queryObject.target_new_high - queryObject.target_new_low + 1) +
        queryObject.target_new_low
    );
    target_pay = Math.floor(
      Math.random() *
        (queryObject.target_pay_high - queryObject.target_pay_low + 1) +
        queryObject.target_pay_low
    );
    target_active = Math.floor(
      Math.random() *
        (queryObject.target_active_high - queryObject.target_active_low + 1) +
        queryObject.target_active_low
    );
    // this.logger.warn(queryObject.directorId)
    let targetObj = {
      task_id: queryObject.id,
      task_name: queryObject.task_name,
      directorId: queryObject.directorId,
      new_date: this.utils.formatDate(new Date()),
      updateTime: new Date(),
      target_new: target_new,
      target_pay: target_pay,
      target_active: target_active,
      // lc_two: 0,
      // lc_three: 0,
      // lc_four: 0,
      // lc_five: 0,
      // lc_six: 0,
      // lc_seven: 0,
      // lc_eight: 0,
      // lc_nine: 0,
      // lc_ten: 0,
      // lc_eleven: 0,
      // lc_twelve: 0,
      // lc_thirteen: 0,
      // lc_fourteen: 0,
      // lc_fifteen: 0,
      // lc_sixteen: 0,
      // lc_seventeen: 0,
      // lc_eighteen: 0,
      // lc_nineteen: 0,
      // lc_twenty: 0,
      // lc_twentyone: 0,
      // lc_twentytwo: 0,
      // lc_twentythree: 0,
      // lc_twentyfour: 0,
      // lc_twentyfive: 0,
      // lc_twentysix: 0,
      // lc_twentyseven: 0,
      // lc_twentyeight: 0,
      // lc_twentynine: 0,
      // lc_thirty: 0
    };
    if (gameTargetEntity) {
      //已存在，则更新
      const updateResult =
        await this.ShuyouGameTargetEntity.createQueryBuilder()
          .update()
          .set(targetObj)
          .where('task_id = :task_id and new_date = :new_date', {
            task_id: queryObject.id,
            new_date: this.utils.formatDate(new Date()),
          })
          .execute();
      // this.logger.warn(updateResult)
      if (updateResult.affected >= 1) {
        return 1000;
      } else {
        return -1;
      }
    } else {
      //不存在，则新建
      await this.ShuyouGameTargetEntity.insert(targetObj);
    }
  }
  /**
   * 重写分页查询
   * @param query
   */
  async page(query) {
    let {
      task_id,
      task_name,
      new_date,
      directorId,
      is_complete,
      login_modeId,
      game_agentId,
    } = query;
    // if (!new_date) {
    //   new_date = this.utils.formatDate(new Date())
    // }
    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,c.remark,
              IFNULL(c.complete_active,0) AS complete_active,c.updateTime,c.is_complete,c.amount,t.xjf_id,
              b.name AS directorName,b.id AS directorId,t.login_modeId AS login_modeId,l.name AS login_mode,
              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,
              m.complete_new_hand,m.complete_lc_hand,m.is_pay_hand,m.complete_pay_hand,m.price_hand,m.amount_hand,m.pay_mode_hand,
              m.other_pay_hand,m.is_same_hand,m.account_hand,m.is_wt_hand,m.is_xjf_hand
            FROM
              shuyou_game_target a
              LEFT JOIN shuyou_game_task t ON a.task_id = t.id
              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_game_complete_hand m ON a.task_id = m.task_id AND a.new_date = m.new_date 
              LEFT JOIN shuyou_reason_incomplete d ON a.task_id = d.task_id AND a.new_date = d.new_date 
              LEFT JOIN shuyou_lo_mode l ON t.login_modeId = l.id
            WHERE
              1 = 1
            ${this.setSql(task_id, 'and a.task_id LIKE ?', [`%${task_id}%`])}
            ${this.setSql(task_name, 'and a.task_name LIKE ?', [
              `%${task_name}%`,
            ])}
            ${this.setSql(directorId, 'and b.id = ?', [directorId])}
            ${this.setSql(login_modeId, 'and t.login_modeId = ?', [
              login_modeId,
            ])}
            ${this.setSql(game_agentId, 'and t.game_agentId = ?', [
              game_agentId,
            ])}
            ${this.setSql(new_date, 'and a.new_date >= ? and a.new_date <= ?', [
              this.utils.formatDate(new Date(new_date[0])),
              this.utils.formatDate(new Date(new_date[1])),
            ])}
            ${this.setSql(is_complete, 'and c.is_complete = ?', [is_complete])}
        `;
    const result = await this.sqlRenderPage(sql, query);
    let page = 0;
    let size = 0;
    let total = 0;
    let pageInfo = [];
    if (result) {
      page = result.pagination.page;
      size = result.pagination.size;
      total = result.pagination.total;
      await ykhForeach(result.list, async (item, index) => {
        let obj = item;
        const handCardEntitys =
          await this.ShuyouGameCompleteHandCardEntity.find({
            task_id: item.task_id,
            new_date: item.new_date,
          });
        let cardList = [];
        if (handCardEntitys) {
          handCardEntitys.forEach(h => {
            let obj_son = {
              card_account: h.card_account,
              card_balance: h.card_balance,
            };
            cardList.push(obj_son);
          });
        }
        obj.card_list = cardList;
        pageInfo.push(obj);
      });
    }
    // console.log(pageInfo)
    let sqlRenderPage = {
      list: pageInfo,
      pagination: {
        page: page,
        size: size,
        total: total,
      },
    };
    // console.log(sqlRenderPage)
    return sqlRenderPage;
  }

  /**
   * 重载info接口
   * @memberof ShuyouGameTargetService
   */
  async info(id) {
    let info;
    const shuyouGameTargetEntity = await this.ShuyouGameTargetEntity.findOne({
      id,
    });
    const shuyouGameCompleteHandEntity =
      await this.ShuyouGameCompleteHandEntity.findOne({
        task_id: shuyouGameTargetEntity.task_id,
        new_date: shuyouGameTargetEntity.new_date,
      });
    // const handCardEntitys = await this.ShuyouGameCompleteHandCardEntity.find({
    //   task_id: shuyouGameTargetEntity.task_id,
    //   new_date: shuyouGameTargetEntity.new_date
    // });
    // let cardList = []
    // if (handCardEntitys) {
    //   handCardEntitys.forEach(e => {
    //     cardList.push(e)
    //   });
    // }
    info = shuyouGameTargetEntity;
    // info.card_list = cardList
    if (shuyouGameCompleteHandEntity) {
      info.complete_new_hand = shuyouGameCompleteHandEntity.complete_new_hand;
      info.complete_lc_hand = shuyouGameCompleteHandEntity.complete_lc_hand;
      info.is_pay_hand = shuyouGameCompleteHandEntity.is_pay_hand;
      info.complete_pay_hand = shuyouGameCompleteHandEntity.complete_pay_hand;
      info.price_hand = shuyouGameCompleteHandEntity.price_hand;
      info.amount_hand = shuyouGameCompleteHandEntity.amount_hand;
      info.pay_mode_hand = shuyouGameCompleteHandEntity.pay_mode_hand;
      info.other_pay_hand = shuyouGameCompleteHandEntity.other_pay_hand;
      info.is_same_hand = shuyouGameCompleteHandEntity.is_same_hand;
      info.account_hand = shuyouGameCompleteHandEntity.account_hand;
      info.is_wt_hand = shuyouGameCompleteHandEntity.is_wt_hand;
      info.is_xjf_hand = shuyouGameCompleteHandEntity.is_xjf_hand;
      // info.card_list = [{ card_account: '', card_balance: '' }];
    } else {
      info.complete_new_hand = 0;
      info.complete_lc_hand = 0;
      info.complete_pay_hand = 0;
    }
    return info;
  }

  /**
   * 重新下发今日付费未成功的账号以及重置留存账号
   * @memberof ShuyouGameTargetService
   */
  async resetPay(id) {
    const ShuyouGameTaskEntity = await this.ShuyouGameTaskEntity.findOne({
      id,
    });
    if (ShuyouGameTaskEntity) {
      // console.log(ShuyouGameTaskEntity)
      let message;
      message = await this.ShuyouXJFUtilsService.resetPay(
        ShuyouGameTaskEntity.xjf_id
      );
      if (message.data == 'ok') {
        return { code: 1000, data: message.data };
      } else {
        return { code: -1, data: message.data };
      }
    } else {
      return { code: -1, data: '未找到xjf_id' };
    }
  }

  /**
   * 查询任务目标与完成
   * @param query
   */
  async getTaskTAndC(queryObj) {
    let { task_id, new_date } = queryObj;
    const sql = `
          SELECT
              a.task_id,a.task_name,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.is_complete,c.amount,xmy_id,qq_channel,qq_id,mz_id,mz_channel,
              b.name AS directorName,l.name AS login_mode,g.name AS game_agent,
              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_task t ON a.task_id = t.id
              LEFT JOIN shuyou_game_director b ON a.directorId = b.id
              LEFT JOIN shuyou_lo_mode l ON t.login_modeId = l.id
              LEFT JOIN shuyou_game_agent g ON t.game_agentId = g.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
              1 = 1
            ${this.setSql(task_id, 'and a.task_id = ?', [task_id])}
            ${this.setSql(new_date, 'and a.new_date = ?', [
              this.utils.formatDate(new Date(new_date)),
            ])}
        `;
    // console.log(sql)
    return this.nativeQuery(sql);
  }
}

// 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++;
  }
};
