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) {}
  async getWallet(uid: string): Promise<any> {
    const data = await this.http.httpRequst(
      'https://server.fmode.cn/api/ailiao/wallet',
      { uid: uid },
      'POST'
    );
    return data['data'];
  }
  getFansAndFollow(uid: string): Promise<any> {
    let sql = `SELECT 
    (SELECT COUNT(*) FROM "ProfileRadar" WHERE "fromUser" = '${uid}' AND "name" = '关注' AND "isDeleted" IS NOT TRUE) AS follow,
    (SELECT COUNT(*) FROM "ProfileRadar" WHERE "toUser" = '${uid}' AND "name" = '关注' AND "isDeleted" IS NOT TRUE) AS fans;`;
    return this.http.customSQL(sql);
  }
  async getGift(type?: string): Promise<any> {
    let where = type ? `AND "type" = '${type}'` : '';
    let sql = `SELECT "objectId" AS "id","name","price","order","imgUrl","type","rightsMap"
    FROM "GiftModule"
    WHERE "company" = '${this.company}'
    ${where}
    ORDER BY "price"`;
    const data: any = await this.http.customSQL(sql);
    return data?.data;
  }
  getGiftLogCount(uid: string): Promise<any> {
    let sql = `SELECT SUM("index")
    FROM "LoveRender"
    WHERE "fromUser" ='${uid}'`;
    return this.http.customSQL(sql);
  }
  async getGiftList(uid: string, limit?: number, skip?: number): Promise<any> {
    let where = '';
    if (limit) {
      where = `OFFSET ${skip ?? 0} LIMIT ${limit}`;
    }
    let sql = `SELECT lr.name,lr.image
    FROM (
      SELECT *,ROW_NUMBER() OVER (PARTITION BY "gift" ORDER BY "createdAt" DESC) as rn
      FROM "LoveRender"
      WHERE "toUser" = '${uid}'
      AND "isDeleted" IS NOT TRUE
    ) lr
    WHERE lr.rn = 1
    ORDER BY lr."createdAt" DESC
    ${where}
    `;
    const data: any = await this.http.customSQL(sql);
    return data.data;
  }
  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);
  }

  /* 赠送礼物 */
  async putGift(
    toUid: string,
    gid: string,
    giftCount?: number
  ): Promise<any> {
    let baseurl = 'https://server.fmode.cn/api/ailiao/save_gift';
    let reqBody = {
      fromUid: Parse.User.current()?.id,
      toUid: toUid,
      gid: gid,
      index: giftCount ?? 1,
    };
    return await this.http.httpRequst(baseurl, reqBody, 'POST');
  }

  /** 获取房间列表
   * @star 星级
   * @sex 主播性别
   * */
  async getRooms(parse?: any): Promise<any> {
    let { uid, star, sex, title, recommend, follow } = parse;
    let whereSearch = title
      ? `AND (prof.name LIKE '%${title}%' OR r."title" LIKE '%${title}%')`
      : '';
    let whereStar = star ? `AND prof."state" = '${star}'` : '';
    let whereSex = sex ? `AND prof."sex" = '${sex}'` : `AND prof."sex" = '女'`;
    let whereHot = recommend ? `AND r."isHot" = TRUE` : '';
    let sql = `SELECT r."objectId" rid,r."title",r."isHot",r."cover",r."content",
    prof."name",prof."idcard",prof."state",prof.sex,prof.birthdate,
    us."mobile",us."objectId" AS uid,us.nickname,
    (
      SELECT prordar."objectId" FROM "ProfileRadar" AS prordar
      WHERE prordar."toUser" = us."objectId"
      AND prordar.name = '关注'
      AND prordar."isDeleted" IS NOT TRUE
      AND prordar."fromUser" = '${uid}'
      LIMIT 1
    ) AS follow
    FROM "Room" AS r
    LEFT JOIN "Profile" AS prof
    ON prof."objectId" = r."profile"
    LEFT JOIN "_User" AS us
    ON us."objectId" = r."user"
    WHERE r."company" = '${this.company}'
    AND r."isDeleted" IS NOT TRUE
    ${whereStar}
    ${whereSex}
    ${whereSearch}
    ${whereHot}
    `;
    if(follow){
      sql = follow ? `SELECT * FROM (${sql}) AS tabl WHERE follow IS NOT NULL` : ''
    }
    const data: any = await this.http.customSQL(sql);
    return data.data;
  }
}
