import { Inject, Post, Body, Headers } from '@midwayjs/core';
import { CoolController, BaseController } from '@cool-midway/core';
import { PushOpenService } from '../../service/open';
import { WeightUploadDto } from '../../dto/weight.dto';
import * as crypto from 'crypto';

const CLIENT_ID = '10001';
const SECRET = '9001ac9676b8';


/**
 * 开放上报数据接口
 */


@CoolController({
  prefix: '/open/push',
})
export class AppPushOpenController extends BaseController {
  @Inject()
  pushOpenService: PushOpenService;

  @Post('/weight', { summary: '原始称重上报接口' })
  async uploadWeight(
    @Headers() headers: any,
    @Body() data: WeightUploadDto,
  ) {
    const clientId = headers['clientid'];
    const sign = headers['sign'];

    // 1. clientId 校验
    if (clientId !== CLIENT_ID) {
      await this.pushOpenService.writePushAuditLog("weight",{ "deviceNo": clientId, "requestContent": data, "errorMessage": "非法 clientId" });
      return {
        code: 1001,
        msg: '非法 clientId',
        data: null,
      };
    }

    // 2. 签名校验
    const signStr =
      [
        clientId,
        data.deviceNo,
        data.uploadTime,
        data.garbageType,
        data.garbageWeight,
        SECRET,
      ].join(',');

    const realSign = crypto
      .createHash('sha256')
      .update(signStr)
      .digest('hex')
      .toLowerCase();

    if (realSign !== sign?.toLowerCase()) {
      await this.pushOpenService.writePushAuditLog("weight",{ "deviceNo": data.deviceNo, "requestContent": data, "errorMessage": "签名验证失败" });

      return {
        code: 1002,
        msg: '签名验证失败',
        data: null,
      };
    }
    try {
      await this.pushOpenService.reportWeight(data);
      return {
        code: 0,
        msg: '',
        data: 'success',
      };
    } catch (err) {
      await this.pushOpenService.writePushAuditLog("weight",{ "deviceNo": data.deviceNo, "requestContent": data, "errorMessage": "系统异常,写入失败." });

      return {
        code: 500,
        msg: '系统异常',
        data: null,
      };
    }
  }


  @Post('/cameragps', { summary: '原始车载监控上报接口' })
  async uploadCameraGps(
    @Body() body: any
  ) {

    const result = await this.pushOpenService.receiveCameraGpsMessage(body);
    //return this.ok(result);

    return {"messageId":result}

  }
}
