import { settradePayRe, getDischargeSettlementDetails, getsubscribeID } from './service';
import history from '../../utils/history';
import { debounce } from '../../utils/index';
import { reportCmPV_YL } from '../../utils/cloudMonitorHelper';
import { tradeResult } from '../../service/common';
Component({
  data: {
    jsonData: {
      Inpatient: {}
    },
    moneyArray: ['¥100', '¥200', '¥300', '¥500', '¥1000', '¥2000'],
    selectedMoney: null,
    money: null,
    inpatientId: '',
    // 住院人的id
    selectIndex: 0,
    // 默认选择的住院人的index
    isReady: false,
    attention: ''
  },

  didMount() {
    const {
      inpatientId,
      attention
    } = this.$page.data.query || {};
    this.setData({
      inpatientId,
      attention
    });
    this.subscribeMsg();
    /* 服务预警，押金缴纳 */

    reportCmPV_YL({
      title: '押金缴纳'
    });
  },

  methods: {
    subscribeMsg() {
      const pluginId = 2021001155639035;
      my.loadPlugin({
        plugin: `${pluginId}@*`,
        success: () => {
          this.setData({
            isReady: true
          }); // 储存插件实列
          // eslint-disable-next-line no-undef

          const pluginInstance = requirePlugin(`dynamic-plugin://${pluginId}`);
          this.requestSubscribeMessage = pluginInstance.requestSubscribeMessage;
        }
      });
    },

    pageScrollToFn(scrollTop) {
      my.pageScrollTo({
        scrollTop
      });
    },

    // 当input框失焦时候，自动返回顶部
    onBlurChange() {
      this.pageScrollToFn(0);
    },

    // 由于唤起支付弹窗时候，会遮挡掉支付按钮，所以对页面做了自动滚动处理
    onFocusChange() {
      setTimeout(() => {
        this.pageScrollToFn(100);
      }, 100);
    },

    async getJsonData(info) {
      const {
        inpatientId
      } = this.data;

      try {
        // 分为两种情况，第一种当从住院人列表跳转过来的时候，有住院人id，第二种是从首页跳转过来，无住院人id
        if (!inpatientId) {
          const infoDetail = info && info.length > 0;
          this.setData({
            jsonData: {
              Inpatient: infoDetail ? info[0] : {}
            },
            inpatientId: infoDetail ? info[0].inpatientId : ''
          });
        } else {
          const res = await getDischargeSettlementDetails({
            inpatientId
          });
          this.choosePatient(res);
        }
      } catch (error) {
        console.log(error, 'error');
      }
    },

    onGetDatas(info) {
      if (!info || info.length === 0) {
        my.alert({
          content: this.data.attention || '请绑定住院人',
          success: () => {
            my.navigateBack();
          }
        });
        return false;
      }

      this.getJsonData(info);
    },

    selectMoney(event) {
      this.setData({
        selectedMoney: event.target.dataset.index,
        money: parseInt(this.data.moneyArray[event.target.dataset.index].replace('¥', ''))
      }, () => {
        this.payMoney();
      });
    },

    changeMoney: debounce((event, that) => {
      let {
        value: money
      } = event.detail;
      const defaultValue = money === '';
      const diff = money.indexOf('.') !== -1;
      money = money.replace(/\s*/g, '');

      if (diff) {
        const diffLength = money.indexOf('.');

        if (money.slice(diffLength).length > 3) {
          return;
        }

        if (money.length > diffLength + 1 && money[money.length - 1] !== '0') {
          money = Number(money);
        } else if (money[money.length - 1] != 0) {
          money = `${Number(money)}.`;
        }
      } else {
        money = Number(money);
      }

      that.setData({
        money: defaultValue ? '' : money
      });
    }, 100),

    popOverClose() {
      // 关闭弹出框
      this.$page.$popModal.hidePopover();
    },

    /**
     * 选择住院人
    */
    choosePatient(info) {
      const {
        hospitalizationRecordList
      } = this.$page.$popModal.data;
      const selectIndex = hospitalizationRecordList.findIndex(item => info.inpatientId === item.inpatientId); // 获取用户id

      this.setData({
        jsonData: {
          Inpatient: info
        },
        inpatientId: info.inpatientId,
        selectIndex
      });
      this.$page.$popModal.hidePopover();
    },

    /**
     * 增加住院人
    */
    addPatient() {
      history.push({
        title: '添加住院人',
        pageType: 'add-inpatient-information',
        query: {
          color: '#000',
          backBtnColor: '#000',
          background: '#fff'
        }
      });
      this.$page.$popModal.hidePopover();
    },

    onAdmissionRegistration() {
      this.$page.$popModal.showPopover({
        title: '选择住院人',
        popupPosition: 'bottom',
        onButtonClose: () => this.popOverClose(),
        // 弹出框关闭
        onChoosePatient: info => this.choosePatient(info),
        // 选择就诊人
        onAddPatient: () => this.addPatient() // 添加就诊人

      });
    },

    // 订阅插件要用时，请放开注释
    requestSubscribeMessageFn(subscribeID) {
      const that = this;
      return new Promise(resolve => {
        this.requestSubscribeMessage({
          // 模板id列表，最多3个
          entityIds: [subscribeID],

          callback() {
            that.setTrade();
            resolve(true);
          }

        });
      });
    },

    // 支付前先要订阅
    async payMoney() {
      try {
        const subscribeID = await getsubscribeID();
        await this.requestSubscribeMessageFn(subscribeID.depositTemplateId);
      } catch (error) {
        console.log(error, 'error');
      }
    },

    // 支付弹窗
    async setTrade() {
      const {
        money,
        inpatientId
      } = this.data;

      try {
        if (money) {
          const {
            tradeNo: tradeNO,
            outTradeNo,
            depositId
          } = await settradePayRe({
            amount: money,
            inpatientId
          });
          my.tradePay({
            tradeNO,
            success: async res => {
              // 4000 订单处理失败
              // 6001 用途中途取消支付
              // 6002 网络链接出错
              if (res.resultCode === '4000' || res.resultCode === '6002' || res.resultCode === '6001') {
                // 支付失败
                my.showToast({
                  type: 'fail',
                  content: res.memo || '订单支付失败'
                });
              } else {
                // 其他情况调用接口确认
                const payRes = await tradeResult({
                  tradeNo: tradeNO,
                  outTradeNo,
                  resultCode: res.resultCode
                });

                if (payRes.status === 'TRADE_SUCCESS') {
                  history.push({
                    query: {
                      depositId,
                      color: '#000',
                      backBtnColor: '#000',
                      background: '#fff'
                    },
                    title: '押金缴纳详情',
                    pageType: 'pay-result'
                  });
                } else {
                  my.showToast({
                    type: 'fail',
                    content: res.memo || '订单支付失败'
                  });
                }
              }
            }
          });
        }
      } catch (error) {
        console.log(error, 'error');
      }
    }

  }
});