<template>
  <view class="submit-order">
    <!-- 自定义导航栏 -->
    <custom-navbar
      title="提交订单"
      :showBack="true"
      backgroundColor="#FFFFFF"
    ></custom-navbar>

    <!-- 地址信息 -->
    <view
      class="address-section"
      @click="goToAddress"
      v-if="service.server_kind == 1"
    >
      <image
        src="/static/images/gohome_location.png"
        class="positon-icon"
        mode="aspectFit"
      ></image>
      <text
        class="address-choice"
        v-if="!reservation_address.server_address || !reservation_address.is_ok"
        >请选择到家地址</text
      >
      <view class="address-info" v-else>
        <view class="user-info">
          <text class="name">{{ reservation_address.name }}</text>
          <text class="phone">{{ reservation_address.call_phone }}</text>
        </view>
        <view class="address"
          >{{ reservation_address.server_address
          }}{{ reservation_address.house_number }}
        </view>
      </view>
      <image
        src="/static/images/arrow_right.png"
        class="arrow-icon"
        mode="aspectFit"
      ></image>
    </view>

    <!--  v-if="service.server_kind==1" -->
    <view class="section-cont" v-if="service.server_kind == 1">
      <!-- 时间选择 -->
      <view class="time-section" @click="openTimePicker">
        <text class="time-label">到家时间</text>
        <view class="time-value">
          <text class="time">{{ selectedTime || '请选择时间' }}</text>
          <image
            src="/static/images/arrow_right.png"
            class="arrow-icon"
            mode="aspectFit"
          ></image>
        </view>
      </view>
      <!-- 师傅信息 -->
      <view class="master-section">
        <text class="master-name">{{
          service.server_kind == 1
            ? "手艺人"
            : service.server_kind == 2
            ? "店铺"
            : ""
        }}</text>
        <text class="master-info">{{ syrorsjInfo.name }}</text>
      </view>
    </view>

    <!-- 预约服务 -->
    <view class="service-section">
      <view class="section-title">
        <view class="icon"></view>
        <text class="section-lable">预约服务</text>
      </view>
      <view class="service-item" @click="goToDetail(service.id)">
        <image
          class="service-image"
          v-if="service.photo && service.photo.length != 0"
          :src="service.photo[0]"
          mode="aspectFill"
        ></image>
        <view class="service-info">
          <text class="service-name text-overflow">{{ service.title }}</text>
          <view class="service-count">
            <text class="count-lable">服务数量</text>
            <text class="count-num">x1</text>
          </view>
        </view>
      </view>
      <view class="price-info">
        <text class="price-label">原始价格:</text>
        <text class="price-value">¥{{ service.server_price }}</text>
      </view>
      <view class="total-price">
        <text class="total-label">订单小计:</text>
        <text class="total-value">¥{{ service.server_price }}</text>
      </view>
    </view>

    <!-- 备注 -->
    <!-- <view class="remark-section">
      <text class="remark-title">备注(选填)</text>
      <textarea 
        class="remark-input"
        v-model="remark"
        placeholder="请您输入需要备注的内容,如现场情况等"
        placeholder-class="placeholder"
      ></textarea>
    </view> -->

    <!-- 底部结算栏 -->
    <view class="footer">
      <view class="price-total">
        <text class="price">¥{{ service.server_price }}</text>
        <text class="amount-lable">订单小计</text>
      </view>
      <view class="submit-btn" @click="submitOrder">提交订单</view>
    </view>

    <!-- 时间选择弹框 -->
    <select-time-page
      ref="selecTime"
      :timeOptions="timeOptions"
      :service="service"
      @sureTime="sureTime"
      @closeTime="closeTime"
    ></select-time-page>
  </view>
</template>

<script>
import selectTimePage from "../../components/select-time-page/select-time-page.vue";
import customNavbar from "@/components/custom-navbar/custom-navbar.vue";
import { debounce } from "../../utils/debounce";
import request from "@/utils/request";

