import { Provide, Logger } from '@midwayjs/decorator';
import { BaseService } from '@cool-midway/core';
import { ILogger } from '@midwayjs/logger';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import * as _ from 'lodash';
import { BillEntity } from '../entity/bill';
import * as moment from 'moment';

@Provide()
export class BillService extends BaseService {
  @InjectEntityModel(BillEntity)
  billEntity: Repository<BillEntity>;

  @Logger()
  logger: ILogger;

  async runBill() {
    this.logger.info('每日账单定时器计算');
    const date = moment().subtract(1, 'day').format('YYYY-MM-DD');
    const yestodayTime = [date + ' 00:00:00', date + ' 23:59:59'];
    const sql = `SELECT 
    a.mchId,
    SUM(IF(a.status = 1, a.amount, 0)) as num1,
    SUM(IF(a.status = 1, a.charge, 0)) as num2,
    SUM(IF(a.status = 1, 1, 0)) as num3,
    count(*) as num4,
    SUM(IF(a.status = 1, a.channelCharge, 0)) as num5
    FROM dj_order a WHERE 1=1 
    ${this.setSql(true, 'and (a.createTime between ? and ?)', yestodayTime)}
    group by a.mchId`;
    const data = await this.nativeQuery(sql);
    const promises = data.map(item => {
      return this.billEntity.insert({
        date,
        mchId: item.mchId,
        total: item.num4,
        num: item.num3,
        amount: item.num1,
        channelCharge: item.num5,
        charge: item.num2,
      });
    });
    return await Promise.all(promises);
  }

  async page(query) {
    let { date = [], mchId = '' } = query;
    const sql = `SELECT * FROM dj_bill a WHERE 1=1
      ${this.setSql(mchId, 'and a.mchId like ?', [`%${mchId}%`])}
      ${this.setSql(
        date && date.length === 2,
        'and (a.date between ? and ?)',
        date
      )}
    `;
    return this.sqlRenderPage(sql, query);
  }
}
