import randomId from 'random-id';

import { pinyin } from 'pinyin-pro';
import { iDocTransResult } from '../docBase/docBase.type';
import {
  iDocApiSpeaker,
  iDocSpeaker,
  iDocSpeakerAPIData,
} from './docSpeaker.type';

// 发言人头像配置
import {
  defaultSpeakerAvatar,
  editNameSpeakerAvatarBgColorList,
  editNameSpeakerAvatarList,
  splitedSpeakerAvatarList,
} from './docSpeaker.config';

// 获取发言人头像可用数据
export const getSpeakerAvatarLength = () => {
  return editNameSpeakerAvatarList.length;
};

// 默认发言人数据
const defaultSpeaker: iDocSpeaker = {
  // 封装数据
  uid: '1',
  displayName: '发言人',
  speakerAvatar: defaultSpeakerAvatar, // 默认头像
  speakerAvatarName: '',
  inSpeakerSummer: false,
  // 基础数据
  ui: '1',
  name: '',
};

// 解析发言人 Tag 接口数据到本地
export const resolveSpeakerAPIData = (
  speakerApiData?: iDocSpeakerAPIData,
  speakerSplited = false, // 发言人是否已经区分
): {
  speakerList: iDocSpeaker[];
  speakerAvatarLastIndex: number;
} => {
  // 返回默认发言人
  if (
    !speakerApiData ||
    !speakerApiData.user_info ||
    !speakerApiData.user_map_info
  ) {
    return {
      speakerList: [defaultSpeaker],
      speakerAvatarLastIndex: 0,
    };
  }
  // 返回数据
  const speakerList: iDocSpeaker[] = [];
  const { user_info } = speakerApiData;

  // 接口数据转为数组
  const apiSpeakerList: Array<
    iDocApiSpeaker & {
      userMapInfoId: string;
    }
  > = [];
  let apiSpeakerDataHasNoNameAvaId = false; // 是否需要补全发言人头像 ID
  let maxNameAvaId = 0; // 发言人头像下标
  Object.keys(user_info).forEach((key: keyof typeof user_info) => {
    const data = user_info[key];
    apiSpeakerList.push({
      ...data,
      userMapInfoId: key,
    });
    // 1. 外网数据处理(内网数据有userid/avatarUrl)
    if (!data.userid && !data.avatarUrl) {
      // 历史数据，有发言人，没有发言人头像 ID。需要修复
      if (data.name && data.nameAvaId === undefined) {
        apiSpeakerDataHasNoNameAvaId = true;
      }
      // 计算发言人构想最大值
      if (data.nameAvaId !== undefined) {
        maxNameAvaId = Math.max(maxNameAvaId, data.nameAvaId);
      }
    }
  });

  // 补全 NameAvaId 数据
  if (apiSpeakerDataHasNoNameAvaId) {
    // 数据补全
    apiSpeakerList.forEach((t) => {
      if (t.userid || t.avatarUrl) return;
      if (t.nameAvaId === undefined) {
        // 已超过头像 ID 最大值
        if (maxNameAvaId + 1 >= editNameSpeakerAvatarList.length) {
          maxNameAvaId = 0;
        } else {
          maxNameAvaId++;
        }
        t.nameAvaId = maxNameAvaId;
      }
    });
  }

  // 组装数据
  apiSpeakerList.forEach((userInfo) => {
    const {
      ui,
      name,
      defaultAvatarIdx,
      nameAvaId,
      isNewSpeakerSummer,
      userid,
      avatarUrl,
    } = userInfo;

    // 内网发言人
    if (userid && avatarUrl) {
      speakerList.push({
        // 基础数据
        ...userInfo,
        // 组装数据
        uid: ui,
        displayName: name,
        speakerAvatar: avatarUrl,
        speakerAvatarName: '',
        speakerAvatarBgColor: '',
        inSpeakerSummer: !!isNewSpeakerSummer,
        bizUid: userid,
        avatarUrl,
        userid,
      });
      return;
    }

    // 外网发言人
    // 1. 计算发言人展示名称

    // 没有发言人名称，从原文区进行计算(不需要同步)
    // 新增 智能区分发言人
    if (!name && defaultAvatarIdx === undefined) return;
    const displayName = name || `发言人 ${defaultAvatarIdx}`;
    const speakerAvatarName = name ? name[0] : '';

    let speakerAvatar = '';
    let speakerAvatarBgColor;

    if (defaultAvatarIdx === undefined) {
      // 2. 计算发言人头像
      const uiNumber = Number.parseInt(ui, 10);
      // 1.编辑的发言人 2. 区分过发言人 3.其他都是默认发言人
      speakerAvatar = name
        ? editNameSpeakerAvatarList[nameAvaId!]
        : speakerSplited
          ? splitedSpeakerAvatarList[uiNumber]
          : defaultSpeakerAvatar;
      speakerAvatarBgColor = name
        ? editNameSpeakerAvatarBgColorList[nameAvaId!]
        : undefined;
    } else {
      const avatarIdx = defaultAvatarIdx % splitedSpeakerAvatarList.length;
      speakerAvatar = splitedSpeakerAvatarList[avatarIdx];
      speakerAvatarBgColor = undefined;
    }

    speakerList.push({
      // 基础数据
      ...userInfo,
      // 组装数据
      uid: ui,
      displayName,
      speakerAvatar,
      speakerAvatarName,
      speakerAvatarBgColor,
      inSpeakerSummer: !!isNewSpeakerSummer,
    });
  });

  return {
    speakerList,
    speakerAvatarLastIndex: maxNameAvaId,
  };
};

