import {
  SettingsForServiceApi,
  DocumentApi,
  ServiceApi,
  RegistryApi,
  DictionaryApi,
} from '@openapi/registry-service';
import {
  SocialSupportMeasuresApi,
  CriteriaApi,
} from '@openapi/personal-accounts';
import { ActionTree, GetterTree, MutationTree } from 'vuex';
import axios from 'axios';

const settingsForServiceApi = new SettingsForServiceApi();
const documentApi = new DocumentApi();
const socialSupportMeasuresApi = new SocialSupportMeasuresApi();
const serviceApi = new ServiceApi();
const registryApi = new RegistryApi();
const criteriaApi = new CriteriaApi();
const dictionaryApi = new DictionaryApi();

interface State {
  card: Record<string, string>;
  cardInitial: Record<string, string>;
  serviceIdName: any;
  registryIdName: any;
  socialSupportMeasureName: any;
  dictionaries: any;
  loading: boolean;
  unsavedChanges: any;
  stateColorMapSet: {
    [key: string]: string;
  };
}

export const state: State = {
  card: {},
  cardInitial: {},
  serviceIdName: {},
  registryIdName: {},
  socialSupportMeasureName: {},
  dictionaries: {},
  loading: false,
  unsavedChanges: '',
  stateColorMapSet: {
    DRAFT: 'grey',
    IN_PROCESS: 'purple',
    READY_FOR_PUBLISH: 'positive',
  },
};

export const getters: GetterTree<State, State> = {
  settingsForServiceCard(state) {
    return state.card;
  },
  settingsForServiceCardInitial(state) {
    return state.cardInitial;
  },
  setServiceIdName(state) {
    return state.serviceIdName;
  },
  setRegistryIdName(state) {
    return state.registryIdName;
  },
  setsocialSupportMeasure(state) {
    return state.socialSupportMeasureName;
  },
  setSettingsDictionary(state) {
    return state.dictionaries;
  },
  stateColorMapSet(state) {
    return state.stateColorMapSet;
  },
  settingsLoading(state) {
    return state.loading;
  },
  unsavedChanges(state) {
    return state.unsavedChanges;
  },
};

export const mutations: MutationTree<State> = {
  settingsForServiceCard(state, card) {
    state.card = card;
  },
  settingsForServiceCardInitial(state, cardInitial) {
    state.cardInitial = cardInitial;
  },
  setServiceIdName(state, serviceIdName) {
    state.serviceIdName = serviceIdName;
  },
  setRegistryIdName(state, registryIdName) {
    state.registryIdName = registryIdName;
  },
  setsocialSupportMeasure(state, socialSupportMeasureName) {
    state.socialSupportMeasureName = socialSupportMeasureName;
  },
  setSettingsDictionary(state, dictionary) {
    const code = dictionary.filter.slice(6);

    state.dictionaries[code] = dictionary.records[0].documents;
  },
  setSettingsDictionaryEvent(state, dictionary) {
    state.dictionaries[dictionary.name] = dictionary.documents;
  },
  settingsLoading(state, loading) {
    state.loading = loading;
  },
  unsavedChanges(state, changes) {
    state.unsavedChanges = changes;
  },
};

export const actions: ActionTree<State, State> = {
  setCardForJson({ commit }, newCard) {
    if (newCard && Object.keys(newCard).length) {
      commit('settingsForServiceCard', newCard);
    }
  },
  setCardForJsonInitial({ commit }, newCard) {
    if (newCard && Object.keys(newCard).length) {
      commit('settingsForServiceCardInitial', newCard);
    }
  },
  setunsavedChanges({ commit }, changes) {
    commit('unsavedChanges', changes);
  },
  getSettingsForServicePersonMeta(
    { commit, dispatch, state }: any = {},
    { id, opts = {} } = {}
  ) {
    const resultExpand = [...(opts.expand || [])].join(',');
    commit('settingsLoading', true);
    settingsForServiceApi
      .getSettingsForServicePerson(id, resultExpand)
      .then((data: any) => {
        dispatch('getServiceId', data.data.serviceId);
        if (data.data.socialSupportMeasureId) {
          dispatch('getSocialSupportMeasure', data.data.socialSupportMeasureId);
        } else {
          commit('setsocialSupportMeasure', {});
        }
        if (data.data.registryId) {
          dispatch('getRegistryId', data.data.registryId);
        } else {
          commit('setRegistryIdName', {});
        }
        commit('settingsForServiceCard', data.data);
        commit('settingsForServiceCardInitial', data.data);

        if (
          data.data.settingsforservicecriteria &&
          data.data.settingsforservicecriteria.length
        ) {
          const arr = data.data.settingsforservicecriteria.map(
            (criteria: any) => criteria.criteriaId
          );
          const query = `id=in=(${arr.join(',')})`;

          criteriaApi
            .pagingCriteria(
              undefined,
              undefined,
              query,
              undefined,
              undefined,
              '',
              {}
            )
            .then((criteries) => {
              const critList = criteries.data.records;
              const total = critList.map((item, i) =>
                Object.assign(
                  {},
                  item,
                  state.card.settingsforservicecriteria[i]
                )
              );

              commit('settingsForServiceCard', {
                ...state.card,
                settingsforservicecriteria: total,
              });
              commit('settingsForServiceCardInitial', {
                ...state.card,
                settingsforservicecriteria: total,
              });
            });
        }
      })
      .finally(() => {
        commit('settingsLoading', false);
      });
  },
  async getSocialSupportMeasure({ commit }, id) {
    const { data } = await socialSupportMeasuresApi.getSocialSupportMeasures(
      id
    );

    commit('setsocialSupportMeasure', data);
    return data;
  },
  updateStatus({}, id) {
    // TODO: запроса нет в опенапи и ямле
    return axios.put(
      '/service/registry/service/settings-for-service/update-status',
      [{ settingsForServiceId: id }]
    );
  },
  getServiceId({ commit }: any = {}, id) {
    serviceApi.getService(id).then((data: any) => {
      commit('setServiceIdName', data.data);
    });
  },
  getRegistryId({ commit }: any = {}, id) {
    registryApi.getRegistry(id).then((data: any) => {
      commit('setRegistryIdName', data.data);
    });
  },
  getSettingsDictionary({ commit }, code) {
    return documentApi
      .pagingDocuments('dictionary', undefined, undefined, `code==${code}`)
      .then((data) => {
        commit('setSettingsDictionary', data.data);
        return data;
      });
  },
  getSettingsDictionaryEvent({ commit }, code) {
    return dictionaryApi.searchDictionary(`name==${code}`).then((data) => {
      commit('setSettingsDictionaryEvent', data.data[0]);
      return data;
    });
  },
};
