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


export function useCompany() {
  const userInfo = useUserInfo();
  const userStore = useUserStoreHook();

  const licenseSet = computed(() => userStore.licenseSet)

  /** 当前用户的公司列表 */  
  const companyList = computed(() => useUserStoreHook().companyList);
  /** 当前用户选择的公司 */ 
  const currentCompany = computed(() => useUserStoreHook().currentCompany || {});
  /** 设置账户的公司列表 */ 
  const setCompanies = (list) => useUserStoreHook().companyList = list

  function setCurrentCompany(value, list?: any) {
    const filter: any = ({ companyCode }) => companyCode === value;
    const company = (list || companyList.value).find(filter) || {}


    if (company && company.companyCode) { company.companyNo = company.companyCode }
    /** 超管用户可以查看所有 */ 
    if(userInfo.isSuperUser.value) {
      company.companyName = value?.companyName || '所有公司'
      company.companyCode = value?.companyNo || ''
    }

    userStore.setCurrentCompany(company);
    return company
  }

  function getCurrentLicense(){
    const license = licenseSet.value.find(item => item.companyNo === currentCompany.value.companyCode)
    return license?.company_license || ''
  }

  watch(() => companyList.value, () => {
    setCompanies(companyList.value.map(item => {
      const lice = licenseSet.value.find(({ companyNo }) => companyNo === item.companyCode)
      return { ...item, company_license: lice?.company_license }
    }))
  }, {
    deep: true
  })

  return {
    licenseSet,
    companyList,
    setCompanies,
    currentCompany,
    setCurrentCompany,
    getCurrentLicense
  };
}
