import { Inject, Provide } from '@midwayjs/decorator';
import { BaseService } from 'midwayjs-cool-core';
import { InjectEntityModel } from '@midwayjs/orm';
import { Repository } from 'typeorm';
import { ShuyouIdCardEntity } from '../entity/idcard';
import { ICoolCache } from 'midwayjs-cool-core';
// const fs = require('fs')
// const readline = require('readline');
// const path = require('path');
// const async = require('async')
import * as _ from 'lodash';
import { ShuyouIdCardUsageEntity } from '../entity/idcard_usage';

/**
 * 商品
 */
@Provide()
export class ShuyouIdCardService extends BaseService {
  @InjectEntityModel(ShuyouIdCardEntity)
  ShuyouIdCardEntity: Repository<ShuyouIdCardEntity>;

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

  @Inject('cool:cache')
  coolCache: ICoolCache;

  /***
   * 批量插入数据库
   */
  async batchAdd(id_card: any) {
    let idcard_text = id_card
    const sqlBatchAdd = `
      insert 
        IGNORE into 
        shuyou_id_card (id_name, id_number, flag) 
        values 
    `+ idcard_text;
    // console.log(sqlBatchAdd)
    return await this.nativeQuery(sqlBatchAdd);
  }

  /**
   * 获取库里身份证总数量
   * @return {*} 
   * @memberof ShuyouIdCardService
   */
  async getAllCount(flag: string) {
    const sql = `
    select count(id) as num from shuyou_id_card 
    where 1 = 1
      ${this.setSql(flag, ' and flag = ?', [flag])}
    `;
    return await this.nativeQuery(sql);
  }

  /**
  *获取指定行数身份信息
  */
  async getRows(channel: string, offset: number, rows: number, repeatTime: number, flag: string) {
    const sql = `
      SELECT * from shuyou_id_card  
      where 1 = 1
      ${this.setSql(flag, ' and flag = ?', [flag])}
      and id NOT IN (select id_idCard from shuyou_id_card_usage where
      ${this.setSql(channel, ' channel = ?', [channel])}
      ${this.setSql(repeatTime, ' and use_count > ? )', [repeatTime])}
      ${this.setSql(rows, ' limit ?,?', [offset, rows])}
    `;
    console.log(sql)
    const list = await this.nativeQuery(sql);
    let linshiData = [];
    let idList = [];
    if (!_.isEmpty(list)) {
      list.forEach(e => {
        let obj = {
          id_name: e.id_name,
          id_number: e.id_number,
          flag: e.flag
        }
        let idObj = {
          id_idCard: e.id,
          id_number: e.id_number,
          channel: channel
        }
        linshiData.push(obj)
        idList.push(idObj)
      });
    }
    // console.log(linshiData)
    // console.log(idList)
    idList.forEach(async e => {
      if (e.id_idCard) {
        const idCardUsageEntity = await this.ShuyouIdCardUsageEntity.findOne(e);
        // console.log(idCardUsageEntity)
        if (!idCardUsageEntity) {
          e.use_count = 1
          await this.ShuyouIdCardUsageEntity.insert(e);
        } else {
          idCardUsageEntity.use_count = idCardUsageEntity.use_count + 1;
          await this.ShuyouIdCardUsageEntity.save(idCardUsageEntity);
        }
      }
    });
    return linshiData
  }

  /**
   * 返回所有数据
   */
  // @Cache(5)
  // async all() {
  //   return this.ShuyouIdCardEntity.find();
  // }

  /**
   *
   *
   * @param {string} channel
   * @param {string} id_number
   * @return {*} 
   * @memberof ShuyouIdCardService
   */
  async updateRow(channel: string, id_number: string) {
    // const { id_name } = query;
    let obj = {
      channel: channel,
      id_number: id_number
    }
    const idCardUsageEntity = await this.ShuyouIdCardUsageEntity.findOne(obj);
    if (idCardUsageEntity) {
      idCardUsageEntity.use_count = 1000;
      await this.ShuyouIdCardUsageEntity.save(idCardUsageEntity);
      return 1000
    } else {
      return -1
    }
  }

  /**
   * 重载新增接口
   */
  //  async add(param) {
  //   const { category_id } = param;
  //   if(category_id){
  // const categories = await this.NewsCategoriesEntity.findOne(category_id);
  //       categories.article_count = categories.article_count + 1;
  //       await this.NewsCategoriesEntity.save(categories);
  //   }

  //   return super.add(param);
  // }


  /**
   * 事务
   * @param params
   * @param queryRunner
   */
  // @CoolTransaction({ isolation: 'SERIALIZABLE' })
  // async testTransaction(params: any, queryRunner?: QueryRunner) {
  //   await queryRunner.manager.insert<ShuyouIdCardEntity>(ShuyouIdCardEntity, {
  //     id_name: '测试',
  //     id_number: '52020210520123',
  //     flag: ''
  //   });
  // }
}
