<template>
  <view>
    <u-sticky>
      <scroll-view scroll-x="true" class="DatePicker">
        <view
          v-for="allowableDate in allowableDates"
          :key="allowableDate"
          :class="[
            'DatePickerItem',
            { 'is-active': $u.dayjs(allowableDate).isSame(date, 'day') },
          ]"
          @tap="handleChangeDate(allowableDate)"
        >
          <view :style="{ fontSize: '14px', textAlign: 'center' }">{{
            $u.dayjs(allowableDate).isToday()
              ? "今天"
              : $u.timeFormat(allowableDate, "[周]dd")
          }}</view>
          <view>{{ allowableDate | timeFormat("MM.DD") }}</view>
        </view>
      </scroll-view>
    </u-sticky>

    <view class="p-page">
      <view
        v-if="!loading && trains.length === 0"
        :style="{ textIndent: '2em' }"
      >
        <text class="text-content"
          >很抱歉，按您的查询条件，当前未找到从<text class="mx-ssm fw-bold">{{
            from
          }}</text
          >到<text class="mx-ssm fw-bold">{{ to }}</text
          >的列车。</text
        >
      </view>

      <view
        v-for="train in trains"
        :key="train.trainNo"
        class="page-box TrainItem p-base"
      >
        <u-row :gutter="12">
          <u-col :span="3">
            <view class="Time">{{
              train.query.fromTime | timeFormat("HH:mm")
            }}</view>
            <view class="Station">{{ train.query.from }}</view>
          </u-col>
          <u-col :span="3">
            <view class="text-center" :style="{ fontSize: '14px' }">
              <view>{{ train.trainNo }}</view>
              <u-line></u-line>
              <view>{{
                train.query.fromTime | timeDiff(train.query.toTime)
              }}</view>
            </view>
          </u-col>
          <u-col :span="3">
            <view class="Time text-end">{{
              train.query.toTime | timeFormat("HH:mm")
            }}</view>
            <view class="Station text-end">{{ train.query.to }}</view>
          </u-col>
          <u-col :span="3">
            <view class="u-flex-center ps-lg">
              <u-button
                type="primary"
                size="mini"
                @tap="handleToByTicket(train)"
                >预定</u-button
              >
            </view>
          </u-col>
        </u-row>
      </view>
    </view>
  </view>
</template>

<script>
import apiTrains from "@/api/trains.js";

export default {
  data() {
    return {
      allowableDates: [], // 顶部日期选择
      from: "", // 上车站
      to: "", // 下车站
      date: "", // 乘车日期
      trains: [], // 车次查询结果
      loading: false, // 加载中（用于判断是否显示空列表）
    };
  },
  computed: {
    queryTrainParams() {
      return {
        from: this.from,
        to: this.to,
        date: this.date,
      };
    },
  },
  watch: {
    queryTrainParams(val) {
      this.handleQueryTrain(val);
    },
  },
  onLoad(query) {
    const { from, to, date } = query;
    this.from = decodeURIComponent(from);
    this.to = decodeURIComponent(to);
    this.date = this.$u.dayjs(decodeURIComponent(date)).format();

    this.initAllowableDates();
  },
  onReady() {
    // 如果需要在页面进入时设置标题，可以在`onReady`内执行，以避免被框架内的修改所覆盖。
    uni.setNavigationBarTitle({ title: `${this.from} > ${this.to}` });
    uni.setNavigationBarColor({
      backgroundColor: "#3c9cff", // --color-primary
      frontColor: "#ffffff",
    });
  },
  methods: {
    initAllowableDates() {
      // 15 天购票日期
      for (let i = 0; i < 15; i += 1) {
        this.allowableDates.push(this.$u.dayjs().add(i, "day").format());
      }
    },
    handleChangeDate(date) {
      this.date = date;
    },
    handleQueryTrain(params) {
      // 有备无患
      if (!params || !params.from || !params.to || !params.date) {
        uni.switchTab({ url: "/pages/HomeView/HomeView" });
      }

      uni.showLoading({ title: "正在加载", mask: true });
      this.loading = true;

      apiTrains
        .get({
          from: params.from,
          to: params.to,
          date: params.date,
        })
        .then((res) => {
          this.trains = res.data.map((trn) => ({
            ...trn,
            query: this.formatTrainToQuery(trn, params.from, params.to),
          }));
        })
        .catch(() => {})
        .then(() => {
          uni.hideLoading();
          this.loading = false;
        });
    },
    handleToByTicket(train) {
      if (!this.$store.state.auth.id) {
        uni.navigateTo({ url: "/pages/LoginView/LoginView" });
        return;
      }

      uni.navigateTo({
        url: `/pages/BuyTicketView/BuyTicketView?train_no=${encodeURIComponent(
          train.trainNo
        )}&from=${encodeURIComponent(
          train.query.from
        )}&from_time=${encodeURIComponent(
          train.query.fromTime
        )}&to=${encodeURIComponent(
          train.query.to
        )}&to_time=${encodeURIComponent(
          train.query.toTime
        )}&date=${encodeURIComponent(this.date)}`,
      });
    },

    /**
     * 以三个参数获取车次查询需要的显示对象
     * @param {Object} train
     * @param {String} from 上车站（from_station)
     * @param {String} to 下车站（to_station）
     */
    formatTrainToQuery(train, from, to) {
      const stations = train.stations;
      const fromIndex = stations.findIndex((stn) => stn.name === from);
      const toIndex = stations.findIndex((stn) => stn.name === to);
      let price = 0;
      for (let i = fromIndex; i <= toIndex; i += 1) {
        price += stations[i].price;
      }

      return {
        from: from, // 上车站
        fromTime: stations[fromIndex].depTime, // 发车时间
        to: to, // 下车站
        toTime: stations[toIndex].arrTime, // 到站时间
      };
    },
  },
};
</script>

<style scoped lang="scss">
$date-picker-bg: $u-primary;
$date-picker-color: #ffffff;

.DatePicker {
  white-space: nowrap;
  padding: var(--space-sm) var(--space-base);
  background-color: $date-picker-bg;
  color: $date-picker-color;
}

.DatePickerItem + .DatePickerItem {
  margin-left: var(--space-sm);
}

.DatePickerItem {
  display: inline-block;
  padding: var(--space-ssm);
  border-radius: calc(var(--space-ssm) * 1.5);

  &.is-active {
    background-color: $date-picker-color;
    color: $date-picker-bg;
  }
}
</style>
