import { dynamicPageName, prefixPagePath } from "../../../../core/utils";
import { orderDetail, cancelOrder } from './service';
import { cuttingDate } from '../../utils';
import history from '../../utils/history';
import { tradePay } from '../../utils/tradePay';
import { reportApi } from '../../utils/cloudMonitorHelper';
Component({
  props: {},
  data: {
    result: {
      id: '',
      // 就诊人id
      status: -1,
      // 预约状态 0-待支付 1-已支付（预约成功）2-排队中 7-已就诊 8-过期未就诊  9-已取消
      date: '',
      // 2022-09-20
      day: '',
      // 周一
      am: '',
      // 上午
      time: '' // 00:00

    },
    countown: '0',
    modalOpened: false,
    buttons: [{
      text: '不，先留着'
    }, {
      text: '取消预约',
      extClass: 'buttonBold'
    }],
    viewItem: [{
      label: '就诊日期',
      key: 'date'
    }, {
      label: '就诊时间',
      key: 'time'
    }, {
      label: '就诊医院',
      key: 'districtName'
    }, {
      label: '就诊科室',
      key: 'depName'
    }, {
      label: '就诊人',
      key: 'name'
    }, {
      label: '预约医生',
      key: 'doctor'
    }, {
      label: '挂号费用',
      key: 'price'
    }, {
      label: '就诊卡',
      key: 'card'
    }],
    refund: ['https://gw.alipayobjects.com/mdn/rms_373ab8/afts/img/A*03IPSKd3OmkAAAAAAAAAAAAAARQnAQ', 'https://gw.alipayobjects.com/mdn/rms_373ab8/afts/img/A*03IPSKd3OmkAAAAAAAAAAAAAARQnAQ']
  },

  didMount() {
    const {
      query
    } = this.$page.data;
    this.orderDetail();
    const {
      where
    } = query || {};

    if (where === 'order-pay') {
      /* 服务办结,预约挂号 */
      reportApi('预约挂号');
    }
  },

  didUnmount() {
    if (this.timer) {
      clearTimeout(this.timer);
    }
  },

  methods: {
    saveRef(ref) {
      this.subscribe = ref;
    },

    orderDetail() {
      const {
        query = {
          orderId: ''
        }
      } = this.$page.data;
      const {
        where
      } = query;
      my.showLoading();
      orderDetail({
        orderId: query.orderId
      }).then(data => {
        this.setData({
          result: Object.assign(data, cuttingDate(data.startTime))
        });
        const {
          status,
          expireTime = '',
          systemTime = ''
        } = this.data.result;

        if (status === 0) {
          const now = new Date(systemTime.replace(/-/g, '/')).getTime();
          const start = new Date(expireTime.replace(/-/g, '/')).getTime();

          if (!this.timeEndFlag) {
            this.doTimeout(start - now, () => {
              this.orderDetail();
              this.timeEndFlag = true;
            });
          }
        } else if (status === 1) {
          /* 如果是从下单页面过来的，拉起消息授权 */
          if (where === 'order-pay') {
            this.grantSubscribe();
          }
        }

        my.hideLoading();
      });
    },

    // 打开取消预约弹出
    onCancel() {
      this.setData({
        modalOpened: true
      });
    },

    // 确认取消预约
    onButtonClick(e) {
      this.setData({
        modalOpened: false
      });

      if (e.target.dataset.index === 1) {
        const {
          query = {
            orderId: ''
          }
        } = this.$page.data;
        cancelOrder({
          orderId: query.orderId,
          reason: ''
        }).then(() => {
          this.orderDetail();
        });
      }
    },

    // 再次预约
    reAppoint() {
      my.navigateTo({
        url: `${prefixPagePath}/${dynamicPageName}/index?pageCode=hospital-new-select-area`
      });
    },

    toH5(e) {
      const {
        url
      } = e.target.dataset;
      history.toH5(url);
    },

    hrefTo() {
      my.ap.navigateToAlipayPage({
        path: 'alipays://platformapi/startapp?appId=77700284&page=pages/medical/index?chInfo=YY_xiaochengxu'
      });
    },

    // 消息订阅授权
    grantSubscribe() {
      this.subscribe.subscribeMessage();
    },

    // 发起倒计时
    doTimeout(val, cb = () => {}) {
      if (val > 0) {
        const timeout = 200;
        val -= timeout;
        this.timer = setTimeout(() => {
          this.doTimeout(val, cb);
        }, timeout);
      } else {
        val = 0;
        cb();
      }

      const second = Math.floor(val / 1000);
      const h = Math.floor(second / 3600);
      const m = Math.floor(second % 3600 / 60);
      const s = second % 60;
      this.setData({
        countown: `${h > 0 ? `${h}:` : ''}${h > 0 || m > 0 ? `${`0${m}`.slice(-2)}:` : ''}${h > 0 || m > 0 || s > 0 ? `0${s}`.slice(-2) : '0'}`
      });
    },

    // onPay
    onPay() {
      tradePay({
        type: 1,
        idNum: this.data.result.orderId,
        depName: this.data.result.depName
      }, {
        tradeType: 'Appointment'
      }).then(() => {
        this.orderDetail(); // 支付成功之后发起消息订阅授权

        this.subscribe.subscribeMessage();
      });
      /* 服务办结，挂号缴费 */

      reportApi('挂号缴费');
    },

    toBackHome() {
      const len = getCurrentPages().length;
      my.navigateBack({
        delta: len + 1
      });
    }

  }
});