import { scenicTouristList } from './../../../services';
import fetchService from './../../../utils/fetchService';
Component({
  props: {
    title: '',
    onChange: () => null
  },
  data: {
    list: [],
    selectedIds: []
  },

  async didMount() {
    await this.fetchTouristList();
  },

  methods: {
    updateState(state) {
      const func = resolve => this.setData(state, resolve);

      return new Promise(func);
    },

    async fetchTouristList() {
      await this.updateState({
        list: await fetchService(scenicTouristList)
      });
    },

    async setDataByIds(opts) {
      const {
        list = []
      } = this.data;
      const {
        ids = [],
        cancel = true,
        selected = true,
        reset
      } = opts || {};
      if (reset) list.forEach(item => item.selected = false);
      ids.forEach(_id => list.some(item => {
        const has = item.id === _id;
        if (has) item.selected = cancel ? !item.selected : selected;
        return has;
      }));
      const selectedItems = list.filter(item => item.selected);
      const selectedIds = selectedItems.map(item => item.id);
      this.props.onChange(selectedItems);
      await this.updateState({
        selectedIds,
        list: [...list]
      });
    },

    async onItemChange(id = []) {
      await this.setDataByIds({
        ids: [id]
      });
    },

    async onMoreChange(items) {
      const ids = items.map(item => item.id);
      await this.setDataByIds({
        ids,
        cancel: false,
        selected: true,
        reset: true
      });
    },

    async onDeleteItem(id) {
      await this.setDataByIds({
        ids: [id],
        cancel: false,
        selected: false
      });
    },

    async onEdit(item) {
      const {
        list
      } = this.data;
      const index = list.findIndex(({
        id
      }) => item.id === id);

      if (index > -1) {
        const _item = list[index];
        list[index] = { ..._item,
          ...item
        };
        await this.updateState({
          list: [...list]
        });
      }
    },

    async onAddItem(item) {
      const {
        list
      } = this.data;
      list.push(item);
      await this.updateState({
        list: [...list]
      });
    },

    async onNativeDelete(item) {
      const {
        list
      } = this.data;
      const index = list.findIndex(_item => _item.id === item.id);

      if (index > -1) {
        list.splice(index, 1);
        await this.updateState({
          list: [...list]
        });
      }
    }

  }
});