import { connect } from 'herculex';
import { createSubscribe } from 'applet-page-component';
import { soldierListCerts, queryCertDetail } from '../../services';
Component(connect({
  mapStateToProps: {}
})(createSubscribe({
  async onShow() {
    await this.onInit();
  }

})({
  data: {
    imgSrcPrefix: '',
    certList: [],
    serviceList: [],
    certMap: {},
    loading: true
  },
  props: {
    componentData: {}
  },

  async didMount() {
    const {
      componentData
    } = this.props;
    const {
      serviceList
    } = componentData;
    await this.updateData({
      serviceList
    });
    await this.onInit();
    await this.updateData({
      loading: false
    });
  },

  methods: {
    updateData(data) {
      return new Promise(resolve => this.setData(data, resolve));
    },

    async onInit() {
      const {
        serviceList
      } = this.data;
      const {
        length
      } = serviceList;
      /*
      * 如果服务数量大于一个，请求获取证件列表接口
      * */

      if (length > 1) {
        await this.getCardList();
      }
      /*
      * 如果服务数量等于一个，请求获取证件详情接口
      * */


      if (length === 1) {
        await this.getCardDetail();
      }
    },

    async getCardList() {
      const certMap = {};
      const [err, result] = await soldierListCerts();
      if (err) return;
      result.forEach(item => {
        certMap[item.certType] = item;
      });
      await this.updateData({
        certMap
      });
    },

    async getCardDetail() {
      const {
        certMap,
        serviceList
      } = this.data;
      const serviceItem = serviceList[0] || {};
      const {
        certType
      } = serviceItem.extInfo || {};
      const [err, result] = await queryCertDetail(certType);
      if (err) return;
      certMap[certType] = result;
      await this.updateData({
        certMap
      });
    }

  }
})));