import { Inject, Provide } from '@midwayjs/decorator';
import { BaseService, CoolCommException } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import * as _ from 'lodash';
import { AgentMerchantEntity } from '../entity/agentMerchant';
import * as moment from 'moment';
import { AgentEntity } from '../entity/agent';

@Provide()
export class AgentOrderService extends BaseService {

  @InjectEntityModel(AgentEntity)
  agentEntity: Repository<AgentEntity>;


  @InjectEntityModel(AgentMerchantEntity)
  agentMerchantEntity: Repository<AgentMerchantEntity>;

  @Inject()
  ctx;

  async summary(query) {
    let {
      orderNo = '',
      outOrderNo = '',
      mchId = '',
      payType = '',
      status = '',
      createTime = [],
    } = query;
    if (!createTime || createTime.length !== 2) {
      return {
        num1: 0,
        num2: 0,
        num3: 0,
        num4: 0,
        num5: 0,
      };
    }
    if (moment(createTime[1]).diff(moment(createTime[0]), 'days') > 30) {
      return {
        num1: 0,
        num2: 0,
        num3: 0,
        num4: 0,
        num5: 0,
      };
    }
    const { userId } = this.ctx.admin;
    const agent = await this.agentEntity.findOne({
      where: {
        userId: userId
      }
    })
    if (!agent) {
      return {
        num1: 0,
        num2: 0,
        num3: 0,
        num4: 0,
        num5: 0,
      };
    }
    const agentMchs = await this.agentMerchantEntity.findBy({ agentId: agent.id + '' })
    let mchIds = agentMchs.map(item => {
      return "'" + item.mchId + "'";
    })
    if (!mchIds || mchIds.length === 0) {
      return {
        num1: 0,
        num2: 0,
        num3: 0,
        num4: 0,
        num5: 0,
      };
    }
    const sql = `SELECT 
    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
    FROM dj_order a WHERE 1=1
    and a.mchId in (${mchIds.join(',')})
    ${this.setSql(orderNo, 'and a.orderNo like ?', [`%${orderNo}%`])}
    ${this.setSql(outOrderNo, 'and a.outOrderNo like ?', [`%${outOrderNo}%`])}
    ${this.setSql(mchId, 'and a.mchId like ?', [`%${mchId}%`])}
    ${this.setSql(payType, 'and a.payType = ?', [payType])}
    ${this.setSql(status, 'and a.status = ?', [status])}
    ${this.setSql(
      createTime && createTime.length === 2,
      'and (a.createTime between ? and ?)',
      createTime
    )}
    `;
    return this.nativeQuery(sql);
  }

  async page(query) {
    let {
      orderNo = '',
      outOrderNo = '',
      mchId = '',
      payType = '',
      status = '',
      createTime = [],
    } = query;
    if (!createTime || createTime.length !== 2) {
      throw new CoolCommException('请选择日期范围');
    }
    if (moment(createTime[1]).diff(moment(createTime[0]), 'days') > 30) {
      throw new CoolCommException('日期范围最大只能30天');
    }
    const { userId } = this.ctx.admin;
    const agent = await this.agentEntity.findOne({
      where: {
        userId: userId
      }
    })
    if (!agent) {
      return null;
    }
    const agentMchs = await this.agentMerchantEntity.findBy({ agentId: agent.id + '' })
    const mchIds = agentMchs.map(item => {
      return "'" + item.mchId + "'";
    })
    if (!mchIds || mchIds.length === 0) {
      return null;
    }
    const sql = `SELECT a.id, a.orderNo, a.outOrderNo, a.mchId, a.payType, a.amount, a.charge, a.status, a.currency, a.remark, a.createTime FROM dj_order a WHERE 1=1
      and a.mchId in (${mchIds.join(',')})
      ${this.setSql(orderNo, 'and a.orderNo like ?', [`%${orderNo}%`])}
      ${this.setSql(outOrderNo, 'and a.outOrderNo like ?', [`%${outOrderNo}%`])}
      ${this.setSql(mchId, 'and a.mchId like ?', [`%${mchId}%`])}
      ${this.setSql(payType, 'and a.payType = ?', [payType])}
      ${this.setSql(status, 'and a.status = ?', [status])}
      ${this.setSql(
      createTime && createTime.length === 2,
      'and (a.createTime between ? and ?)',
      createTime
    )}
    `;
    return this.sqlRenderPage(sql, query);
  }
}
