import { prefixPagePath, dynamicPageName } from "../../../../core/utils";
import getDay, { format as DateFormat } from '../../utils/getDay';
import fetchService from '../../utils/fetchService';
import parseToQueryString from '../../utils/parseToQueryString';
import { scenicOrderPay, scenicPurchaseInfo, scenicTicketReserve } from './../../services';
const threeDays = [getDay(0, '今天'), getDay(1, '明天'), getDay(2, '后天')];
Component({
  data: {
    loading: true,
    // 票面数据
    ticketInfo: {},
    // 选中某一天
    selectedDay: {},
    // 今天、明天、后天的数据
    threeDayList: [],
    // 日历数据
    calendarList: [],
    // 日历库存数据
    calendarTags: [],
    // 选中某一天下标
    selectedDateIndex: -1,
    // 时间段
    timeInterval: [],
    // 选中的时间段
    timeIntervalIndex: -1,
    // 票单价
    singlePrice: 0,
    // 票的数量
    ticketNum: 0,
    // 最大购买数量
    maxBuyNum: 0,
    // 禁用日期
    disableDates: [],
    // 选中的日期
    selectedDate: '',
    // 预订须知
    purchaseInfo: null,
    touristList: []
  },
  props: {},

  async didMount() {
    await this.fetchThreeDay();
  },

  methods: {
    /*
    * 数据更新
    * */
    updateState(state) {
      const func = resolve => {
        this.setData(state, resolve);
      };

      return new Promise(func);
    },

    getProductId() {
      const {
        options
      } = this.$page;
      const {
        productId
      } = options;
      return productId;
    },

    /*
    * 获取预订须知
    * */
    async getPurchaseInfo() {
      return scenicPurchaseInfo({
        id: this.getProductId()
      });
    },

    /*
    * 根据日期查询某一天的具体数据
    * */
    getInfoByDate(_date, list) {
      const {
        calendarList = []
      } = this.data;
      return (list || calendarList).find(({
        date
      }) => _date === date);
    },

    /* 加载三天的数据 */
    async fetchThreeDay() {
      let result = {};
      const params = {
        productId: this.getProductId()
      };

      try {
        result = await fetchService(scenicTicketReserve, params);
      } catch (e) {
        return false;
      }

      const {
        inventoryList = []
      } = result;
      await this.updateState({
        calendarList: inventoryList
      });
      const threeDay = threeDays.map(item => ({ ...item,
        ...this.getInfoByDate(item.date)
      }));
      const updateState = {
        loading: false,
        ticketInfo: result,
        threeDayList: threeDay
      };
      await this.updateState(updateState);
    },

    /* 将日期列表转为对象 */
    transformDataForMap(list = [], map = {}) {
      list.forEach(item => map[item.date] = item);
      return map;
    },

    /* 加载某月的数据 */
    async fetchListByDate(date, dates) {
      let result = {};
      const disabledDays = [];
      const params = {
        date,
        productId: this.getProductId()
      };

      try {
        result = await fetchService(scenicTicketReserve, params);
      } catch (e) {
        return false;
      }

      const {
        inventoryList = []
      } = result;
      const daysMap = this.transformDataForMap(inventoryList);
      /*
      * 更新一下数据
      * */

      await this.updateState({
        calendarList: inventoryList
      });
      /*
      * 这里筛选出需要禁用的日期
      * */

      dates.forEach(day => {
        const {
          stock = 0,
          date: _date
        } = daysMap[day] || {};
        if (!_date || !+stock) disabledDays.push(day);
      });
      await this.updateState({
        disableDates: disabledDays,
        calendarTags: this.getCalendarTags(inventoryList)
      });
    },

    /*
    * 日历数据
    * */
    getCalendarTags(list = []) {
      const filterList = list.filter(({
        stock
      }) => !!+stock);
      return filterList.map(({
        stock,
        date
      }) => ({
        date,
        text: `余${+stock === -1 ? '999+' : stock}`
      }));
    },

    async onDateChange(index) {
      const {
        threeDayList
      } = this.data;
      const {
        date,
        stock = 0,
        sellPrice = 0,
        hoursList = []
      } = threeDayList[index] || {};

      const _hoursList = hoursList || [];

      const curTimeStamp = Date.now();
      /*
      * 超过时间不允许选择
      * */

      _hoursList.forEach(item => {
        const {
          endTime
        } = item;
        const endTimeStamp = new Date(`${DateFormat(date)} ${endTime}`).getTime();
        item.disabled = curTimeStamp > endTimeStamp;
      });

      let updateData = {
        ticketNum: 0,
        selectedDate: date,
        timeIntervalIndex: -1,
        singlePrice: sellPrice,
        timeInterval: _hoursList,
        selectedDateIndex: index
      };
      /*
      * 如果当前日期没有时段则为全时段
      * */

      if (!_hoursList.length) {
        updateData = { ...updateData,
          ticketNum: 1,
          maxBuyNum: +stock,
          timeIntervalIndex: 0
        };
      }

      await this.updateState(updateData);
    },

    async onTimeIntervalChange(index) {
      const {
        timeInterval
      } = this.data;
      const {
        stock = 0
      } = timeInterval[index] || {};
      await this.updateState({
        ticketNum: 1,
        maxBuyNum: +stock,
        timeIntervalIndex: index
      });
    },

    async onCountHandle({
      val
    }) {
      await this.updateState({
        ticketNum: val
      });
    },

    /* 打开日历 */
    async onOpenCalendar(date, dates) {
      my.showLoading({
        content: '加载中..'
      });
      await this.fetchListByDate(date, dates);
      my.hideLoading();
    },

    /* 点击日历日期 */
    async onTapDate(res) {
      const {
        lunar,
        date,
        month,
        fulldate
      } = res;
      let updateData = {};
      /*
      * 检查三天中有没有这个日期
      * */

      const {
        threeDayList = []
      } = this.data;
      const index = threeDayList.findIndex(({
        date: _date
      }) => _date === fulldate);

      if (index > -1) {
        await this.onDateChange(index);
      } else {
        threeDayList[2] = {
          date: fulldate,
          showName: `周${lunar.ncWeek.substr(lunar.ncWeek.length - 1)}`,
          showDate: [month, date].join('-'),
          ...this.getInfoByDate(fulldate)
        };
        updateData = {
          threeDayList
        };
        await this.updateState(updateData);
        await this.onDateChange(2);
      }
    },

    async onTouristChange(list) {
      await this.updateState({
        touristList: list
      });
    },

    /*
    * 获取选择的时间
    * */
    getSelectDate() {
      const {
        threeDayList,
        selectedDateIndex
      } = this.data;
      return threeDayList[selectedDateIndex] || {};
    },

    /*
    * 获取时间段
    * */
    getTimeRange() {
      const {
        timeInterval,
        timeIntervalIndex
      } = this.data;
      return timeInterval[timeIntervalIndex] || {};
    },

    /*
    * 获取游客列表信息
    * */
    getTouristList() {
      const {
        touristList = []
      } = this.data;
      return touristList.map(item => {
        return {
          id: item.id,
          touristName: item.name,
          certType: item.certType,
          idCardNo: item.idCardNo,
          touristMobile: item.mobile
        };
      });
    },

    /*
    * 获取游客Id
    * */
    getTouristIds() {
      const list = this.getTouristList();
      return list.map(item => item.id);
    },

    /*
    * 打开授权
    * */
    openAuth() {
      return new Promise(resolve => {
        const scopes = ['scenic_order_auth'];
        const extInfo = {
          bizType: 'LIFE_APP',
          bizId: '2021002112693576'
        };
        my.getAuthCode({
          scopes,
          extInfo,
          complete: resolve
        });
      });
    },

    /*
    * 下单
    * */
    async onSubmit({
      currentTarget
    }) {
      const {
        value: disabled
      } = currentTarget.dataset;
      if (disabled) return false;
      const {
        singlePrice,
        ticketInfo,
        ticketNum: quantity
      } = this.data;
      const touristIds = this.getTouristIds();

      if (!touristIds.length) {
        return my.showToast({
          content: '请至少选择一名旅客'
        });
      }

      if (touristIds.length > quantity) {
        return my.showToast({
          content: '游客数量不能大于票的数量'
        });
      }

      const {
        endTime: hoursEndTime,
        startTime: hoursStartTime,
        id: hoursStockId
      } = this.getTimeRange();
      const {
        date: playDate,
        id: inventoryId
      } = this.getSelectDate();
      const {
        productId
      } = ticketInfo;
      const params = {
        quantity,
        playDate,
        hoursEndTime,
        hoursStartTime,
        inventoryId,
        hoursStockId,
        productId,
        touristList: JSON.stringify(touristIds),
        amount: (quantity * singlePrice).toFixed(2)
      };
      await this.openAuth();
      my.showLoading({
        content: '下单中..'
      });

      try {
        const {
          tradeNo = '',
          orderId = '',
          needPay = false
        } = await fetchService(scenicOrderPay, params);

        if (!needPay) {
          my.hideLoading();
          return this.toOrderDetail(orderId);
        }

        my.tradePay({
          tradeNO: tradeNo,
          complete: () => {
            this.toOrderDetail(orderId);
          }
        });
      } catch (e) {
        my.alert({
          title: '提示',
          content: e.msg || '下单失败',
          buttonText: '我知道了'
        });
      }

      my.hideLoading();
    },

    toOrderDetail(orderId) {
      const pageCode = 'scenicOrderDetail';
      const params = {
        orderId,
        pageCode
      };
      my.redirectTo({
        url: `${prefixPagePath}/${dynamicPageName}/index${parseToQueryString(params)}`
      });
    }

  }
});