import { connect } from 'herculex';
import { reportCourtInfo, getCourtlistInfo } from './../utils';
import { setPagesQuery } from "../../../../core/utils/index";
const app = getApp();
Component(connect({
  mapStateToProps: {
    currentCourt: state => state.$global.currentCourt
  }
})({
  props: {
    componentData: {}
  },
  data: {
    imgSrcPrefix: app.globalData.imgSrcPrefix,
    courtInfo: {
      id: ''
    }
  },

  async didMount() {
    const {
      longitude,
      latitude
    } = getApp().globalData.regionData;
    const [err, res] = await getCourtlistInfo({
      lng: longitude,
      lat: latitude
    });
    if (err || !res) return [err, null];
    let currentCourt = null;

    for (const item of res.list) {
      currentCourt = item.list.find(every => every.id === res.currentId);
      currentCourt.courtName = item.name;
      if (currentCourt) break;
    }

    this.commit('$global:updateState', {
      courtInfo: res
    }); // 全部小区列表信息

    this.commit('$global:updateState', {
      currentCourt
    }); // 全部小区列表信息
    // 设置app.js中全局的参数

    const {
      id,
      name
    } = currentCourt;
    setPagesQuery({
      communityCode: id,
      communityName: name
    });
  },

  didUpdate() {
    // eslint-disable-next-line prefer-const
    let {
      currentCourt,
      courtInfo
    } = this.data;

    if (currentCourt && currentCourt.id !== courtInfo.id) {
      courtInfo = {
        id: currentCourt.id,
        name: currentCourt.name
      };
      this.setData({
        courtInfo
      });
      this.report();
    }
  },

  methods: {
    // eslint-disable-next-line no-unused-vars
    async addCard(e) {
      const {
        serviceList = []
      } = this.props.componentData;
      const {
        url,
        urlType
      } = serviceList[0] || {};
      const payload = {
        urlType,
        url
      };

      if (url) {
        return this.$page.dispatchGlobal('handleJumpService', payload);
      }
    },

    onJumpAreaSelect() {
      my.navigateTo({
        url: '/antbuilder/industry/smartcommunity/pages/area-select/index'
      });
    },

    async report() {
      const {
        currentCourt
      } = this.data;

      if (currentCourt && currentCourt.id && currentCourt.name) {
        const data = {
          dataType: 1,
          dataKey: currentCourt.id,
          dataTitle: currentCourt.name
        };
        await reportCourtInfo(data);
      }
    }

  }
}));