import ContactPersonService from "@/db/ContactPersonService";
import OutletDBService from "@/db/OutletDBService";
import UserInfoDBService from "@/db/UserInfoService";
import AddressService from "@/service/AddressService";
import UserService from "@/service/UserService";
import { eRole } from "@/types/roleType";
import { getUserMsg } from "./userMsg";

/* 拿到地址对应的用户昵称 */
export const getDisplayNamesFromAddress = async (
  addressList: string[]
): Promise<string[]> => {
  /* 数据库查 有结果拿 没结果网上查且存 */
  const user = getUserMsg();

  let foundList = [] as any[];
  let notFoundList = [] as any[];

  if (user?.role === eRole.user) {
    const ret = await ContactPersonService.getInstance().findByList(
      addressList
    );
    foundList = ret.foundList;
    notFoundList = ret.notFoundList;
  } else if (user?.role === eRole.staff) {
    const ret = await UserInfoDBService.getInstance().findByList(addressList);
    foundList = ret.foundList;
    notFoundList = ret.notFoundList;
  }

  const fullList = foundList as unknown as any;

  if (notFoundList.length !== 0) {
    if (user?.role === eRole.user) {
      const ret = await UserService.getInstance().staffInfo({
        addrs: notFoundList,
      });
      if (ret.code === 200) {
        const theoseNotFoundList = ret.data.item;
        ContactPersonService.getInstance().save(theoseNotFoundList);
        fullList.push(...theoseNotFoundList);
      }
    } else if (user?.role === eRole.staff) {
      const ret = await UserService.getInstance().userInfo({
        addrs: notFoundList,
      });
      if (ret.code === 200) {
        const theoseNotFoundList = ret.data;
        UserInfoDBService.getInstance().save(theoseNotFoundList);
        fullList.push(...theoseNotFoundList);
      }
    }
  }

  return addressList.map((item) => {
    const msg = fullList.find((i: any) => i?.addr === item);
    if (msg?.out_let_name) {
      return msg?.out_let_name + msg.user_name;
    } else {
      return msg?.phone;
    }
  });
};

/* 获取网点名称 */
export const getDisplayNamesFromOutletId = async (outletids: number[]) => {
  const promiseList = outletids.map(async (id) => {
    const outlet = await OutletDBService.getInstance().get(id);
    if (!outlet) {
      const ret = await AddressService.getInstance().getOutlet({
        id,
      });
      if (ret.code === 200) {
        await OutletDBService.getInstance().add({
          name: ret.data.outlet_name,
          id: ret.data.id,
        });
        return ret.data.outlet_name;
      }
    } else {
      !outlet.isDeleted &&
        AddressService.getInstance()
          .getOutlet({
            id,
          })
          .then((ret) => {
            if (ret.code === 200) {
              OutletDBService.getInstance().update({
                name: ret.data.outlet_name,
                id: ret.data.id,
              });
            } else {
              OutletDBService.getInstance().update({
                id,
                isDeleted: true,
              });
            }
          });
      return `${outlet.name}${outlet.isDeleted ? "(已停止营业)" : ""}`;
    }
  });
  const list = await Promise.all(promiseList);
  return list;
};

export const getDisplayNames = async (
  list: { outletId?: number; address?: string }[]
) => {
  const promiseList = list.map((i) => {
    if (i.outletId !== undefined) {
      return getDisplayNamesFromOutletId([i.outletId]).then((ret) => ret[0]);
    } else if (i.address !== undefined) {
      return getDisplayNamesFromAddress([i.address]).then((ret) => ret[0]);
    } else return "";
  });

  return Promise.all(promiseList);
};

export const getMsgFromAddress = async (
  addressList: string[]
): Promise<any[]> => {
  /* 数据库查 有结果拿 没结果网上查且存 */
  const user = getUserMsg();

  let foundList = [] as any[];
  let notFoundList = [] as any[];

  if (user?.role === eRole.user) {
    const ret = await ContactPersonService.getInstance().findByList(
      addressList
    );
    foundList = ret.foundList;
    notFoundList = ret.notFoundList;
  } else if (user?.role === eRole.staff) {
    const ret = await UserInfoDBService.getInstance().findByList(addressList);
    foundList = ret.foundList;
    notFoundList = ret.notFoundList;
  }

  const fullList = foundList as unknown as any;

  if (notFoundList.length !== 0) {
    if (user?.role === eRole.user) {
      const ret = await UserService.getInstance().staffInfo({
        addrs: notFoundList,
      });
      if (ret.code === 200) {
        const theoseNotFoundList = ret.data.item;
        ContactPersonService.getInstance().save(theoseNotFoundList);
        fullList.push(...theoseNotFoundList);
      }
    } else if (user?.role === eRole.staff) {
      const ret = await UserService.getInstance().userInfo({
        addrs: notFoundList,
      });
      if (ret.code === 200) {
        const theoseNotFoundList = ret.data;
        UserInfoDBService.getInstance().save(theoseNotFoundList);
        fullList.push(...theoseNotFoundList);
      }
    }
  }

  return addressList.map((item) => {
    const msg = fullList.find((i: any) => i?.addr === item);
    return msg;
  });
};
