import { connect } from 'herculex';
import { getCommunityInfo, getVisitReason, visitRegistration } from '../utils';
import { storageAPI } from "../../../../core/utils/jsapi";
import { prefixPagePath, dynamicPageName } from "../../../../core/utils";
import dayjs from 'dayjs';
const app = getApp();
Component(connect({
  mapStateToProps: {
    userInfo: state => state.$global.userInfo,
    passport: state => state.$global.passport,
    alipayUid: state => state.$global.getIn(['userInfo', 'alipayUid'], ''),
    accessMode: state => state.accessMode,
    reasons: state => state.reasons || [],
    reasonsError: state => state.reasonsError || false,
    errorType: state => state.errorType
  }
})({
  props: {
    componentData: {}
  },
  data: {
    imgSrcPrefix: app.globalData.imgSrcPrefix,
    reportExpiresTime: 60,
    footer: [{
      text: '重新获取'
    }],
    subject: '请选择来访原因',
    showSecondReason: false,
    currentIndex: -1,
    buttonDisable: true,
    activatedStep: 1,
    //
    form: {
      communityCode: '',
      reason: '',
      description: '',
      reasonText: '',
      reasonLogo: '',
      extendFileds: '',
      longitude: '',
      latitude: '',
      buildingName: '',
      unitName: '',
      houseName: '',
      roomInfo: ''
    }
  },

  didUpdate(prevProps, prevData) {
    const {
      reasons,
      currentIndex,
      passport,
      form
    } = this.data;

    if (prevData.passport && prevData.passport.roomInfo !== passport.roomInfo && currentIndex > -1 && reasons[currentIndex].showFloor && passport.roomInfo) {
      this.setData({
        buttonDisable: reasons[currentIndex].childContent.required && !form.description,
        'form.roomInfo': passport.roomInfo,
        'form.buildingName': passport.buildingName,
        'form.unitName': passport.unitName,
        'form.houseName': passport.houseName
      });
    }
  },

  async didMount() {
    // 获取当前页面的参数信息
    const query = getCurrentPages().pop().options || {};
    const {
      communityCode,
      communityName,
      sceneCode
    } = query; // 获取拜访列表

    const res = await getVisitReason(sceneCode);
    const {
      reasons
    } = res;
    this.commit({
      reasons,
      reasonsError: !reasons
    });
    const [, {
      data = {}
    }] = await storageAPI.getStorage({
      key: 'passport'
    });
    let passport = {}; // 本地没有匹配passport的情况下，根据页面信息更新passport

    if (communityCode && !communityName) {
      // 请求communityName相关信息
      const res3 = await getCommunityInfo(communityCode);

      if (res3) {
        passport = { ...passport,
          ...res3,
          sceneCode
        };
      }
    } else {
      passport = {
        communityCode,
        communityName,
        sceneCode
      };
    }

    if (!communityCode && !this.data.passport.communityCode) {
      this.commit({
        errorType: 'NOCOMMUNITY',
        errorMsg: '小区不存在',
        errorBrief: '请扫描正确的二维码'
      });
      return;
    }

    if (!communityCode) return;

    if (data && !this.data.errorType) {
      passport = { ...data,
        ...passport
      }; // 检查本地passport是否过期, 没过期跳转到第三页面

      const reportExpiresTime = parseInt(this.props.componentData.componentExtInfo.reportExpiresTime || this.data.reportExpiresTime);

      if (passport.reason && passport.visitTime) {
        const nowTime = dayjs();
        const isReportExpires = nowTime.diff(dayjs(passport.visitTime), 'second') > reportExpiresTime;

        if (!isReportExpires || data.communityCode === communityCode) {
          this.commit('$global:updateState', {
            passport
          });
          return my.navigateTo({
            url: `${prefixPagePath}/${dynamicPageName}/index?pageCode=visitRegistrationPage`
          });
        } else {
          // 直接发起请求
          const formData = { ...passport,
            visitTime: dayjs().format()
          };
          const [err, res2 = {}] = await visitRegistration(formData);

          if (err || res2.result !== 'success') {
            const {
              communityCode: communityCode2,
              communityName: communityName2,
              sceneCode: sceneCode2
            } = passport;
            const jumpUrl = `${prefixPagePath}/${dynamicPageName}/index?pageCode=visitReasonPage&communityCode=${communityCode2}&communityName=${communityName2}&sceneCode=${sceneCode2}`;
            this.commit({
              errorType: 'SYSTEM_BUSY',
              errorMsg: '系统繁忙',
              errorBrief: '请稍后再试',
              operations: [{
                btnText: '重试',
                handleName: 'reload',
                url: jumpUrl
              }]
            });
            return;
          } // 更新passport信息，并跳转到第三页面


          const newPassport = { ...passport,
            qrCodeUrl: res2.qrCodeUrl || ''
          };
          this.commit('$global:updateState', {
            passport: newPassport
          }); // 更新storage

          await storageAPI.setStorage({
            key: 'passport',
            data: newPassport
          });
          return my.navigateTo({
            url: `${prefixPagePath}/${dynamicPageName}/index?pageCode=visitRegistrationPage`,
            success: () => {
              this.handleReset();
            }
          });
        }
      }
    }

    this.commit('$global:updateState', {
      passport
    });
  },

  methods: {
    // checkCertified() {
    //   if (this.data.accessMode === 'realName' && this.data.userInfo.isCertified === 'F') {
    //     this.commit({
    //       errorType: 'NOCERTIFIED',
    //       errorMsg: '还未完成实名认证',
    //       errorBrief: '请先完成实名认证',
    //       operations: [{ btnText: '去认证', handleName: 'jumpToAlipayPage', url: 'https://custweb.alipay.com/certify/personal/LIFE_PAY' }],
    //     });
    //   }
    // },
    async refreshReason() {
      // 获取当前页面的参数信息
      const query = getCurrentPages().pop().options || {};
      const {
        sceneCode
      } = query; // 获取拜访列表

      const res = await getVisitReason(sceneCode);
      const {
        reasons
      } = res;
      this.commit({
        reasons,
        reasonsError: !reasons
      });
    },

    onStepsItemClick() {
      const {
        passport
      } = this.data;
      const newPassport = { ...passport,
        roomInfo: ''
      };
      this.commit('$global:updateState', {
        passport: newPassport
      });
      my.navigateTo({
        url: `/antbuilder/industry/scanpass/pages/select-room/index?communityCode=${passport.communityCode}&communityName=${passport.communityName}&sceneCode=${passport.sceneCode}`
      });
    },

    // 选择来访原因
    handleReasons(e) {
      const {
        dataset
      } = e.target;
      const childContent = this.data.reasons[dataset.index].childContent || {};
      const buttonDisable = childContent.required || false; // eslint-disable-next-line no-mixed-operators

      const showSecondReason = childContent.childContentType === 'textarea' && childContent || childContent.childContentDatasource && childContent.childContentDatasource.length > 0;
      this.setData({
        'form.reason': dataset.code,
        'form.reasonText': dataset.title,
        currentIndex: dataset.index,
        showSecondReason,
        buttonDisable
      });
    },

    // 选择具体原因
    handleSecondReason(e) {
      const value = e.target.dataset.value || e.detail.value;
      const {
        reasons,
        currentIndex,
        form
      } = this.data;
      let buttonDisable = reasons[currentIndex].childContent.required && !value;

      if (reasons[currentIndex].showFloor && !form.roomInfo) {
        buttonDisable = true;
      }

      const reasonText = reasons[currentIndex].name + (e.target.dataset.title ? `-${e.target.dataset.title}` : '');
      const reasonLogo = e.target.dataset.logo;
      this.setData({
        'form.description': value,
        'form.reasonText': reasonText,
        'form.reasonLogo': reasonLogo,
        buttonDisable
      });
    },

    // 提交登记
    async onSubmit() {
      const {
        form,
        passport = {},
        alipayUid
      } = this.data;
      const formData = {
        communityCode: passport.communityCode,
        sceneCode: passport.sceneCode || '',
        reason: form.reason,
        description: form.description,
        extendFileds: form.extendFileds || '',
        roomInfo: form.roomInfo,
        buildingName: form.buildingName,
        unitName: form.unitName,
        houseName: form.houseName,
        longitude: app.globalData.regionData.longitude,
        latitude: app.globalData.regionData.latitude
      };
      const [err, res = {}] = await visitRegistration(formData);

      if (err || res.result !== 'success') {
        const {
          communityCode,
          communityName,
          sceneCode
        } = passport;
        const jumpUrl = `${prefixPagePath}/${dynamicPageName}/index?pageCode=visitReasonPage&communityCode=${communityCode}&communityName=${communityName}&sceneCode=${sceneCode}`;
        this.commit({
          errorType: 'SYSTEM_BUSY',
          errorMsg: '系统繁忙',
          errorBrief: '请稍后再试',
          operations: [{
            btnText: '重试',
            handleName: 'reload',
            url: jumpUrl
          }]
        });
        return;
      } // 更新passport信息，并跳转到第三页面


      const newPassport = { ...passport,
        alipayUid,
        reason: form.reason,
        description: form.description,
        reasonText: form.reasonText,
        reasonLogo: form.reasonLogo,
        qrCodeUrl: res.qrCodeUrl || '',
        visitTime: dayjs().format()
      };
      this.commit('$global:updateState', {
        passport: newPassport
      }); // 更新storage

      await storageAPI.setStorage({
        key: 'passport',
        data: newPassport
      });
      my.navigateTo({
        url: `${prefixPagePath}/${dynamicPageName}/index?pageCode=visitRegistrationPage`,
        success: () => {
          this.handleReset();
        }
      });
    },

    // 重置表单
    handleReset() {
      this.setData({
        currentIndex: -1,
        showSecondReason: false,
        buttonDisable: true,
        activatedStep: 1,
        'form.reason': '',
        'form.description': '',
        'form.reasonText': '',
        'form.reasonLogo': '',
        'form.roomInfo': '',
        'form.buildingName': '',
        'form.unitName': '',
        'form.houseName': ''
      });
    }

  }
}));