import { Get, Inject, Provide, Query, ALL } from '@midwayjs/decorator';
import { ILogger } from '@midwayjs/logger';
// import { Context } from 'egg';
import { CoolController, BaseController } from 'midwayjs-cool-core';
import { IQueue } from 'midwayjs-cool-queue';
import { ShuyouIdCardEntity } from '../../entity/idcard';
import { ShuyouIdCardService } from '../../service/idcard';
import * as _ from 'lodash';


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


/**
 * 商品
 */
@Provide()
@CoolController({
  // 添加通用CRUD接口
  api: ['add', 'delete', 'update', 'info', 'list', 'page'],
  // 设置表实体
  entity: ShuyouIdCardEntity,

})
export class ShuyouAppIdCardController extends BaseController {
  @Inject()
  shuyouIdCardService: ShuyouIdCardService;

  // 队列
  @Inject()
  demoQueue: IQueue;

  @Inject()
  logger: ILogger;

  /**
   *获取指定行数身份信息
   *http://127.0.0.1:8001/app/shuyou/idcard/getRows?channel=腾讯&rows=1
   *http://ykhvip.fun/api/app/shuyou/idcard/getRows?channel=腾讯&rows=1
   * @param {object} queryObject
   * @return {*} 
   * @memberof ShuyouAppIdCardController
   */
  @Get('/getRows')
  async getRows(@Query(ALL) queryObject) {
    let { channel, rows, flag } = queryObject
    // this.logger.info(channel)
    // this.logger.info(rows)
    if (!channel) {
      return this.fail('缺少必要参数[channel=渠道&rows=行数]', -1)
    }
    if (!rows || rows == 0) {
      rows = 1
    }
    if (!flag) {
      flag = ''
    }
    const count = parseInt(rows)
    if (isNaN(count)) {
      return this.fail('rows参数错误，必须为数字', -1)
    }
    const countAll = await this.shuyouIdCardService.getAllCount(flag);
    const offset = Math.round(Math.random() * countAll[0].num - 1)
    const list = await this.shuyouIdCardService.getRows(channel, offset, count, repeatTime, flag);
    if (list.length > 0) {
      return this.ok(list);
    } else {
      return this.fail('无符合条件的身份信息', -1);
    }
  }
  /**
   * 请求所有数据
   * @returns
   */
  // @Get('/all')
  // async all() {
  //   // return this.ok(await this.shuyouIdCardService.all());
  //   return this.ok(await this.shuyouIdCardService.all());
  // }

  /**
   *修改身份信息状态
   *http://127.0.0.1:8001/app/shuyou/idcard/updateRow?channel=腾讯&id_number=120321198408140840
   *http://ykhvip.fun/api/app/shuyou/idcard/updateRow?channel=腾讯&id_number=120321198408140840
   * @param {object} queryObject
   * @return {*} 
   * @memberof ShuyouAppIdCardController
   */
  @Get('/updateRow')
  async updateRow(@Query(ALL) queryObject) {
    const { channel, id_number } = queryObject
    const state = await this.shuyouIdCardService.updateRow(channel, id_number);
    if (state == 1000) {
      return this.ok('修改成功');
    } else {
      return this.fail('修改失败', -1);
    }

  }


  /**
   * 发送数据到队列
   */
  // @Post('/queue')
  // async queue() {
  //   this.demoQueue.queue.add(
  //     { a: 1 },
  //     {
  //       removeOnComplete: true,
  //       removeOnFail: true,
  //     }
  //   );
  // }
}
