import { Provide } from '@midwayjs/core';
import { BaseService, CoolCommException } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { BasicdataSorterEntity } from '../../basicdata/entity/sorter';
import { PushSorterHealthEntity } from '../entity/sorterhealth';
import { PushSorterGpsEntity } from '../entity/sortergps';
import { PushSiteweightEntity } from '../entity/siteweight';
import { BasicdataSiteEntity } from '../../basicdata/entity/site';

/**
 * 分拣员上报（健康、GPS、压缩站称重）
 */
@Provide()
export class PushSorterAppService extends BaseService {
  @InjectEntityModel(BasicdataSorterEntity)
  basicdataSorterEntity: Repository<BasicdataSorterEntity>;

  @InjectEntityModel(PushSorterHealthEntity)
  pushSorterHealthEntity: Repository<PushSorterHealthEntity>;

  @InjectEntityModel(PushSorterGpsEntity)
  pushSorterGpsEntity: Repository<PushSorterGpsEntity>;

  @InjectEntityModel(PushSiteweightEntity)
  pushSiteweightEntity: Repository<PushSiteweightEntity>;

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

  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 reportHealth(param: any) {
    const sorter = await this.getSorter(param.sorterId);
    const row = await this.pushSorterHealthEntity.save({
      idCard: sorter.businessId,
      departmentId: sorter.departmentId,
      uploadTime: param.uploadTime ? new Date(param.uploadTime) : new Date(),
      temperature: param.temperature,
      heartRate: param.heartRate,
      bloodPressureHigh: param.bloodPressureHigh,
      bloodPressureLow: param.bloodPressureLow,
      bloodOxygen: param.bloodOxygen,
      stepCount: param.stepCount || 0,
      dataType: param.dataType || '周期',
    });
    return row;
  }

  async reportGps(param: any) {
    const sorter = await this.getSorter(param.sorterId);
    if (param.longitude == null || param.latitude == null) {
      throw new CoolCommException('缺少定位信息');
    }
    return this.pushSorterGpsEntity.save({
      idCard: sorter.businessId,
      name: sorter.businessName,
      departmentId: sorter.departmentId,
      uploadTime: param.uploadTime ? new Date(param.uploadTime) : new Date(),
      longitude: Number(param.longitude),
      latitude: Number(param.latitude),
      height: Number(param.height || 0),
      speed: Number(param.speed || 0),
      accuracy: Number(param.accuracy || 0),
    });
  }

  async addSiteweight(param: any) {
    const sorter = await this.getSorter(param.sorterId);
    if (!param.businessId) {
      throw new CoolCommException('请选择压缩站');
    }
    const weight = Number(param.weight);
    if (!weight || weight <= 0) {
      throw new CoolCommException('请填写垃圾重量');
    }
    const site = await this.basicdataSiteEntity.findOneBy({
      businessId: String(param.businessId),
    });
    return this.pushSiteweightEntity.save({
      businessId: param.businessId,
      departmentId: param.departmentId || site?.departmentId || sorter.departmentId,
      deviceNo: param.deviceNo || '人工填报',
      uploadTime: param.uploadTime ? new Date(param.uploadTime) : new Date(),
      garbageType: param.garbageType || 'SW64',
      weight,
      remark: param.remark,
      extraData: JSON.stringify({
        source: 'sorter-app',
        sorterId: sorter.businessId,
      }),
    });
  }

  async siteweightPage(query: any) {
    const { sorterId, page = 1, size = 10 } = query || {};
    const sorter = await this.getSorter(sorterId);
    const find = this.pushSiteweightEntity
      .createQueryBuilder('a')
      .select([
        'a.*',
        'd.businessName AS businessName',
        'd.siteType AS siteType',
      ])
      .leftJoin(BasicdataSiteEntity, 'd', 'a.businessId = d.businessId')
      .where('d.siteType = :st', { st: '压缩站' })
      .andWhere('a.deviceNo = :dn', { dn: '人工填报' });
    if (sorter.departmentId) {
      find.andWhere('a.departmentId = :deptId', {
        deptId: sorter.departmentId,
      });
    }
    find.orderBy('a.uploadTime', 'DESC');
    return this.entityRenderPage(find, { ...query, page, size }, false);
  }
}
