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> = [];
  userLevelColor: any = {
    '1': {
      color: '#fff',
    },
    '2': {
      color: '#0ec52e',
    },
    '3': {
      color: '#377cf7',
    },
    '4': {
      color: '#cbb013',
    },
    '5': {
      color: '#ec760c',
    },
    '6': {
      color: '#ec0cce',
    },
    '7': {
      color: '#8d0cec',
    },
    '8': {
      color: '#dd0a0a',
    },
  };
  authorLevelColor: any = {
    '1': {
      color: '#10b590',
    },
    '2': {
      color: '#dd70ff',
    },
    '3': {
      color: '#ed9647',
    },
    '4': {
      color: '#fb73ca',
    },
    '5': {
      color: '#efeb38',
    },
    '6': {
      color: '#c11010',
    },
  };

  get identity(): boolean {
    let profile = JSON.parse(localStorage.getItem('profile') || '{}');
    return profile?.identyType === 'anchor';
  }
  friends: Array<any> = [];
  constructor(private http: HttpService) {
    this.initEmoji();
  }

  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 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;
  }
  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'];
  }
  /* 获取主播余额 */
  async getAuthorWallet(uid: string): Promise<any> {
    const data = await this.http.httpRequst(
      'https://server.fmode.cn/api/ailiao/wallet/income',
      { 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, id?: string): Promise<any> {
    let where = type ? `AND "type" = '${type}'` : ``;
    let whereId = id ? `AND "objectId" = '${id}'` : ``;
    let sql = `SELECT "objectId" AS "id","name","price","order","imgUrl","video","type","rightsMap","config"
    FROM "GiftModule"
    WHERE "company" = '${this.company}'
    AND "isDeleted" IS NOT TRUE
    ${where}
    ${whereId}
    ORDER BY "order"`;
    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 name,image,"gift",COUNT("gift")
      FROM "LoveRender"
      WHERE "toUser" = '${uid}'
      AND "isDeleted" IS NOT TRUE
      GROUP BY name,image,"gift"
      ${where}
    `;
    const data: any = await this.http.customSQL(sql);
    return data.data;
  }
  /* 获取好友列表 */
  async getFriends(uid: string, val?: string): Promise<any> {
    let where = val ? `WHERE u.nickname LIKE '%${val}%'` : '';
    let rejectsSql = `SELECT invited FROM "EventLog" WHERE "isDeleted" IS NOT TRUE AND "user" = '${uid}' AND "isAward" = TRUE `;
    let data: any = await this.http.customSQL(rejectsSql);
    let list = data.data;
    let notInclude = list?.map((item: any) => {
      return `'${item.invited}'`;
    });
    let sql = `SELECT u.avatar,u.nickname,u."objectId" AS uid,f."channel",
    f.deadline
     FROM
      (SELECT (CASE WHEN "friend" = '${uid}' THEN "user" ELSE "friend" END) fid,"channel",
      ("Friends".config::jsonb ->> '${uid}')::jsonb ->> 'deadline' AS deadline --被删除的聊天记录时间
      FROM "Friends"
      WHERE "isDeleted" IS NOT TRUE
      AND "isPass" = TRUE
      AND ("friend" = '${uid}'
      OR "user" = '${uid}')
      GROUP BY fid,"channel",deadline) AS f
    LEFT JOIN "_User" AS u
    ON u."objectId" = f.fid 
    ${
      notInclude.length > 0
        ? `WHERE u."objectId" NOT IN (${notInclude}) AND u.nickname LIKE '%${val}%'`
        : where
    }
    `;
    let res = await this.http.customSQL(sql);
    this.friends = res['data'];
    return res['data']
  }

  async getRetFriends(uid: string): Promise<Parse.Object | undefined> {
    let query = new Parse.Query('EventLog');
    query.equalTo('user', Parse.User.current()?.id);
    query.equalTo('invited', uid);
    query.notEqualTo('isDeleted', false);
    // query.equalTo('isAward', true);
    query.select('isAward');
    return await query.first();
  }
  /* 获取系统通知 */
  getSysNotice(uid: string, limit?: number, skip?: number): Promise<any> {
    let sql = `SELECT
    "Friends"."objectId" fid,"friend","Friends"."user",
    (CASE WHEN "user" = '${uid}' THEN '请求添加' || us.nickname ||'为好友'
	  ELSE '收到'||u.nickname||'的好友申请' END) title,
    (CASE WHEN "user" = '${uid}' THEN us.avatar
	  ELSE u.avatar END) avatar,
    (CASE WHEN "user" = '${uid}' THEN us."objectId"
	  ELSE u."objectId" END) tuid,
    (CASE WHEN "isPass" = TRUE THEN '200'
    WHEN "isPass" = FALSE THEN '101'
    ELSE '100' END) status,
    "Friends"."createdAt"
    FROM "Friends"
	  LEFT JOIN "_User" AS u
    ON u."objectId" = "Friends"."user"
	  LEFT JOIN "_User" AS us
    ON us."objectId" = "Friends"."friend"
    WHERE "Friends"."company" = '${this.company}'
    AND "Friends"."isDeleted" IS NOT TRUE
    AND (friend = '${uid}' OR "user" = '${uid}')
    ORDER BY "Friends"."createdAt" DESC
    OFFSET ${skip || 0} LIMIT ${limit || 20}`;
    return this.http.customSQL(sql);
  }

  async getLinkUsers(params: {
    company?: string;
    value?: string;
    limit?: number;
    skip?: number;
    sex?: string;
    city?: string;
  }): Promise<any> {
    params['company'] = this.company;
    let baseurl = 'https://server.fmode.cn/api/ailiao/users';
    const data = await this.http.httpRequst(baseurl, params, 'POST');
    return data?.data;
  }

  /* 赠送礼物 */
  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(type?: string, limit?: number, range?: string) {
    let startTime;
    let date = new Date();
    switch (range) {
      case 'month':
        startTime = date.getFullYear() + '-' + (date.getMonth() + 1) + '-1';
        break;
      case 'week':
        date.setDate(date.getDate() - date.getDay() + 1);
        date = new Date(date);
        startTime =
          date.getFullYear() +
          '-' +
          (date.getMonth() + 1) +
          '-' +
          date.getDate();
        break;
      default:
        startTime =
          date.getFullYear() +
          '-' +
          (date.getMonth() + 1) +
          '-' +
          date.getDate();
        break;
    }
    let sql = `SELECT us."objectId",us."nickname",us."avatar",ROUND(SUM("credit")::numeric, 2) AS credit
      FROM (
        SELECT COALESCE(SUM(llog.gold ),0) AS "credit",llog."toUser" AS uid
        FROM "LoveRender" AS llog
        WHERE llog.company = '${this.company}'
        AND llog."isDeleted" IS NOT TRUE
        ${range ? `AND llog."createdAt" >= '${startTime}'` : ''}
        GROUP BY llog."toUser"
        UNION
        SELECT SUM(lalog.duration / 60 * lalog.unit) "credit","Room"."user" AS uid
        FROM "LiveActiveLog" AS lalog
        LEFT JOIN "Room"
        ON lalog."room" = "Room"."objectId"
        WHERE lalog.company = '${this.company}'
        AND lalog."isDeleted" IS NOT TRUE
        ${range ? `AND lalog."createdAt" >= '${startTime}'` : ''}
        GROUP BY "Room"."user"
      ) AS tbl
      LEFT JOIN "_User" us
      ON us."objectId" = tbl.uid
      GROUP BY us."objectId",us."username"
      ORDER BY SUM(tbl."credit") DESC LIMIT ${limit ?? 50}`;
    if (type == 'user') {
      sql = `SELECT us."objectId",us."nickname",us."avatar",ROUND(SUM("credit")::numeric, 2) AS credit
        FROM (
          SELECT COALESCE(SUM(llog.gold ),0) AS "credit",llog."fromUser" AS uid
          FROM "LoveRender" AS llog
          WHERE llog.company = '${this.company}'
          AND llog."isDeleted" IS NOT TRUE
          ${range ? `AND llog."createdAt" >= '${startTime}'` : ''}
          GROUP BY llog."fromUser"
          UNION
          SELECT SUM(lalog.duration / 60 * lalog.unit) "credit",lalog."user" AS uid
          FROM "LiveActiveLog" AS lalog
          WHERE lalog.company = '${this.company}'
          AND lalog."isDeleted" IS NOT TRUE
          ${range ? `AND lalog."createdAt" >= '${startTime}'` : ''}
          GROUP BY lalog."user"
        ) AS tbl
          LEFT JOIN "_User" us
          ON us."objectId" = tbl.uid
          GROUP BY us."objectId",us."username"
          ORDER BY SUM(tbl."credit") DESC LIMIT ${limit ?? 50}`;
    }
    let res: any = await this.http.customSQL(sql);
    return res.data;
  }

  /* 获取直播时长 */
  async getLiveActiveLog(logid: string) {
    let sql = `SELECT SUM("duration") FROM "LiveActiveLog" WHERE "liveLog" = '${logid}'`;
    let res: any = await this.http.customSQL(sql);
    return res.data[0]?.sum;
  }

  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 '摩羯座';
  }

  async getPost(limit?: number, skip?: number, uid?: string): Promise<any> {
    let sql = `SELECT "DramaPost"."objectId", "DramaPost".content,"DramaPost".images,"DramaPost"."isVerify",
    us."objectId" uid, us.avatar,us.nickname,"Profile"."identyType",TO_CHAR("DramaPost"."createdAt", 'YYYY-MM-DD HH24:MI') AS formatted_date,
    (SELECT "isVerify" FROM "DramaPostLog" 
      WHERE "DramaPostLog"."dramaPost" = "DramaPost"."objectId" 
      AND "DramaPostLog"."user" = '${Parse.User.current()?.id}'
      AND "DramaPostLog"."isDeleted" IS NOT TRUE
      LIMIT 1
    ) AS "isPostLog",
    (SELECT COUNT(*) FROM "DramaPostLog" 
      WHERE "DramaPostLog"."dramaPost" = "DramaPost"."objectId" 
      AND "DramaPostLog"."isDeleted" IS NOT TRUE
      LIMIT 1
    ) AS "postCount",
    (SELECT "objectId" FROM "UserVip" 
      WHERE "UserVip"."user" = "DramaPost"."user" 
      AND "UserVip"."isDeleted" IS NOT TRUE
      AND DATE("UserVip"."expiredAt") >= now()
      LIMIT 1
    ) AS "isVip"
    --(CASE WHEN DATE("DramaPost"."createdAt") >= now() THEN true ELSE false END)
    FROM "DramaPost"
    LEFT JOIN "_User" as us
    ON us."objectId" = "DramaPost"."user"
    LEFT JOIN "Profile"
    ON "Profile"."user" = "DramaPost"."user"
    WHERE "DramaPost"."company" = '${this.company}'
    AND "DramaPost"."isDeleted" IS NOT TRUE
    ${uid ? `AND "DramaPost"."user" = '${uid}'` : ''}
    ${uid ? `` : `AND "DramaPost"."isVerify" IS TRUE`}
    ORDER BY "DramaPost"."createdAt" DESC
    OFFSET ${skip ?? 0} LIMIT ${limit ?? 10}`;
    let res: any = await this.http.customSQL(sql);
    return res.data;
  }

  async getCommentScore(room: string) {
    let sql = `SELECT (SUM("credit")/COUNT("objectId")) AS ave
    FROM "DramaPostLog"
    WHERE room = '${room}'
    `;
    let res: any = await this.http.customSQL(sql);
    return res.data[0]['ave'];
  }

  async getRelation(limit?: number, skip?: number) {
    let uid = Parse.User.current()?.id;
    let sql = `SELECT us."objectId",us."nickname",us."avatar",ROUND(SUM("credit")::numeric, 2) AS credit
    FROM (
      SELECT COALESCE(SUM(llog.gold ),0) AS "credit",llog."toUser" AS uid
      FROM "LoveRender" AS llog
      WHERE llog.company = '${this.company}'
      AND llog."isDeleted" IS NOT TRUE
      AND llog."fromUser" = '${uid}'
      GROUP BY llog."toUser"
      UNION
      SELECT SUM(lalog.duration / 60 * lalog.unit) "credit","Room"."user" AS uid
      FROM "LiveActiveLog" AS lalog
      LEFT JOIN "Room"
      ON lalog."room" = "Room"."objectId"
      WHERE lalog.company = '${this.company}'
      AND lalog."isDeleted" IS NOT TRUE
      AND lalog."user" = '${uid}'
      GROUP BY "Room"."user"
    ) AS tbl
    LEFT JOIN "_User" us
    ON us."objectId" = tbl.uid
    GROUP BY us."objectId",us."username"
    ORDER BY SUM(tbl."credit") DESC 
    OFFSET ${skip || 0} LIMIT ${limit ?? 50}`;
    if (this.identity) {
      sql = `SELECT us."objectId",us."nickname",us."avatar",ROUND(SUM("credit")::numeric, 2) AS credit
      FROM (
        SELECT COALESCE(SUM(llog.gold ),0) AS "credit",llog."fromUser" AS uid
        FROM "LoveRender" AS llog
        WHERE llog.company = '${this.company}'
        AND llog."isDeleted" IS NOT TRUE
        AND llog."toUser" = '${uid}'
        GROUP BY llog."fromUser"
        UNION
        SELECT SUM(lalog.duration / 60 * lalog.unit) "credit",lalog."user" AS uid
        FROM "LiveActiveLog" AS lalog
        LEFT JOIN "Room"
        ON lalog."room" = "Room"."objectId"
        WHERE lalog.company = '${this.company}'
        AND lalog."isDeleted" IS NOT TRUE
        AND "Room"."user" = '${uid}'
        GROUP BY lalog."user"
      ) AS tbl
        LEFT JOIN "_User" us
        ON us."objectId" = tbl.uid
        GROUP BY us."objectId",us."username"
        ORDER BY SUM(tbl."credit") DESC 
        OFFSET ${skip || 0} LIMIT ${limit ?? 50}`;
    }
    let res: any = await this.http.customSQL(sql);
    return res.data;
  }
}
