import { doctorInfo, doctorOrderSourceList } from './service';
import * as utils from '../../utils';
Component({
  props: {},
  data: {
    doctor: {
      doctorId: '',
      name: '',
      picUrl: '',
      level: '',
      description: '',
      specialty: '',
      departments: []
    },
    days: [],
    startTime: '',
    endTime: '',
    showIntro: false,
    showRange: false,
    rangeItem: {},
    routeState: {}
  },

  didMount() {
    const d = new Date();
    const startTime = d.toLocaleDateString().replace(/\//g, '-');
    d.setDate(d.getDate() + 7);
    const endTime = d.toLocaleDateString().replace(/\//g, '-');
    this.setData({
      startTime,
      endTime
    });
    const {
      query = {
        depId: '',
        doctorId: ''
      }
    } = this.$page.data;
    this.init(query);
  },

  methods: {
    init(query) {
      my.showLoading();
      Promise.all([doctorInfo({
        doctorId: query.doctorId
      }).then(res => {
        this.setData({
          doctor: res
        });
      }), doctorOrderSourceList({
        depId: query.depId,
        doctorId: query.doctorId,
        startTime: this.data.startTime,
        endTime: this.data.endTime
      }).then(res => {
        const days = [];
        res.forEach(item => {
          const {
            date
          } = utils.cuttingDate(item.startTime);
          const temp = days.find(m => m.date === date);

          if (temp) {
            temp.orderSources.push(item);
          } else {
            days.push({
              date,
              today: date === utils.cuttingDate().date,
              orderSources: [item]
            });
          }
        });
        this.setData({
          days
        });
      })]).then(() => {
        my.hideLoading();
      });
    },

    // 查看更多
    showIntro() {
      this.setData({
        showIntro: true
      });
    },

    onClose() {
      this.setData({
        showIntro: false
      });
    },

    // 跳转预约
    onAppointment({
      target
    }) {
      const {
        query = {
          depId: ''
        }
      } = this.$page.data;
      const {
        doctor
      } = this.data;
      const depName = (doctor.departments.find(m => m.departmentId === query.depId) || {
        name: ''
      }).name;
      const routeState = {
        query: {
          level: doctor.level,
          depName,
          doctorId: doctor.doctorId,
          doctorName: doctor.name,
          queueNum: '',
          payType: '就诊时支付',
          districtName: doctor.districtName
        },
        title: '挂号确认',
        pageType: 'order-pay'
      };
      this.setData({
        showRange: true,
        rangeItem: target.dataset.row,
        routeState
      });
    },

    onTimeRangeClose() {
      this.setData({
        showRange: false
      });
    }

  }
});