import { prefixPagePath, dynamicPageName } from "../../../../../core/utils";
import { touristsList } from '../../../services';
import PubSub, { ADD_TOURIST_ITEM, EDIT_TOURIST_ITEM, DELETE_TOURIST_ITEM } from './../../../utils/pubSub';

const isEqual = (newVal, oldVal) => JSON.stringify(newVal) === JSON.stringify(oldVal);

Component({
  mixins: [],
  data: {
    showBottom: false,
    passengerList: []
  },
  props: {
    ids: [],
    onChangeList: () => null
  },

  onInit() {
    this.selectedIds = [];
    this.onAddItem = this.onAddItem.bind(this);
    this.onEditItem = this.onEditItem.bind(this);
    this.onDeleteItem = this.onDeleteItem.bind(this);
  },

  didMount() {
    this.getTouristsList(this.props.ids || []);
    PubSub.on(ADD_TOURIST_ITEM, this.onAddItem);
    PubSub.on(EDIT_TOURIST_ITEM, this.onEditItem);
    PubSub.on(DELETE_TOURIST_ITEM, this.onDeleteItem);
  },

  async didUpdate() {
    const {
      ids: curIds
    } = this.props;
    const {
      selectedIds: ids
    } = this;
    const {
      passengerList
    } = this.data;

    if (!isEqual(ids, curIds)) {
      await this.setTouristsList(passengerList, curIds);
    }
  },

  didUnmount() {
    PubSub.off(ADD_TOURIST_ITEM, this.onAddItem);
    PubSub.off(EDIT_TOURIST_ITEM, this.onEditItem);
    PubSub.off(DELETE_TOURIST_ITEM, this.onDeleteItem);
  },

  methods: {
    async onAddItem(item) {
      const {
        passengerList
      } = this.data;
      passengerList.unshift(item);
      await this.updateState({
        passengerList: [...passengerList]
      });
    },

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

      if (index > -1) {
        const _item = passengerList[index];
        passengerList[index] = { ..._item,
          ...item
        };
      }

      await this.updateState({
        passengerList: [...passengerList]
      });
    },

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

      if (index > -1) {
        passengerList.splice(index, 1);
      }

      await this.updateState({
        passengerList: [...passengerList]
      });
    },

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

      return new Promise(func);
    },

    async setTouristsList(list, ids = []) {
      list.forEach(item => {
        item.checked = !!ids.find(id => id === item.id);
      });
      const update = {
        passengerList: [...list]
      };
      this.selectedIds = ids;
      await this.updateState(update);
    },

    // 选择
    async onChangeInfo(e) {
      const {
        value
      } = e.detail;
      const {
        id
      } = e.currentTarget.dataset;
      const {
        passengerList
      } = this.data;
      const index = passengerList.findIndex(item => item.id === id);

      if (index > -1) {
        passengerList[index].checked = value;
      }

      await this.updateState({
        passengerList: [...passengerList]
      });
    },

    // 确定
    async sureGoBack() {
      const {
        passengerList
      } = this.data;
      const checkList = passengerList.filter(item => item.checked);

      if (checkList.length > 0) {
        await this.updateState({
          showBottom: false
        });
        this.props.onChangeList(checkList);
      } else {
        my.showToast({
          content: '请至少选择一名旅客'
        });
      }
    },

    openBuyInfo() {
      this.setData({
        showBottom: true
      });
    },

    closeBuyInfo() {
      const {
        passengerList
      } = this.data;
      passengerList.forEach(item => {
        item.checked = false;
      });
      this.setData({
        showBottom: false,
        passengerList: [...passengerList]
      });
      this.selectedIds = [];
    },

    // 查询联系人列表
    async getTouristsList(ids) {
      const [err, list] = await touristsList();
      if (err) return false;
      await this.setTouristsList(list, ids);
    },

    // 联系人操作
    goTouristsOperate(data) {
      const objInfo = data.target.dataset.info || {};
      const isTag = data.target.dataset.tag || '';
      const id = isTag === 'add' ? '' : objInfo.id;
      const {
        name
      } = objInfo;
      const {
        mobile
      } = objInfo;
      const {
        certType
      } = objInfo;
      const {
        idCardNo
      } = objInfo;
      let actionType = '';

      switch (isTag) {
        case 'update':
          actionType = 'UPDATE';
          break;

        case 'add':
          actionType = 'ADD';
          break;
      }

      if (isTag === 'add') {
        my.navigateTo({
          url: `${prefixPagePath}/${dynamicPageName}/index?pageCode=touristsOperate`
        });
      }

      if (isTag === 'update') {
        my.navigateTo({
          url: `${prefixPagePath}/${dynamicPageName}/index?pageCode=touristsOperate&id=${id}&actionType=${actionType}&name=${name}&mobile=${mobile}&certType=${certType}&idCardNo=${idCardNo}`
        });
      }
    }

  }
});