import { mapState } from 'vuex'

const map = {
  currentCompany: (state) => state.user.currentCompany, // 当前选中的业务公司
  isSupertube: state => state.user.isSupertube, // 是否超管
  companylist: (state) => state.user.companylist
}

const companyHelper = {
  computed: { ...mapState(map) },
  methods: {
    /**
     * 当前公司发生改变时默认执行的方法,重置列表数据
     */
    onCompanyChangeInner() {
      const vm = this
      const { searchList, pageInfo, parmValue } = vm
      if (!searchList) return null
      if (pageInfo) this.pageInfo.curr = 1
      if (parmValue) this.parmValue.page = 1
      this.searchList()
    },

    /**
     * 判断当前是否有选中公司 没有选中返回false并提示警告信息
    */
    isHasCurrentCompany(message = '请选择一家公司') {
      const current = this.currentCompany
      if (!current && message) this.$message.warning(message)
      return !!current
    },

    /**
     * 判断当前公司是否为业务公司
    */
    currentIsBusinessCompany(message = '请选择一家业务公司') {
      const current = this.currentCompany
      const isBusiness = current.indexOf('GS') >= 0
      if (!isBusiness) this.$message.warning(message)
      return isBusiness
    },

    /**
     * 获取公司编码和名称根据code
    */
    getCompanyWithCode(code) {
      const _code = code || this.currentCompany
      if (!this.companylist || this.companylist.length === 0 || !_code) return {}
      return this.companylist.find(({ code }) => code === _code) || {}
    }
  },
  watch: {
    /**
     * 当前公司发生改变执行时默认执行mixins内部的onCompanyChangeInner
     * 当组件内部methods实现了onCompanyChange方法则调用组件内部的onCompanyChange方法
    */
    currentCompany: {
      handler() {
        const vm = this
        const { isSupertube, onCompanyChange, onCompanyChangeInner } = vm
        // 超管公司改变后执行该方法(刷新列表页或自定义实现)
        if (isSupertube) onCompanyChange ? onCompanyChange() : onCompanyChangeInner()
      },
      immediate: false,
      deep: true
    }
  }
}

export default companyHelper
