import { Provide } from '@midwayjs/core';
import { BaseService, CoolCommException } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { OperationWastesaleEntity } from '../entity/wastesale';
import { BasicdataSorterEntity } from '../../basicdata/entity/sorter';
import { BasicdataWastetypeEntity } from '../../basicdata/entity/wastetype';
import { BasicdataBuyerEntity } from '../../basicdata/entity/buyer';
import { BasicdataSiteEntity } from '../../basicdata/entity/site';

/**
 * 可回收物收益服务
 */
@Provide()
export class OperationWastesaleService extends BaseService {
  @InjectEntityModel(OperationWastesaleEntity)
  operationWastesaleEntity: Repository<OperationWastesaleEntity>;

  @InjectEntityModel(BasicdataSorterEntity)
  basicdataSorterEntity: Repository<BasicdataSorterEntity>;

  @InjectEntityModel(BasicdataWastetypeEntity)
  basicdataWastetypeEntity: Repository<BasicdataWastetypeEntity>;

  @InjectEntityModel(BasicdataBuyerEntity)
  basicdataBuyerEntity: Repository<BasicdataBuyerEntity>;

  @InjectEntityModel(BasicdataSiteEntity)
  basicdataSiteEntity: Repository<BasicdataSiteEntity>;

  /**
   * 写入前计算总价
   */
  async modifyBefore(data: any, type: 'add' | 'update') {
    if (type === 'add' || type === 'update') {
      if (data.weight !== undefined && data.unitPrice !== undefined) {
        data.totalPrice = Number(
          (Number(data.weight) * Number(data.unitPrice)).toFixed(2)
        );
      }
    }
  }

  async getSorter(sorterId: string) {
    const sorter = await this.basicdataSorterEntity.findOneBy({
      businessId: String(sorterId || '').trim(),
    });
    if (!sorter || sorter.status !== 0) {
      throw new CoolCommException('分拣员账号不可用');
    }
    return sorter;
  }

  /**
   * 分拣员新增销售记录
   */
  async appAdd(param: any) {
    const sorter = await this.getSorter(param.sorterId);
    const weight = Number(param.weight);
    let unitPrice = Number(param.unitPrice);
    if (!weight || weight <= 0) {
      throw new CoolCommException('请填写重量');
    }
    if (!param.wasteCode) {
      throw new CoolCommException('请选择垃圾种类');
    }
    if (!param.buyerCode) {
      throw new CoolCommException('请选择收购方');
    }
    if (!unitPrice) {
      const waste = await this.basicdataWastetypeEntity.findOneBy({
        code: param.wasteCode,
      });
      unitPrice = Number(waste?.price || 0);
    }
    const data: any = {
      departmentId: param.departmentId || sorter.departmentId,
      siteId: param.siteId,
      wasteCode: param.wasteCode,
      dateTime: param.dateTime || new Date(),
      weight,
      unitPrice,
      totalPrice: Number((weight * unitPrice).toFixed(2)),
      handlerId: sorter.businessId,
      buyerCode: param.buyerCode,
    };
    await this.operationWastesaleEntity.save(data);
    return data;
  }

  /**
   * 查看当前分拣员的销售记录
   */
  async appPage(query: any) {
    const { sorterId, page = 1, size = 10 } = query || {};
    const sorter = await this.getSorter(sorterId);
    const find = this.operationWastesaleEntity
      .createQueryBuilder('a')
      .select([
        'a.*',
        'c.businessName AS siteName',
        'd.name AS wasteName',
        'f.name AS buyerName',
      ])
      .leftJoin(BasicdataSiteEntity, 'c', 'a.siteId = c.businessId')
      .leftJoin(BasicdataWastetypeEntity, 'd', 'a.wasteCode = d.code')
      .leftJoin(BasicdataBuyerEntity, 'f', 'a.buyerCode = f.code')
      .where('a.handlerId = :hid', { hid: sorter.businessId })
      .orderBy('a.dateTime', 'DESC');
    return this.entityRenderPage(find, { ...query, page, size }, false);
  }
}
