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 { ShuyouGameDirectorEntity } from '../entity/game_director';
import { ShuyouUtilsService } from './utils';
/**
 * 游戏目标
 */
@Provide()
export class ShuyouGameTargetTencentService extends BaseService {
  @InjectEntityModel(ShuyouGameTargetEntity)
  ShuyouGameTargetEntity: Repository<ShuyouGameTargetEntity>;

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

  @Inject()
  logger: ILogger;

  @Inject()
  utils: Utils;

  @Inject()
  shuyouUtilsService: ShuyouUtilsService;

  /**
   * 重载修改接口
   */
  async update(param) {
    const exists = await this.ShuyouGameTargetEntity.findOne({
      id: param.id,
    });
    let content = '';
    let dingContent = '';
    let dingPhone = [];
    let directorName = '';
    const game_director = await this.ShuyouGameDirectorEntity.findOne({
      id: param.directorId,
    });
    if (_.isEmpty(game_director)) {
      directorName = '';
      dingPhone = [];
    } else {
      directorName = game_director.name;
      dingPhone.push(game_director.phone);
    }
    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;
      }
      if (exists.target_new != param.target_new) {
        content += '新增目标改为' + param.target_new;
      }
      if (exists.target_pay != param.target_pay) {
        content += '付费目标改为' + param.target_pay;
      }
      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) {
        // console.log('修改成功~');
        // throw new CoolCommException('修改成功~');
        dingContent =
          '+ **' +
          directorName +
          ' ↓↓↓**\n>##### ' +
          param.task_name +
          ',' +
          content +
          '\n';
        //微信机器人
        // await sendVx_Robot(
        //   directorName + ':' + param.task_name + ',' + content
        // );
        //钉钉机器人
        await this.shuyouUtilsService.postRobot(dingContent, dingPhone);
        //企业微信机器人
        await this.shuyouUtilsService.postRobotEnterpriseWeChat(dingContent);
        await this.shuyouUtilsService.postRobotEnterpriseWeChat2(dingContent);
        // console.log('修改成功~')
      } else {
        // throw new CoolCommException('修改成功~');
        console.log('修改失败~');
      }
    } 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;
    }
  }
  /**
   * 重写分页查询
   * @param query
   */
  async page(query) {
    let { task_name, new_date, directorId, is_complete } = query;
    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,t.login_modeId AS login_modeId,
              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_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
              t.game_agentId = 1
            ${this.setSql(task_name, 'and a.task_name LIKE ?', [
              `%${task_name}%`,
            ])}
            ${this.setSql(directorId, 'and b.id = ?', [directorId])}
            ${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])}
        `;
    return this.sqlRenderPage(sql, query);
  }
}
// 微信机器人接口
// let sendVx_Robot = function (content) {
//   var url =
//     'http://148.70.251.170:19730/?liebie=1&mubiao=数优-深圳对接组&neirong=' +
//     content;
//   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);
//       });
//   });
//   return pm;
// };