export default {
  components: {
    customNavbar,
    selectTimePage,
  },
  data() {
    return {
      serviceTimeNum:3,
      serviceId: "",
      syrorsjInfo: {}, // 手艺人或商家信息
      // 地址信息
      reservation_address: {},
      s1: "",
      s2: "",
      s3: "",
      selected_date: "",
      selected_time: "",
	  server_kind:null,
      // 时间信息
      selectedTime: null,
      dateList: ["今天", "明天", "后天"],
      timeOptions: [],
      selectedDateIndex: 0,
      selectedTimeIndex: 0,
      sureTimeDataIndex: 0,
      showTimePicker: false,
      // 服务信息
      service: {
        photo: [],
        server_kind: "",
        title: "",
        server_price: "",
      },
      // 备注
      remark: "",
      // 订单信息
      orderInfo: {
        originalPrice: 0.01,
        totalPrice: 0.01,
      },
      isSubmit: false,
      // 状态映射配置
      stateConfig: {
        1: {
          class: "state-available",
          text: "可约",
        },
        2: {
          class: "state-full",
          text: "约满",
        },
        3: {
          class: "state-rest",
          text: "休息",
        },
        4: {
          class: "state-locked",
          text: "锁定",
        },
        5: {
          class: "state-unavailable",
          text: "不可用",
        },
      },
    };
  },
  async onLoad(options) {
    try {
      if (options.id) {
        this.name = options.name;
        // 获取服务详情
        const serverdetail = await request.post("/user/serverdetail", {
          id: options.id,
        });
        if (serverdetail.state === 1) {
          this.service = serverdetail.data;
          if (this.service.server_time) {
            this.serviceTimeNum = Math.ceil(this.service.server_time / 10);
          }

          let url;
		  this.server_kind = serverdetail.data.server_kind
          if (serverdetail.data.server_kind == 1) {
            url = "/user/syrdetail";
          } else if (serverdetail.data.server_kind == 2) {
            url = "/user/sjdetail";
          }
          const syrorsjInfo = await request.post(url, {
            id: serverdetail.data.publish_user_id,
          });
          this.syrorsjInfo = syrorsjInfo.data;
          if (serverdetail.data.server_kind == 1) {
            //今天的时间
            let today = this.getDateStr(0);
            this.getyestimearrFirst(today, "today");
            await this.getDefaultAddress(options.id);
          }
        }
      }
    } catch (err) {
      console.log("报错", err);
    }
  },
  methods: {
    // 列表项的class获取方法
    getItemClass(state) {
      return this.stateConfig[state]?.class || "state-unknown";
    },
    // 获取默认地址
    getDefaultAddress(id) {
      request
        .post("/user/getdefaultaddress", {
          id,
        })
        .then((res) => {
          console.log("res============", res);
          if (res.data && res.data.is_ok) {
            this.reservation_address = res.data;
            this.reservation_address_id = res.data.id;
          }
        })
        .catch((err) => {
          console.log("err", err);
        });
    },
    // 进入时获取预约时间
    getyestimearrFirst(date, type) {
      let that = this;
      that.timeOptions = [];
      request
        .post("/user/reserve/timeList", {
          user_syr_id: this.service.publish_user_id,
        })
        .then(async (res) => {
          that.timeOptions = [
            ...that.timeOptions,
            res.data.today,
            res.data.tomorrow,
            res.data.after,
          ];
          let stateMap = {
            1: "可约",
            2: "约满",
            3: "休息",
            4: "锁定",
            5: "不可用",
          };
          that.timeOptions.forEach((item) => {
            item.forEach((ClipboardItem) => {
              ClipboardItem.stateName = stateMap[ClipboardItem.state];
            });
          });
          // //判断最早可预约时间
          // let today = res.data.today.find((item, index) => {
          //   that.selectedTime = `今天 ${res.data.today[index].show_time}`;
          //   that.selectedTimeIndex = index;
          //   that.selected_date = this.getDateStr(0);
          //   that.selected_time = item.show_time;
          //   return item.state === 1;
          // });
          // if (!today) {
          //   let tomorrow = res.data.tomorrow.find((item, index) => {
          //     that.selectedTime = `明天 ${res.data.today[index].show_time}`;
          //     that.selectedDateIndex = 1;
          //     that.selectedTimeIndex = index;
          //     that.selected_date = this.getDateStr(1);
          //     that.selected_time = item.show_time;
          //     return item.state === 1;
          //   });
          //   if (!tomorrow) {
          //     let after = res.data.after.find((item, index) => {
          //       that.selectedTime = `后天 ${res.data.today[index].show_time}`;
          //       that.selectedDateIndex = 2;
          //       that.selectedTimeIndex = index;
          //       that.selected_date = this.getDateStr(2);
          //       that.selected_time = item.show_time;
          //       return item.state === 1;
          //     });
          //   }
          // }
        })
        .catch((err) => {
          console.log("报错", err);
        });
    },
    // 获取预约时间
    async getyestimearr(date, type) {
      let that = this;
      that.timeOptions = [];
      await request
        .post("/user/reserve/timeList", {
          user_syr_id: this.service.publish_user_id,
        })
        .then((res) => {
          that.timeOptions = [
            ...that.timeOptions,
            res.data.today,
            res.data.tomorrow,
            res.data.after,
          ];
          let stateMap = {
            1: "可约",
            2: "约满",
            3: "休息",
            4: "锁定",
            5: "不可用",
          };
          that.timeOptions.forEach((item) => {
            item.forEach((ClipboardItem) => {
              ClipboardItem.stateName = stateMap[ClipboardItem.state];
            });
          });
        })
        .catch((err) => {
          console.log("报错", err);
        });
    },
    
    // 获取日期字符串
    getDateStr(days) {
      const date = new Date();
      date.setDate(date.getDate() + days);
      return `${date.getFullYear()}-${(date.getMonth() + 1)
        .toString()
        .padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}`;
    },

    goToDetail(id) {
      uni.navigateTo({
        url: "/pages/service/detail?id=" + id,
      });
    },
    // 打开时间选择弹框
    async openTimePicker() {
      console.log("打开时间选择弹框", this.selected_date);
      console.log(this.service)
      await this.getyestimearr(this.selected_date);
      this.$refs.selecTime.openTime();
    },
    // 确认时间
    sureTime(date) {
      console.log("选择时间", date);
      if (Object.keys(date).length) {
        this.selectedTime = `${this.dateList[date.selectedDateIndex]} ${
          date.time.show_time
        }`;
        this.selected_date = this.getDateStr(date.selectedDateIndex);
        this.selected_time = date.time.show_time;
        this.selectedTimeIndex = date.selectedTimeIndex;
        this.selectedDateIndex = date.selectedDateIndex;
      }
    },
    closeTime() {
      console.log("关闭时间选择弹框");
    },
    // 选择地址
    goToAddress() {
      //  uni.showToast({
      //  	title: "该内容暂未开通",
      // icon: 'none'
      //  })
      uni.navigateTo({
        url: "/pages/address/list?id=" + this.service.id,
      });
    },
    // 选择到家地址结果
    addReservation(item) {
      this.reservation_address_id = item.id;
      this.reservation_address = item;
    },
    // 提交订单
    submitOrder: debounce(async function () {

      if(this.selected_time.length == 0 && this.server_kind == 1){
         uni.showToast({
            title: `请选择时间`,
            icon: "none",
          });
          return
      }
      if (this.isSubmit) return;
      try {
        // 判断当前时间是否可用
        // const timeavailable = request.post('/user/servertimeavailable');
        uni.showLoading({
          title: "提交中...",
        });
        let orderData = {};
        if (this.service.server_kind == 1) {
          if (!this.reservation_address_id) {
            uni.showToast({
              title: "请选择到家地址",
              icon: "none",
            });
            return;
          }
          orderData = {
            server_id: this.service.id, // 测试ID
            server_title: this.service.title, // 测试ID
            server_type_first_id: this.service.first_class_id, // 测试ID
            server_type_secod_id: this.service.second_class_id, // 测试ID
            order_kind: this.service.server_kind, // 测试ID
            order_type: 3, // 测试ID
            order_money: this.service.server_price, // 测试ID
            reservation_time: `${this.selected_date} ${this.selected_time}:00`,
            reservation_address_id: this.reservation_address_id,
            remark: this.remark,
          };
        } else {
          orderData = {
            server_id: this.service.id, // 测试ID
            server_title: this.service.title, // 测试ID
            server_type_first_id: this.service.first_class_id, // 测试ID
            server_type_secod_id: this.service.second_class_id, // 测试ID
            order_kind: this.service.server_kind, // 测试ID
            order_type: 3, // 测试ID
            order_money: this.service.server_price, // 测试ID
            remark: this.remark,
          };
        }

        const res = await request.post("/user/creatorder", orderData);

        uni.hideLoading();

        if (res.state === 1) {
          uni.showToast({
            title: "提交成功",
            icon: "none",
            duration: 2000,
          });

          this.isSubmit = true;
          setTimeout(() => {
            uni.redirectTo({
              url: `/pages/order/pay?id=${res.data.id}&money=${this.service.server_price}&title=${this.service.title}&number=${res.data.number}`,
            });
          }, 500);
        } else {
          uni.showToast({
            title: res.msg || "提交失败",
            icon: "none",
          });
          this.isSubmit = false;
        }
      } catch (error) {
        uni.hideLoading();
        uni.showToast({
          title: "提交失败，请重试",
          icon: "none",
        });
        console.error("提交订单失败:", error);
        this.isSubmit = false;
      }
    }, 500),
  },
};
</script>

