import { Get, Inject, Provide, Query, ALL } from '@midwayjs/decorator';
import { ILogger } from '@midwayjs/logger';
import { CoolController, BaseController } from 'midwayjs-cool-core';
import { ShuyouGameTaskEntity } from '../../entity/game_task';
import { ShuyouGameTaskService } from '../../service/game_task';
import * as _ from 'lodash';
import { Utils } from '../../../../comm/utils';
import { ShuyouGameAccountService } from '../../service/game_account';
import { ShuyouTaskAccountRecordEntity } from '../../entity/task_account_record';
import { InjectEntityModel } from '@midwayjs/orm';
import { Repository } from 'typeorm';
import { ShuyouGameAccountRecordEntity } from '../../entity/game_account_record';
import { ShuyouTaskAccountRecordService } from '../../service/task_account_record';
import { ShuyouGameTargetService } from '../../service/game_target';
import * as qiNiu from 'qiniu';
import { ShuyouFileListService } from '../../service/file_list';

// /**同一渠道身份证最大使用次数 **/
// const repeatTime = 20

/**
 * 商品
 */
@Provide()
@CoolController({
  // 添加通用CRUD接口
  api: ['add', 'update', 'info'],
  // 设置表实体
  entity: ShuyouGameTaskEntity,
  service: ShuyouGameTaskService,
})
export class ShuyouAppGameTaskController extends BaseController {
  @Inject()
  logger: ILogger;

  @Inject()
  ShuyouGameTaskService: ShuyouGameTaskService;
  @Inject()
  ShuyouGameTargetService: ShuyouGameTargetService;
  @Inject()
  ShuyouTaskAccountRecordService: ShuyouTaskAccountRecordService;
  @Inject()
  utils: Utils;

  @Inject()
  ShuyouGameAccountService: ShuyouGameAccountService;

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

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

  @Inject()
  ShuyouFileListService: ShuyouFileListService;

  /**http://ykhvip.fun/api/app/shuyou/game_task/getTaskTAndC?new_date=2022-05-31
   * http://127.0.0.1:8001/app/shuyou/game_task/getTaskTAndC?task_id=3520&new_date=2022-05-16
   * //获取游戏目标与完成{task_id,new_date}
   * @param {*} queryObject
   * @memberof ShuyouAppGameTaskController
   */
  //接口添加上任务对应的文件，每个类型只返回一个最高版本号的
  @Get('/getTaskTAndC')
  async getTaskTAndC(@Query(ALL) queryObject) {
    let { task_id, new_date } = queryObject;
    if (!new_date) {
      new_date = this.utils.formatDate(new Date(new_date));
    }
    let queryObj;
    if (task_id && task_id != '') {
      const taskInfo = await this.ShuyouGameTaskService.info(task_id);
      if (!taskInfo) {
        return this.fail('task_id不存在', -1);
      }
      if (taskInfo.is_run == 0) {
        return this.fail('该任务未运行', -1);
      }
      queryObj = {
        task_id: task_id,
        new_date: new_date,
      };
    } else {
      queryObj = {
        new_date: new_date,
      };
    }
    const list = await this.ShuyouGameTargetService.getTaskTAndC(queryObj);
    // this.logger.info(list)
    if (list.length > 0) {
      let resT = [];
      const allFile = await this.ShuyouFileListService.queryAll();
      list.forEach(e => {
        //
        let obj = {
          task_id: e.task_id,
          task_name: e.task_name,
          game_director: e.directorName,
          login_mode: e.login_mode,
          game_agent: e.game_agent,
          target_new: parseInt(e.target_new),
          target_pay: parseInt(e.target_pay),
          target_active: parseInt(e.target_active),
          complete_new: parseInt(e.complete_new),
          complete_pay: parseInt(e.complete_pay),
          complete_active: parseInt(e.complete_active),
          xmy_id: e.xmy_id,
          qq_id: e.qq_id,
          qq_channel: e.qq_channel,
          mz_id: e.mz_id,
          mz_channel: e.mz_channel,
          game_rate: e.game_rate, //群控效率
          game_rate_xmy: e.game_rate_xmy, //小绵羊后台效率
          is_complete: e.is_complete, //是否完成
          amount: e.amount, //付费流水
          incomplete_typeId: e.type_id, //未完成类型
          incomplete_reason: e.reason, //未完成原因
          incomplete_solution: e.solution, //解决办法
          incomplete_new: parseInt(e.incomplete_new),
          incomplete_pay: parseInt(e.incomplete_pay),
          incomplete_active: parseInt(e.incomplete_active),
        };
        //此处传入文件相关信息
        if (allFile.length > 0) {
          allFile.forEach(file => {
            if (file.task_id == e.task_id) {
              let fileObj = {
                file_type: file.type,
                file_version: file.fileVersion,
                qn_address: file.qiniuAddress,
                qn_hash: file.qiniuHash,
              };
              obj['type' + file.type] = fileObj;
            }
          });
        }
        //
        resT.push(obj);
      });

      return {
        code: 1000,
        message: '获取游戏数据成功',
        date: new_date,
        data: resT,
      };
    } else {
      return this.fail('任务' + task_id + '获取失败', -1);
    }
  }

