import { login } from "../../lib/logic";
import { Get } from "../../lib/request/method";
interface Dictionary {
  dictName: string;
  dictType: string;
  items: { dictLabel: string; dictValue: string }[]
}
export default Behavior({
  data: {
    $dictionaries: [] as App.Dictionary[],
  },
  lifetimes: {
    attached() {
      login()
        .then(() => Get<App.Dictionary[], Dictionary[]>(`/dict/getDicts`, {
          shareRequest: true,
          transform({ data }) {
            return data.map(item => {
              return {
                key: item.dictType,
                name: item.dictName,
                options: item.items.map(item => ({
                  label: item.dictLabel,
                  value: item.dictValue,
                  mutex: item.dictLabel === '无' && item.dictValue === '0'
                }))
              }
            })
          }
        }))
        .then(dictionaries => { this.setData({ $dictionaries: dictionaries }); })
    }
  },
  methods: {
    getDictionaryOptions(key: string) {
      const { options } = this.data.$dictionaries.find(item => item.key === key) ?? { options: [] };
      return options
    },
    getDictionaryLabel(key: string, value: string) {
      return this.getDictionaryOptions(key).find(item => item.value === value)?.label ?? ''
    }
  }
})
