import { connect } from 'herculex';
import { getIn } from 'herculex/dist/utils/manipulate';
import { setPagesQuery } from '../../utils';
import { reportCourtInfo, getCourtlistInfo, openCardCase } from '../../utils/service';

const setToast = {
  AUDITING() {
    my.showToast({ content: '会员卡审核中' });
  },

  AUDIT_REJECT() {
    my.showToast({ content: '会员卡审核驳回' });
  },

  WAIT_RELEASE() {
    my.showToast({ content: '会员卡审核通过' });
  },

  CARD() {
    my.showToast({ content: '会员卡已开卡' });
  },
};
Component(
  connect({
    mapStateToProps: {
      regionCode: state => state.$global.regionCode,
      currentCourt: state => state.$global.currentCourt,
    },
  })({
    data: {
      serviceList: [],
      buttonItem: {},
      showRightMiddle: false,
      cardShowBtnDeteil: {},
      noGet:
        'https://gw.alipayobjects.com/mdn/rms_8ed4a1/afts/img/A*2T4xR7miYyUAAAAAAAAAAAAAARQnAQ',
      geted:
        'https://gw.alipayobjects.com/mdn/rms_8ed4a1/afts/img/A*qsXOQrAfO2AAAAAAAAAAAAAAARQnAQ',
      defaultAtvar:
        'https://gw.alipayobjects.com/mdn/rms_47fd3e/afts/img/A*8THwT7aSeiYAAAAAAAAAAABkARQnAQ',
      imgSrcPrefix: getApp().globalData.imgSrcPrefix,
      courtInfo: { id: '' },
    },
    props: {
      componentData: {},
    },
    didMount() {
      this.getServiceList();
      this.getButtonItem();
      this.setInit();
      this.getDistructor();
    },
    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: {
      async getDistructor() {
        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 });
      },
      getButtonItem() {
        const {
          componentExtInfo: {
            cardTemplateId,
            advertiseBackgroundUrl,
            getCardImgShowBtn,
            getCardImgText,
            getCardImgBtnColor,
            getCardImgValueFontColor,
            noGetCardShowBtn,
            noGetCardImgText,
            noGetCardBtnColor,
            noGetCardValueFontColor,
            noGetCardImg,
            getCardImg,
          },
        } = this.props.componentData;
        console.log(advertiseBackgroundUrl, 'advertiseBackgroundUrl');
        try {
          const {
            miniAppId = '',
            accessModeNew = '',
            title = '',
            uuid = '',
            link = '',
            linkQuery = '',
            linkType = '',
            state = '',
          } = advertiseBackgroundUrl ? JSON.parse(advertiseBackgroundUrl) : '';
          const buttonItem = {
            accessMode: accessModeNew,
            miniAppId,
            cardTemplateId,
            name: title,
            serviceUUID: uuid,
            url: link,
            urlQuery: `${linkQuery}&cardType=newMemberCardComponent&cardTemplateId=${cardTemplateId}`,
            urlType: linkType,
          };
          this.setData({
            buttonItem,
            showRightMiddle: state === 'Y',
            cardShowBtnDeteil: {
              getCardImgShowBtn,
              getCardImgText,
              getCardImgBtnColor,
              getCardImgValueFontColor,
              getCardImg,
            },
            noCardShowBtnDeteil: {
              noGetCardShowBtn,
              noGetCardImgText,
              noGetCardBtnColor,
              noGetCardValueFontColor,
              noGetCardImg,
            },
          });
        } catch (e) {
          console.log(e, '新会员卡数据出错');
        }
      },
      async setInit() {
        const { onShow = () => {} } = this.$page;
        this.$page.onShow = async () => {
          const { naviBack } = this.$page.data;
          onShow.call(this.$page);
          if (naviBack === 'new-member-card') {
            await this.dispatch('onResume');
            this.$page.setData({
              naviBack: '',
            });
          }
        };
      },
      getServiceList() {
        const { serviceList } = this.props.componentData;
        const list = [];
        serviceList.forEach(item => {
          if (item.name !== '权益中间件') {
            list.push(item);
          }
        });
        this.setData({
          serviceList: list,
        });
      },
      async openCardCaseRe() {
        const {
          componentExtInfo: { cardTemplateId },
        } = this.props.componentData;

        // eslint-disable-next-line no-unused-vars
        const [_, res] = await openCardCase({
          cardTemplateId,
        });

        if (res === 'CARD') {
          setToast[res]();
          await this.dispatch('onResume');
          return false;
        } else if (res !== 'NOT_CARD') {
          // eslint-disable-next-line no-unused-expressions
          setToast[res]();
          return false;
        } else {
          return true;
        }
      },
      async addCard(e) {
        const {
          componentExtInfo: { applyUrl, cardTemplateId },
        } = this.props.componentData;
        // eslint-disable-next-line no-unused-vars
        const result = await this.openCardCaseRe();
        if (!result) return;
        const { regionCode } = this.data;
        const index = getIn(e, ['target', 'dataset', 'index']);
        await this.dispatch('addCard', {
          index,
          applyUrl,
          cardTemplateId,
          regionCode,
          card: 'newMemberCardComponent',
        });
        this.openCardCaseRe();
      },
      goToCardDetail(e) {
        const memberInfo = getIn(e, ['target', 'dataset', 'memberInfo'], {});
        const { passId } = memberInfo;
        if (passId) {
          this.commit({
            memberInfo: {
              isOpenCardDeail: true,
              ...memberInfo,
            },
          });
          my.openCardDetail({
            passId,
          });
        }
      },
      async 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);
        }
      },
    },
  }),
);