<style scoped lang="less">
.submit-order {
  padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
}

/* 地址信息 */
.address-section {
  background-color: #ffffff;
  padding: 32rpx 24rpx;
  margin: 32rpx 24rpx 0;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 16rpx 0 rgba(210, 213, 224, 0.5);
  display: flex;
  flex-flow: row nowrap;
  justify-content: center;
  align-items: center;
}

.address-choice,
.address-info {
  flex: 1;
}

.positon-icon {
  width: 60rpx;
  height: 60rpx;
  margin-right: 24rpx;
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 8rpx;
}

.name {
  font-size: 32rpx;
  color: #3d3d3d;
  font-weight: 500;
  margin-right: 24rpx;
}

.phone {
  font-size: 32rpx;
  color: #3d3d3d;
  font-weight: 500;
}

.address {
  font-size: 28rpx;
  color: #999999;
}

.section-cont {
  margin: 24rpx 24rpx 0;
  padding: 0 24rpx;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 16rpx 0 rgba(210, 213, 224, 0.5);
  background-color: #fff;
}

/* 时间选择 */
.time-section {
  padding: 32rpx 0;
  display: flex;
  flex-flow: row nowrap;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1rpx solid rgba(0, 0, 0, 0.05);
}

.time-label {
  font-size: 24rpx;
  color: #666666;
}

