import { Injectable } from '@angular/core';
import * as Parse from 'parse';
import { Router } from '@angular/router';
import { HttpService } from './http.service';
@Injectable({
  providedIn: 'root',
})
export class AiChatService {
  isLoggedIn = false;
  company: string = 'Qje9D4bqol';
  constructor(
    private router: Router,
    private http: HttpService,
  ) {}
  getFansAndFollow(uid: string): Promise<any> {
    let sql = `SELECT 
    (SELECT COUNT(*) FROM "ProfileRadar" WHERE "fromUser" = '${uid}' AND "name" = '关注') AS follow,
    (SELECT COUNT(*) FROM "ProfileRadar" WHERE "toUser" = '${uid}' AND "name" = '关注') AS fans;`;
    return this.http.customSQL(sql);
  }
  getGift(uid: string): Promise<any> {
    let sql = `SELECT SUM("index")
    FROM "LoveRender"
    WHERE "fromUser" ='${uid}'`;
    return this.http.customSQL(sql);
  }
  getFriends(uid: string): Promise<any> {
    let sql = `SELECT u.avatar,u.nickname,u.name,u."objectId" AS uid FROM 
    (SELECT (CASE WHEN "friend" = '${uid}' THEN "user" ELSE "friend" END) fid
    FROM "Friends"
    WHERE "friend" = '${uid}'
    OR "user" = '${uid}'
    GROUP BY fid) AS f
    LEFT JOIN "_User" AS u
    ON u."objectId" = f.fid
    `;
    return this.http.customSQL(sql);
  }
  async getLinkUsers(uid: string): Promise<any> {
    // let date = this.datePipe.transform(new Date(), 'yyyy-MM-dd');
    let sql = `SELECT * FROM (
          SELECT row_number() over(partition by tbl."user" order by tbl."createdAt" desc) as "idx",tbl.user, tbl."createdAt", --tbl.content, tbl.appkey,
          us.avatar,us.nickname,us.mobile,
          (CASE WHEN DATE(tbl."createdAt") >= now() THEN true ELSE false END) as istoday
          FROM ( (SELECT * , content:: json ->> 'target_id' AS user 
            FROM "MessageLog" AS msglog
            WHERE jsonb_contains(content, '{"from_id": "${uid}"}')
            ORDER BY msglog."createdAt" DESC)
            UNION 
            (SELECT * ,content:: json ->> 'from_id' AS user 
            FROM "MessageLog" AS msglog 
            WHERE jsonb_contains(content, '{"target_id": "${uid}"}')
            )) AS tbl
            LEFT JOIN "_User" as us
            ON us."objectId" = tbl.user
          )as ntbl
          WHERE ntbl."idx"=1
        ORDER BY ntbl."createdAt" DESC`;
    let res = await this.http.customSQL(sql);
  }
}