  /**http://ykhvip.fun/api/app/shuyou/game_task/getScript?game_id=1000058
   * http://sjyh.kfzs.com/api/app/shuyou/game_task/getScript?game_id=8217
   * http://127.0.0.1:8001/app/shuyou/game_task/getScript?game_id=1000058
   * @param queryObject
   * @returns
   */
  @Get('/getScript')
  async getScript(@Query(ALL) queryObject) {
    let { game_id } = queryObject;
    const taskInfo = await this.ShuyouGameTaskService.infoByGameId(game_id);
    if (_.isEmpty(taskInfo)) {
      return this.fail('task_id不存在', -1);
    }
    const task_id = taskInfo.id;
    //type=11 指获取脚本类型的文件
    const fileEntity = await this.ShuyouFileListService.queryVersionByType(
      task_id,
      11
    );
    // console.log(fileEntity);
    if (fileEntity) {
      let reqObj = {
        task_id: fileEntity.task_id,
        file_version: fileEntity.fileVersion,
        file_address: fileEntity.qiniuAddress,
        file_hash: fileEntity.qiniuHash,
      };
      return {
        code: 1000,
        message: '获取成功',
        fileData: reqObj,
      };
    } else {
      return {
        code: 1001,
        message: '无脚本信息',
      };
    }
  }