.time-value {
  display: flex;
  align-items: center;
}

.time {
  font-size: 24rpx;
  color: #333333;
  margin-right: 8rpx;
}

/* 师傅信息 */
.master-section {
  padding: 32rpx 0;
  display: flex;
  flex-flow: row nowrap;
  justify-content: space-between;
  align-items: center;
}

.master-name {
  font-size: 24rpx;
  color: #666666;
}

.master-info {
  font-size: 24rpx;
  color: #333333;
}

/* 预约服务 */
.service-section {
  background-color: #ffffff;
  padding: 0 24rpx;
  margin: 24rpx 24rpx 0;
  box-shadow: 0 4rpx 16rpx 0 rgba(210, 213, 224, 0.5);
  border-radius: 16rpx;
}

.section-title {
  padding: 24rpx 0;
  display: flex;
  flex-flow: row nowrap;
  justify-content: flex-start;
  align-items: center;
  border-bottom: 1rpx solid rgba(0, 0, 0, 0.05);
}

.icon {
  width: 6rpx;
  height: 28rpx;
  border: 3rpx;
  margin-right: 16rpx;
  background-color: #FF4767;
}

.service-item {
  padding-top: 24rpx;
  display: flex;
  flex-flow: row nowrap;
  justify-content: space-between;
  align-items: stretch;
  margin-bottom: 24rpx;
}

.section-lable {
  font-size: 28rpx;
  font-weight: 500;
  color: #3d3d3d;
}

.service-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 16rpx;
  margin-right: 24rpx;
  background-color: #e2e2e2;
}

.service-info {
  flex: 1;
  display: flex;
  flex-flow: column nowrap;
  justify-content: space-between;
  align-items: stretch;
}

.service-name {
  font-size: 28rpx;
  color: #3d3d3d;
  font-weight: 500;
}

.service-count {
  flex-shrink: 0;
  display: flex;
  flex-flow: row nowrap;
  justify-content: space-between;
  align-items: center;
}

.count-lable {
  font-size: 24rpx;
  color: #666666;
}

.count-num {
  font-size: 32rpx;
  color: #333333;
}

.price-info {
  margin-top: 32rpx;
  margin-bottom: 24rpx;
}

.total-price {
  padding-bottom: 32rpx;
}

.price-info,
.total-price {
  display: flex;
  flex-flow: row nowrap;
  justify-content: space-between;
  align-items: center;
}

.price-label,
.total-label {
  color: #666666;
  font-size: 24rpx;
}

.price-value,
.total-value {
  color: #333333;
  font-size: 24rpx;
  font-weight: 500;
}

/* 备注 */
.remark-section {
  background-color: #ffffff;
  padding: 32rpx 24rpx;
  margin: 24rpx;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 16rpx 0 rgba(210, 213, 224, 0.5);
}

.remark-title {
  font-size: 28rpx;
  color: #333333;
  margin-bottom: 24rpx;
  display: block;
}

.remark-input {
  width: 100%;
  height: 160rpx;
  font-size: 28rpx;
  color: #333333;
}

.placeholder {
  color: #999999;
  font-size: 28rpx;
}

/* 底部结算栏 */
.footer {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 150rpx;
  background-color: #ffffff;
  display: flex;
  flex-flow: row nowrap;
  justify-content: center;
  align-items: center;
  padding: 0 24rpx;
  padding-bottom: env(safe-area-inset-bottom);
}

.price-total {
  flex: 1;
  display: flex;
  flex-flow: column nowrap;
  justify-content: flex-start;
  align-items: flex-start;
}