// 解析 原文内发言人数据 发言人数据
export const resolveSpeakersFromParagraph = (
  transResult?: iDocTransResult,
  speakerSplited = false, // 发言人是否已经区分
): iDocSpeaker[] => {
  // console.log(
  //   'speakerData:resolveSpeakersFromParagraph:speakerSplited',
  //   speakerSplited,
  // );
  const uiList: string[] = [];

  (transResult?.pg ?? []).forEach((_pgItem) => {
    if (_pgItem && _pgItem.ui !== undefined) {
      if (!uiList.includes(_pgItem.ui)) {
        uiList.push(_pgItem.ui as string);
      }
    }
  });

  // 没有数据 || 未区分发言人(只有一个发言人且未进行发言人区分)
  if (!uiList.length || (uiList.length === 1 && !speakerSplited)) {
    return [
      {
        ...defaultSpeaker,
        ui: uiList[0],
        uid: uiList[0],
      },
    ];
  }

  // 已经区分发言人(只处理区分发言人逻辑即可，编辑发言人逻辑后续从 Map 信息处理)
  const splitedSpeakerAvatarLength = splitedSpeakerAvatarList.length;
  const paraphSpeakerList: iDocSpeaker[] = [];
  // eslint-disable-next-line array-callback-return
  uiList.some((ui) => {
    // 只需计算发言人区分的发言人(编辑后的发言人无需从此处计算)
    if (!/^\d+$/.test(ui)) return;

    // 发言人头像计算
    let speakerAvatar = defaultSpeakerAvatar;
    // 发言人区分之后的头像且未编辑过的发言人
    if (speakerSplited) {
      const speakerAvatarIndex = Number.parseInt(ui, 10);
      if (speakerAvatarIndex < splitedSpeakerAvatarLength) {
        speakerAvatar = splitedSpeakerAvatarList[speakerAvatarIndex];
      } else {
        speakerAvatar =
          splitedSpeakerAvatarList[
            speakerAvatarIndex % splitedSpeakerAvatarLength
          ];
      }
    }

    paraphSpeakerList.push({
      // 封装数据
      uid: ui,
      // 后续根据 Map 信息补充数据: displayName/speakerAvatar/speakerAvatarName/speakerAvatarBgColor
      displayName: `发言人${speakerSplited ? ` ${ui}` : ''}`,
      speakerAvatar,
      speakerAvatarName: '',
      // speakerAvatarBgColor: undefined,
      inSpeakerSummer: false,
      // 基础数据
      ui,
      name: '',
    });
  });

  return paraphSpeakerList;
};
