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

const deepClone = obj => JSON.parse(JSON.stringify(obj));

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

Component({
  props: {
    title: '',
    list: [],
    onAdd: () => null,
    onEdit: () => null,
    onDeleteItem: () => null,
    onNativeDelete: () => null
  },
  data: {
    renderList: []
  },

  deriveDataFromProps({
    list
  }) {
    const {
      renderList
    } = this.data;

    const _list = list.filter(item => item.selected);

    if (!isEqual(_list, renderList)) {
      const update = {
        renderList: deepClone(_list)
      };
      this.setData(update);
    }
  },

  onInit() {
    this.onAddItem = this.onAddItem.bind(this);
    this.onEditItem = this.onEditItem.bind(this);
    this.onNativeDelete = this.onNativeDelete.bind(this);
  },

  didMount() {
    PubSub.on(ADD_TOURIST_ITEM, this.onAddItem);
    PubSub.on(EDIT_TOURIST_ITEM, this.onEditItem);
    PubSub.on(DELETE_TOURIST_ITEM, this.onNativeDelete);
  },

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

  methods: {
    onEditItem(item) {
      this.props.onEdit(item);
    },

    onDeleteItem({
      currentTarget
    }) {
      const {
        value: id
      } = (currentTarget || {}).dataset || {};
      this.props.onDeleteItem(id);
    },

    onNativeDelete(item) {
      this.props.onNativeDelete(item);
    },

    onAddItem(item) {
      this.props.onAdd(item);
    },

    toDetailPage({
      currentTarget
    }) {
      const {
        value: item
      } = currentTarget.dataset;
      const {
        id,
        name = '',
        mobile = '',
        certType = '',
        idCardNo = ''
      } = item;
      const actionType = 'EDIT';
      const params = {
        id,
        name,
        mobile,
        actionType,
        certType,
        idCardNo,
        isRequent: 'requent',
        pageCode: 'touristsOperate'
      };
      my.navigateTo({
        url: `${prefixPagePath}/${dynamicPageName}/index${parseToQueryString(params)}`
      });
    }

  }
});