.price-total .price {
  font-size: 28rpx;
  font-weight: 500;
  color: #FF4767;
}

.amount-lable {
  font-size: 24rpx;
  color: #999999;
}

.submit-btn {
  width: 492rpx;
  height: 64rpx;
  background: #FF4767;
  border-radius: 32rpx;
  color: #ffffff;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.arrow-icon {
  width: 32rpx;
  height: 32rpx;
}

/* 弹框遮罩 */
.popup {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 998;
}

.popup-mask {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

/* 时间选择弹框 */
.time-popup {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ffffff;
  border-radius: 24rpx 24rpx 0 0;
  overflow: hidden;
  padding-bottom: env(safe-area-inset-bottom);
  transform: translateY(0);
  transition: transform 0.3s;
  z-index: 999;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 30rpx 36rpx 30rpx;

  .popup-close {
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    font-size: 26rpx;
    color: #999999;
    line-height: 37rpx;
    text-align: left;
    font-style: normal;
  }

  .popup-title {
    font-family: PingFangSC, PingFang SC;
    font-weight: 500;
    font-size: 30rpx;
    color: #333333;
    line-height: 42rpx;
    text-align: left;
    font-style: normal;
  }
}

.time-picker-content {
  padding: 32rpx 32rpx;

  &__datas {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: space-between;

    &__date__item {
      width: 214rpx;
      height: 67rpx;
      background: #f7f8fa;
      border-radius: 10rpx;
      display: flex;
      align-items: center;
      justify-content: center;

      &__text {
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 26rpx;
        color: #333333;
        line-height: 37rpx;
        text-align: left;
        font-style: normal;
        position: relative;
        position: relative;
        z-index: 2;
      }

      &__text.active {
        color: #ffffff;
        background: transparent;
        background-position: bottom;
      }

      &__box {
        width: 214rpx;
        height: 74rpx;
        position: absolute;
        z-index: 1;
      }
    }
  }

  &__time__list {
    flex: 1;
    height: 600rpx;
    margin-top: 30rpx;

    ::-webkit-scrollbar {
      display: none;
    }

    uni-scroll-view .uni-scroll-view::-webkit-scrollbar {
      display: none;
    }

    ::v-deep .uni-scroll-view-content {
      display: flex;
      flex-wrap: wrap;
      justify-content: flex-start;
      -webkit-column-gap: 21rpx;
      column-gap: 21rpx;
      row-gap: 30rpx;
      max-height: 100%;
      height: auto;
    }

    &__item {
      box-sizing: border-box;
      width: 156rpx;
      height: 90rpx;
      background: #f7f8fa;
      border-radius: 10rpx;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 26rpx;
      color: #3c3638;
      line-height: 37rpx;
      text-align: left;
      font-style: normal;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      .__text {
      }

      .__state {
      }
    }

    .state-available {
      color: #3c3638;
      background: #f7f8fa;
      /* 可约 */
    }

    .state-full {
      color: #3c3638;
      background: #e4e9f0;
      /* 约满 */
    }

    .state-rest {
      color: #cdcdcd;
      background: #f7f8f9;
      /* 休息 */
    }

    .state-locked {
      color: #3c3638;
      background: #e4e9f0;
      /* 锁定 */
    }

    .state-unavailable {
      color: #ffffff;
      background: #e4e9f0;
      /* 不可用 */
    }

    .state-unknown {
      /* 未知状态 */
    }

    .isActive {
      background: rgba(252, 67, 124, 0.08);
      border-radius: 10rpx;
      border: 1rpx solid #FF4767;
      color: #FF4767;
      /* 选中状态 */
    }

    &__item.active {
      background-color: #fff0f0;
      color: #ff3e3e;
      font-weight: 500;
    }

    &__item.noselected {
      /* background-color: #FFF0F0; */
      color: #999999;
      font-weight: 500;
    }
  }

  &__time__sure {
    padding: 39rpx 0;
    display: flex;
    justify-content: center;

    &__box {
      width: 648rpx;
      height: 94rpx;
      background: linear-gradient(140deg, #fa4e9a 0%, #FF4767 100%);
      border-radius: 48rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 30rpx;
      color: #ffffff;
      line-height: 42rpx;
      text-align: left;
      font-style: normal;
    }
  }
}

/* 多端适配 */
/* #ifdef H5 */
.time-popup {
  max-height: 85vh;
}

/* #endif */

/* #ifdef APP-PLUS */
.time-popup {
  max-height: 90vh;
}

/* #endif */

/* #ifdef MP-WEIXIN */
.time-popup {
  max-height: 95vh;
}

/* #endif */
</style>
