import { Inject, Provide } from '@midwayjs/core';
// import { Achievement } from '../entity/platform/achievement.entity';
import { TypeORMDataSourceManager } from '@midwayjs/typeorm';
import { Context } from '@midwayjs/koa';
import { Test } from '../entity/test.entity';
@Provide()
export class UtilService {
  @Inject()
  ctx: Context;
  randomStr(len = 6) {
    return Math.random().toString(36).slice(-len);
  }

  // 修改后信息后用户重新审核
  async updateUserAfter(id, body, role_type) {
    // const { status } = body;
    // if (status === '0') {
    //   const model = GetModel(upperFirst(role_type));
    //   const data = await model.findById(id).lean();
    //   await this.uModel.updateOne({ _id: data.user }, { status: '0' });
    // }
  }
  @Inject()
  dataSourceManager: TypeORMDataSourceManager;
  async DBTransaction() {
    const dataSource = this.dataSourceManager.getDataSource('default');
    const data: Test = {
      nick_name: '测试',
      account: `test-${new Date().getTime()}`, //
      hobby: ['睡觉'],
      props: { hobby: '睡觉' },
      array_props: [{ hobby: '睡觉', lik: 'nothing' }],
    };
    await dataSource.transaction(async em => {
      // 事务中的操作会依次做好,并且下一步会在上一步的基础上进行.只有整个函数执行完,才会落实到数据库中
      // const res = await em.update(Test, { id: 1 }, { account: 'test' });
      // const ri = await em.insert(Test, data);
      // const r2 = await em.count(Test, { where: { account: 'test-2' } });
      // if (r2 > 0) throw new ServiceError('data exists');
      // const r = await em.getRepository(Test).query('select json_query(\'{"a": [1, 2, 3, 4, 5], "b": ["2", "a b"], "c": {"d": 4, "e": "ab c"}}\'::jsonb,\'$.b\');');
      const tb = em
        .getRepository(Test)
        .createQueryBuilder()
        // .where('props @> :hobby', { hobby: { hobby: '睡觉' } });
        .where('hobby @> :hobby', { hobby: '睡觉' });
      const tres = await tb.getOne();
      console.log(tres);
      // const builder = em.getRepository(Test).createQueryBuilder('test').select(['test.id', 'test.array_props']).where({ id: 1 });
      // console.log(builder.getSql());
      // const res = await builder.getOne();
      // console.log(res);
    });
  }
}
