import { connect } from 'herculex';
import { makeAppointment } from './service';
import { cuttingDate } from '../../utils';
import { tradePay } from '../../utils/tradePay';
import history from '../../utils/history';
Component(connect({
  mapStateToProps: {
    userInfo: state => state.$global.userInfo
  }
})({
  props: {
    componentData: {}
  },
  data: {
    onlinePay: false,
    // 无需支付
    order: {},
    orderList: [{
      key: 'depName',
      label: '就诊科室'
    }, {
      key: 'doctorName',
      label: '预约医生'
    }, {
      key: 'timeRange',
      label: '就诊日期'
    }, {
      key: 'startTime',
      label: '就诊时间'
    }, {
      key: 'districtName',
      label: '就诊医院'
    }],
    checkedPatient: {},
    inProgress: false,
    // 预约中
    showPatient: false
  },

  didMount() {
    this.orderDetail(Object.assign({
      depName: '',
      doctorName: '',
      doctorId: '',
      orderSourceId: '',
      bindCardNum: '',
      startTime: '',
      queueNum: 0,
      amount: 0,
      payType: '就诊时支付',
      level: '',
      districtName: '',
      onlinePay: true
    }, this.$page.data.query));
  },

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

    // 默认选中就诊人
    onChange(checkedPatient) {
      this.setData({
        checkedPatient
      });
    },

    // 打开就诊人列表
    choosePatient() {
      this.setData({
        showPatient: true
      });
    },

    // 关闭就诊人列表
    onClose() {
      this.setData({
        showPatient: false
      });
    },

    // 确认预约
    async onSubmit() {
      if (this.data.checkedPatient.name) {
        makeAppointment({
          doctorId: this.data.order.doctorId,
          orderSourceId: this.data.order.orderSourceId,
          cardNum: this.data.checkedPatient.bindCardNum
        }).then(data => {
          if (this.data.onlinePay) {
            tradePay({
              type: 1,
              idNum: data.orderId,
              depName: this.data.order.depName
            }, {
              tradeType: 'Appointment'
            }).then(() => {
              this.toDetail(data.orderId); // 支付成功以后，唤起消息订阅

              this.subscribe.subscribeMessage();
            });
          } else {
            this.toDetail(data.orderId);
          }
        });
      } else {
        this.choosePatient();
      }
    },

    // 配置预约单详情
    orderDetail(data) {
      this.setData({
        order: Object.assign(data, cuttingDate(data.startTime)),
        onlinePay: data.onlinePay === 'true'
      });
    },

    // 跳转到预约详情
    toDetail(orderId) {
      history.push({
        title: '预约详情',
        query: {
          orderId,
          where: 'order-pay'
        },
        pageType: 'appointment-result'
      });
    }

  }
}));