import { reactive, watch } from 'vue';
import storejs from 'store';
import deepClone from '@/helpers/deep-clone';

export const getVoiceChinesName = (
  name: string | undefined,
  onlyName?: boolean
) => {
  let viewname = name || '';
  if (name) {
    const cname = appState.chinesePartName[name];
    if (!cname) {
      const names = Object.keys(appState.chinesePartName);
      for (const n of names) {
        if (name.match(n)) {
          // console.table({
          //   输入名称: name,
          //   循环名称: n,
          //   匹配: name.match(n)
          // })
          viewname = name.replace(n, appState.chinesePartName[n]);
          break;
        }
      }
    } else {
      viewname = cname;
    }
  }
  if (onlyName) {
    return viewname ? viewname : '';
  } else {
    return viewname
      ? name + (name !== viewname ? ' (' + viewname + ')' : '')
      : '';
  }
};

export const appState = reactive({
  subjectId: 0,
  subjectLoading: false,
  origanSubjectId: 0, // 原始用户声部
  subjectOptions: [{ value: 0, text: '全部声部' }] as any[],
  chinesePartName: {} as any,
  MusicalInstrumentClassification: {} as any,
  tenantId: null as any,
  organId: null as any,
  extSubjectIds: [] as any[] // 学生的扩展声部
});

const initState = {
  list: [] as any[],
  params: {
    page: 1,
    rows: 10
  },
  error: false,
  levelId: 0,
  typeId: 0,
  levelOptions: [] as any[],
  typeOptions: null as null | any[],
  finished: false,
  loading: false,
  search: '',
  subjectId: 0,
  parentId: 1
};

export const getInitState = () => deepClone(initState);

const state = reactive(getInitState());

watch(state, () => {
  storejs.set('state', state);
});

export const save = () => {
  storejs.set('state', state);
};

export const sync = () => {
  const oldState = storejs.get('state');
  if (oldState) {
    for (const key in oldState) {
      if (Object.prototype.hasOwnProperty.call(oldState, key)) {
        const item: any = oldState[key];
        (state as any)[key] = item;
      }
    }
  }
};

export default state;
