import { getPriceDetails, settlementAuth, settlementExecute, configInfo } from './service';
import history from '../../utils/history';
import { tradeResult } from '../../service/common'; // js策略设计模式

const setObjectMap = {
  // 统一处理格式
  doexist(label, value, index) {
    return {
      label,
      value,
      index
    };
  },

  // 已缴押金格式处理
  depositTotalAmount(detail) {
    return this.doexist('已缴押金', `￥${detail}`, 0);
  },

  // 费用支出格式处理
  spendTotalAmount(detail) {
    return this.doexist('费用实际支出', `-￥${detail}`, 1);
  },

  // 应补缴金额格式处理
  repayAmount(detail) {
    return this.doexist('应补缴金额', `￥${detail}`, 2);
  },

  // 押金余额格式处理
  depositBalance(detail) {
    return this.doexist('押金余额', `￥${detail}`, 2);
  },

  // 医保报销格式处理
  reimbursableAmount(detail) {
    return this.doexist('医保报销', `￥${detail}`, 3);
  }

};
Component({
  data: {
    details: null,
    inpatientId: '',
    // 住院id
    medicareAble: '',
    // 是否是医保结算
    repay: false,
    // 是否唤起支付弹窗
    buttons: [{
      text: '取消'
    }, {
      text: '去结算',
      extClass: 'buttonBold'
    }],
    // 弹窗按钮配置
    showModal: false,
    completed: false,
    logo: 'https://gw.alipayobjects.com/mdn/rms_8ed4a1/afts/img/A*SctSR5ZZwrcAAAAAAAAAAAAAARQnAQ'
  },

  didMount() {
    // 获取参数住院IDhospitalDistrictId
    const optionsValue = JSON.parse(JSON.stringify(this.$page.data.query));
    const {
      inpatientId,
      hospitalDistrictId
    } = optionsValue;
    this.setData({
      inpatientId
    }, async () => {
      // 获取住院人结算详情
      this.getDeails(); // 院区配置信息 [新增]

      const detailInfos = await configInfo({
        hospitalDistrictId
      });
      this.setData({
        detailInfos: detailInfos.configInfo
      });
    });
    this.initAnimation();
  },

  methods: {
    initAnimation() {
      const animation = my.createAnimation({
        duration: 10000,
        timingFunction: 'linear' // 匀速

      });
      animation.translateX(parseInt(-400)).step();
      this.setData({
        animationData: animation.export(),
        // 此处为动画
        animation // 此处为方法

      });
      setTimeout(() => {
        this.animationend();
      }, 10500);
    },

    animationend() {
      const animation = my.createAnimation({
        duration: 0,
        timingFunction: 'linear'
      });
      animation.translateX(0).step();
      this.setData({
        animationData: animation.export()
      });
      setTimeout(() => {
        this.initAnimation();
      }, 200);
    },

    async getDeails() {
      const {
        inpatientId
      } = this.data;
      const authCode = await this.getAuthCodeFn();

      try {
        const details = await getPriceDetails({
          inpatientId,
          authCode
        });
        let priceArrs = [];

        if (details) {
          Object.keys(details).forEach(item => {
            if (item === 'refundAmount' && Number(details[item]) !== 0 || item === 'repayAmount' && Number(details[item]) !== 0) {
              if (item === 'repayAmount') {
                // repayAmount应补缴金额需要唤起支付功能.refundAmount应退款金额
                this.setData({
                  repay: true
                });
              } else {
                this.setData({
                  repay: false
                });
              }

              details.headerTitle = {
                label: item === 'refundAmount' ? '应退金额' : '应补缴金额',
                value: `${details[item]}`
              };
            }

            if (Number(details[item]) === 0) {
              Reflect.deleteProperty(details, item);
            } else if (setObjectMap[item]) {
              priceArrs.push(setObjectMap[item](details[item]));
              Reflect.deleteProperty(details, item);
            }
          });
          priceArrs = priceArrs.sort((a, b) => a.index - b.index);
          details.priceArrs = priceArrs;
          this.setData({
            details,
            medicareAble: !!details.medicareAble,
            completed: true
          });
        }
      } catch (error) {
        console.log(error, 'error');
      }
    },

    getAuthCodeFn() {
      return new Promise(resolve => {
        my.getAuthCode({
          scopes: 'auth_user',
          success: res => {
            resolve(res.authCode);
          }
        });
      });
    },

    navigateToAlipayPageFn(path) {
      return new Promise(resolve => {
        // 跳转H5页面
        my.ap.navigateToAlipayPage({
          path,
          success: () => {
            resolve(true);
          },
          fail: () => {
            resolve(false);
          }
        });
      });
    },

    async onModalClick(e) {
      const {
        inpatientId
      } = this.data;
      const {
        index
      } = e.currentTarget.dataset;

      if (index === 1) {
        // 结算成功跳转结算成功页面
        // 跳转类型 notSupportMedicalRefund - 不支持医保，预结算-退款
        const settlementType = 'notSupportMedicalRefund';
        history.push({
          query: {
            settlementType,
            inpatientId
          },
          title: '出院结算',
          pageType: 'discharge-settlement'
        }); // my.navigateTo({
        //   url: `/pages/discharge-settlement/index?settlementType=notSupportMedicalRefund&inpatientId=${inpatientId}`
        // });
      }

      this.setData({
        showModal: false
      });
    },

    showToast(msg, type = 'success') {
      my.showToast({
        type,
        content: msg,
        duration: 1500
      });
    },

    async goSettlement() {
      const {
        inpatientId,
        medicareAble,
        repay
      } = this.data; // @ts-ignore
      // const { appId: parentAppId } = my.getParentAppIdSync();
      // @ts-ignore

      const {
        appId
      } = my.getAppIdSync();

      try {
        const authCode = await this.getAuthCodeFn();
        const callUrl = `alipays://platformapi/startapp?appId=${appId}&page=/pages/discharge-settlement-detail/index?medicareAble=${medicareAble}&inpatientId=${inpatientId}&repay=${repay}`;

        if (medicareAble) {
          // 支持医保结算
          const details = await settlementAuth({
            authCode,
            callUrl
          });

          if (details.needAuth) {
            // 医保支付需要授权
            this.navigateToAlipayPageFn(details.authUrl); // 判断授权成功进入预结算页面callUrl
          } else {
            // 不需要授权跳转预结算页面
            history.push({
              query: {
                settlementType: 'supportMedicalPreSettlement',
                inpatientId,
                payAuthNo: details.payAuthNo,
                // 医保支付授权编码
                medicareAble,
                repay,
                color: '#000',
                backBtnColor: '#000',
                background: '#fff'
              },
              title: '出院结算',
              pageType: 'pre-settlement'
            });
          }
        } else if (repay) {
          // 不支持支持医保补缴直接需唤起支付功能 支付成功跳转详情
          const detail = await settlementExecute({
            inpatientId,
            useMedicare: medicareAble
          });

          if (detail.tradeNo) {
            // 需要自费补缴时tradeNo
            my.tradePay({
              tradeNO: detail.tradeNo,
              success: async res => {
                // // 支付成功跳转结算成功页面
                // if (res.resultCode === '9000') {
                //   // 跳转类型 notSupportMedicalSupplementary - 不支持医保，预结算-自费补缴
                //   const settlementType = 'notSupportMedicalSupplementary';
                //   history.push({
                //     query: {
                //       settlementType,
                //       inpatientId,
                //       color: '#000',
                //       backBtnColor: '#000',
                //       background: '#fff',
                //     },
                //     title: '出院结算',
                //     pageType: 'discharge-settlement',
                //   });
                // }
                // 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: detail.tradeNo,
                    resultCode: res.resultCode
                  });

                  if (payRes.status === 'TRADE_SUCCESS') {
                    // 跳转类型 notSupportMedicalSupplementary - 不支持医保，预结算-自费补缴
                    const settlementType = 'notSupportMedicalSupplementary';
                    history.push({
                      query: {
                        settlementType,
                        inpatientId,
                        color: '#000',
                        backBtnColor: '#000',
                        background: '#fff'
                      },
                      title: '出院结算',
                      pageType: 'discharge-settlement'
                    });
                  } else {
                    my.showToast({
                      type: 'fail',
                      content: res.memo || '订单支付失败'
                    });
                  }
                }
              }
            });
          }
        } else {
          // 不支持支持医保且退款需二次提醒
          this.setData({
            showModal: true
          });
        }
      } catch (error) {
        console.log(error, 'error');
      }
    }

  }
});