import { connect } from 'herculex';
import request from './../../../core/utils/request';

const app = getApp();
Component(connect({})({
  data: {
    imgSrcPrefix: app.globalData.imgSrcPrefix,
    maxNum: 8,
    defaultColumn: 4,
    badgeConfig: {
      withArrow: true,
      direction: 'left',
    },
    badgeList: [],
  },
  props: {
    componentData: {},
  },
  didMount() {
    this.getData();
  },
  didUpdate(preProps) {
    if (preProps.componentData.componentUUID !== this.props.componentData.componentUUID) {
      return this.getData();
    }
  },
  methods: {
    async getData() {
      const {
        componentUUID,
        componentExtInfo,
        serviceList,
      } = this.props.componentData;
      let badgeList = serviceList;
      const { dynBadge } = componentExtInfo;
      if (!dynBadge) return this.setData({ badgeList });
      // 请求动态数据
      const options = {
        url: 'api/v1/component/dynamicBadge',
        method: 'GET',
        data: { componentUuid: componentUUID },
      };
      const [, data] = await request(options);
      if (data && data.length) {
        badgeList = badgeList.map(item => {
          const dynItem = data.find(t => item.serviceCode === t.serviceCode);
          if (dynItem && dynItem.value) {
            item.extInfo = {
              ...item.extInfo,
              badgeText: dynItem.value,
            };
          }
          return item;
        });
      }
      this.setData({ badgeList });
    },
  },
}));
