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';
  emojis: Array<any> = [];

  constructor(private http: HttpService) {
    this.initEmoji();
  }
  async getAccountLog(): Promise<any> {
    const uid = Parse.User.current()?.id;
    let query = new Parse.Query('Account');
    query.equalTo('user', uid);
    query.notEqualTo('isDeleted', true);
    query.select('objectId');
    let account = await query.first();
    if (!account?.id) {
      return;
    }
    let sql = `SELECT alog."assetCount",TO_CHAR(alog."createdAt", 'YYYY-MM-DD HH24:MI:SS') AS time,
    (CASE WHEN alog."targetAccount" = '${account.id}' THEN 'recharge' ELSE 'used' END) cate,
    "assetType","orderNumber","desc"
    FROM "AccountLog" AS alog
    WHERE (alog."targetAccount" = '${account.id}' OR alog."fromAccount" = '${account.id}')
    AND alog."isVerified" IS TRUE
    AND alog."isDeleted" IS NOT TRUE
    ORDER BY alog."createdAt" DESC`;
    let data: any = await this.http.customSQL(sql);
    return data?.data;
  }
  initEmoji() {
    let emojiChar =
      '☺-😋-😌-😍-😏-😜-😝-😞-😔-😪-😁-😂-😃-😅-😆-👿-😒-😓-😔-😏-😖-😘-😚-😒-😡-😢-😣-😤-😢-😨-😳-😵-😷-😸-😻-😼-😽-😾-😿-🙊-🙋-🙏-✈-🚇-🚃-🚌-🍄-🍅-🍆-🍇-🍈-🍉-🍑-🍒-🍓-🐔-🐶-🐷-👦-👧-👱-👩-👰-👨-👲-👳-💃-💄-💅-💆-💇-🌹-💑-💓-💘-🚲';
    let emojiKey = [
      '60a',
      '60b',
      '60c',
      '60d',
      '60f',
      '61b',
      '61d',
      '61e',
      '61f',
      '62a',
      '62c',
      '602',
      '603',
      '605',
      '606',
      '608',
      '612',
      '613',
      '614',
      '615',
      '616',
      '618',
      '619',
      '620',
      '621',
      '623',
      '624',
      '625',
      '627',
      '629',
      '633',
      '635',
      '637',
      '63a',
      '63b',
      '63c',
      '63d',
      '63e',
      '63f',
      '64a',
      '64b',
      '64f',
      '681',
      '68a',
      '68b',
      '68c',
      '344',
      '345',
      '346',
      '347',
      '348',
      '349',
      '351',
      '352',
      '353',
      '414',
      '415',
      '416',
      '466',
      '467',
      '468',
      '469',
      '470',
      '471',
      '472',
      '473',
      '483',
      '484',
      '485',
      '486',
      '487',
      '490',
      '491',
      '493',
      '498',
      '6b4',
    ];
    let emojis = [];
    let emojiCharArr = emojiChar.split('-');
    for (let i in emojiKey) {
      let em = {
        char: emojiCharArr[i],
        emoji: '0x1f' + emojiKey[i],
      };
      emojis.push(em);
    }
    this.emojis = emojis;
  }
  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."objectId" AS uid,f."channel"
     FROM 
      (SELECT (CASE WHEN "friend" = '${uid}' THEN "user" ELSE "friend" END) fid,"channel"
      FROM "Friends"
      WHERE "isDeleted" IS NOT TRUE
      AND "isPass" = TRUE
      AND ("friend" = '${uid}'
      OR "user" = '${uid}')
      GROUP BY fid,"channel") 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(params?: any): Promise<any> {
    params['company'] = this.company;
    let baseurl = 'https://server.fmode.cn/api/ailiao/roomlist';
    const data = await this.http.httpRequst(baseurl, params, 'POST');
    return data?.data;
  }

  async getOrderAnchor(limit?: number) {
    let sql = `SELECT us."objectId",us."nickname",us."avatar",
    COALESCE(SUM(llog.gold ),0) AS "credit"
    FROM "LoveRender" AS llog
    LEFT JOIN "_User" us
    ON us."objectId" = llog."toUser"
    WHERE llog.company = '${this.company}'
    AND llog."isDeleted" IS NOT TRUE
    GROUP BY us."objectId",us."username"
    ORDER BY "credit" DESC LIMIT ${limit ?? 10}`;
    let res: any = await this.http.customSQL(sql);
    return res.data;
  }

  async get_duration(rid: string, uid: string) {
    let url = 'https://server.fmode.cn/api/ailiao/remain_second';
    let params = {
      rid: rid,
      uid: uid,
    };
    let data = await this.http.httpRequst(url, params, 'POST');
    console.log(data);
    return data.data ?? 0;
  }

  //星座
  getConstellation(idCard: string): string {
    // 提取出生日期部分
    const birthDateStr = idCard.substring(6, 14);
    const year = parseInt(birthDateStr.substring(0, 4), 10);
    const month = parseInt(birthDateStr.substring(4, 6), 10);
    const day = parseInt(birthDateStr.substring(6, 8), 10);

    // 定义星座边界
    const constellationBoundaries = [
      { name: '摩羯座', start: new Date(year, 0, 20) },
      { name: '水瓶座', start: new Date(year, 1, 19) },
      { name: '双鱼座', start: new Date(year, 2, 20) },
      { name: '白羊座', start: new Date(year, 3, 20) },
      { name: '金牛座', start: new Date(year, 4, 21) },
      { name: '双子座', start: new Date(year, 5, 21) },
      { name: '巨蟹座', start: new Date(year, 6, 22) },
      { name: '狮子座', start: new Date(year, 7, 23) },
      { name: '处女座', start: new Date(year, 8, 23) },
      { name: '天秤座', start: new Date(year, 9, 23) },
      { name: '天蝎座', start: new Date(year, 10, 23) },
      { name: '射手座', start: new Date(year, 11, 22) },
      { name: '摩羯座', start: new Date(year + 1, 0, 19) }, // 用于处理12月23日及之后的情况
    ];

    // 创建输入日期对象
    const inputDate = new Date(year, month - 1, day);

    // 查找对应的星座
    for (let i = 0; i < constellationBoundaries.length - 1; i++) {
      if (
        inputDate >= constellationBoundaries[i].start &&
        inputDate < constellationBoundaries[i + 1].start
      ) {
        return constellationBoundaries[i].name;
      }
    }
    // 默认返回摩羯座（理论上不会执行到这里）
    return '摩羯座';
  }
}