  /**
   * http://127.0.0.1:8001/app/shuyou/game_task/get_account?task_id=3520&status=0
   * 拉取任务账号-新增账号{status 0.正常 1.冻结 2.密错 5.人脸验证  6.信用分不足}
   * @param {*} queryObject
   * @return {*}
   * @memberof ShuyouAppGameTaskController
   */
  @Get('/get_account')
  async getAccount(@Query(ALL) queryObject) {
    let { task_id, status } = queryObject;
    if (!task_id) {
      return this.fail('缺少必要参数[task_id=任务id]', -1);
    }
    const taskInfo = await this.ShuyouGameTaskService.info(task_id);
    if (!taskInfo) {
      return this.fail('task_id不存在', -1);
    }
    let account_state = 0;
    if (!status) {
      account_state = 0;
    } else {
      account_state = status;
    }
    const account_typeId = taskInfo.account_typeId;
    const gameIdList = taskInfo.gameIdList;
    const list = await this.ShuyouGameTaskService.getAccountOne(
      task_id,
      account_typeId,
      account_state
    );
    // this.logger.info(list)
    if (list.length > 0) {
      const account_id = list[0].id;
      await this.ShuyouGameAccountService.updateOccupy(account_id, task_id);
      const inserTaskAccountRecord =
        await this.ShuyouTaskAccountRecordEntity.createQueryBuilder()
          .insert()
          .into(ShuyouTaskAccountRecordEntity)
          .values({
            task_id: task_id,
            account_id: account_id,
            new_date: new Date(this.utils.formatDate(new Date())),
            getTimeNew: new Date(), // 新增取号时间
          })
          .execute();
      if (!inserTaskAccountRecord) {
        return this.fail('插入记录表失败', -1);
      }
      // this.logger.info(inserTaskAccountRecord.identifiers[0].id)
      for (const game_id of gameIdList) {
        await this.ShuyouGameAccountRecordEntity.save({
          account_id: account_id + '',
          game_id: game_id + '',
        });
      }
      let obj = {
        record_id: inserTaskAccountRecord.identifiers[0].id,
        account_text: list[0].account_text,
        password_text: list[0].password_text,
        vpn_text: list[0].vpn_text,
        manufacturer: list[0].manufacturer,
        model: list[0].model,
        pnumber: list[0].pnumber,
        imei: list[0].imei,
        imsi: list[0].imsi,
        simserial: list[0].simserial,
        androidid: list[0].androidid,
        mac: list[0].mac,
      };
      return this.ok(obj);
    } else {
      return this.fail('任务' + task_id + '无账号可取', -1);
    }
  }
  /**
   * 留存获取账号接口
   * http://127.0.0.1:8001/app/shuyou/game_task/get_account_retained?task_id=3520&retained_day=2
   * @param {*} queryObject{task_id:任务id,retained_day:留存天数}
   * @return {*}
   * @memberof ShuyouAppGameTaskController
   */
  @Get('/get_account_retained')
  async getAccountRetained(@Query(ALL) queryObject) {
    let { task_id, retained_day } = queryObject;
    if (!task_id || !retained_day) {
      return this.fail('缺少必要参数[task_id=任务id&retained_day=几留]', -1);
    }
    const taskInfo = await this.ShuyouGameTaskService.info(task_id);
    if (!taskInfo) {
      return this.fail('task_id不存在', -1);
    }
    let retained_date = this.utils.getNextDate(new Date(), 1 - retained_day);
    // this.logger.info(retained_date)
    const list = await this.ShuyouGameTaskService.getAccountRetainedOne(
      task_id,
      retained_date
    );
    // this.logger.info(list)
    if (list.length > 0) {
      const record_id = list[0].id;
      const updateTaskAccountRecord =
        await this.ShuyouTaskAccountRecordEntity.createQueryBuilder()
          .update()
          .set({
            statusRetained: -1,
            getTimeRetained: new Date(), // 留存取号时间
          })
          .where('id = :id', {
            id: record_id,
          })
          .execute();
      // this.logger.warn(updateTaskAccountRecord.affected)
      if (updateTaskAccountRecord.affected < 1) {
        return this.fail('修改记录表失败', -1);
      }
      let obj = {
        record_id: record_id,
        account_text: list[0].account_text,
        password_text: list[0].password_text,
        vpn_text: list[0].vpn_text,
        manufacturer: list[0].manufacturer,
        model: list[0].model,
        pnumber: list[0].pnumber,
        imei: list[0].imei,
        imsi: list[0].imsi,
        simserial: list[0].simserial,
        androidid: list[0].androidid,
        mac: list[0].mac,
      };
      return this.ok(obj);
    } else {
      return this.fail(
        '任务' + task_id + ' ' + retained_day + '留已无可取账号',
        -1
      );
    }
  }

  /**
   * 更新账号状态
   * http://127.0.0.1:8001/app/shuyou/game_task/updateAccount?record_id=10&status=0
   * status 0.新增留存成功 1.冻结 2.密错 3.禁用 4.新增出现留存 5.人脸验证  6.信用分不足
   * @param {*} queryObject
   * @return {*}
   * @memberof ShuyouAppGameTaskController
   */
  @Get('/updateAccount')
  async updateAccount(@Query(ALL) queryObject) {
    const { record_id, status } = queryObject;
    // status 0.新增留存成功 1.冻结 2.密错 3.禁用 4.新增出现留存 5.人脸验证
    const TaskAccountRecord =
      await this.ShuyouTaskAccountRecordService.updateAccount(
        record_id,
        status
      );
    if (TaskAccountRecord.code == 1) {
      await this.ShuyouGameAccountService.updateAccountState(
        TaskAccountRecord.account_id,
        status
      );
      return this.ok('修改成功');
    } else if (TaskAccountRecord.code == 2) {
      return this.fail(TaskAccountRecord.message, 2);
    } else {
      return this.fail('修改失败', -1);
    }
  }

  @Get('/getQiniuToken')
  async getQiniuToken() {
    var accessKey = '7_ZqHdxygi4b2rDfeYlRGcNzAotKIHny4Pw7FlrH';
    var secretKdy = 'LHkKpphENfKFMooSwptLo18xySESdS-EdY1yI59_';
    var mac = new qiNiu.auth.digest.Mac(accessKey, secretKdy);
    var options = {
      scope: 'qiniu-cool',
    };
    var putPolicy = new qiNiu.rs.PutPolicy(options);
    var uploadToken = putPolicy.uploadToken(mac);

    this.logger.warn(uploadToken);

    return {
      token: uploadToken,
    };
  }
}
