/* eslint-disable prettier/prettier */
import { computed, nextTick } from "vue";
import { useUserInfo } from "./useUser";
import { useUserStoreHook } from "/@/store/modules/user";

export function useCompany() {
  const { isSuperUser } = useUserInfo();
  const { SET_CURRENT_COMPANY } = useUserStoreHook();
  const companyList = computed(() => useUserStoreHook().companyList);

  const currentCompany = computed(
    () => useUserStoreHook().currentCompany || {}
  );

  const isSwitchingCompany = computed(() => useUserStoreHook().swithingCompany)

  const setCompanyList = (list) => {
    useUserStoreHook().companyList = list;
  }

  const setSwithingComapny = (state: boolean) => useUserStoreHook().swithingCompany = state;


  function setCurrentCompany(value, list?: any) {
    const filter: any = ({ companyCode }) => companyCode === value;

    const _list = list ? list : companyList.value;

    const company = _list.find(filter);

    if (company && company.companyCode) company.companyNo = company.companyCode

    SET_CURRENT_COMPANY(
      isSuperUser.value
        ? {
          companyName: value?.name || '所有公司',
          companyNo: value?.code || ''
        }
        : company
    );

    return company
  }

  return {
    companyList,
    currentCompany,
    setCurrentCompany,
    isSwitchingCompany,
    setSwithingComapny,
    setCompanyList
  };
}
