import { queryForAddressDistance } from '../order-confirm/service';
import { connect } from 'herculex';
import { getMeter } from '../../utils';
Component(connect({
  mapStateToProps: {
    globalShopId: state => state.$global.globalShopId || ''
  }
})({
  props: {
    tableList: [{
      name: 'test',
      mobile: 'test',
      region: ['provinceName', 'cityName', 'test'],
      regionCode: ['provinceCode', 'cityCode', 'test'],
      latitude: 'test',
      longitude: 'test',
      address: 'test',
      isDefault: 'test',
      id: 'test'
    }, {
      name: 'test',
      mobile: 'test',
      region: ['provinceName', 'cityName', 'test'],
      regionCode: ['provinceCode', 'cityCode', 'test'],
      latitude: 'test',
      longitude: 'test',
      address: 'test',
      isDefault: 'test',
      id: 'test'
    }],
    onDelItem: null,
    onEditItem: null,
    onTap: null,
    showDistance: false
  },
  data: {
    rightBtn: [{
      type: 'danger',
      text: '删除',
      index: 0
    }],
    list: []
  },

  async didMount() {
    const {
      deliverType,
      isChoose,
      tableList = []
    } = this.props;
    const {
      globalShopId
    } = this.data;
    this.setData({
      list: tableList
    });

    if (isChoose && deliverType === 'DELIVERY_LOGISTICS' && tableList.length) {
      // 是选择收货地址 需要计算距离
      const reqArry = tableList.map(v => queryForAddressDistance({
        id: v.id,
        shopId: globalShopId
      }));
      Promise.all(reqArry).then(res => {
        res.forEach((v, index) => {
          tableList[index] = { ...tableList[index],
            distance: getMeter(v.distance),
            flag: v.overDistance
          };
          this.setData({
            list: [...tableList]
          });
        });
        this.setData({
          showDistance: true
        });
      }).catch(err => console.log(err, 'err'));
    }
  },

  methods: {
    onRightItemClick(index, text, type, extraInfo, dateSet) {
      const {
        index: tabIndex
      } = dateSet;

      if (index === 0) {
        // 删除
        if (Object.prototype.toString.call(this.props.onDelItem) === '[object Function]') {
          this.props.onDelItem({
            index,
            data: this.props.tableList[tabIndex]
          });
        }
      }
    },

    editItem(e) {
      const index = e.target.dataset.index;

      if (Object.prototype.toString.call(this.props.onEditItem) === '[object Function]') {
        this.props.onEditItem({
          index,
          data: this.props.tableList[index]
        });
      }
    },

    itemTap(e) {
      console.log(e);
      const index = e.target.dataset.index;

      if (Object.prototype.toString.call(this.props.onTap) === '[object Function]') {
        this.props.onTap({
          index,
          data: this.props.tableList[index]
        });
      }
    }

  }
}));