<template>
  <view class="detail-page">
    <!-- 顶部导航栏 -->
    <custom-navbar
      title="订单详情"
      :show-back="true"
      title-color="#333333"
      :backgroundColor="backgroundColor"
    ></custom-navbar>
    <view class="content-part">
      <!-- 订单状态 -->
      <view class="status-section">
        <image class="status-section-image" mode="widthFix" :src="stateItem.icon" />
        <text class="status-text">{{ stateItem.text }}</text>
      </view>

      <!-- 预约信息 -->
      <view class="booking-card">
        <view class="card_title">预约信息</view>
        <view class="service-item">
          <image
            :src="orderInfo.photo[0]"
            v-if="orderInfo.photo && orderInfo.photo.length != 0"
            mode="aspectFill"
            class="service-image"
          ></image>
          <view class="service-info">
            <view class="service-box">
              <text class="service-name white-space-nowrap">{{
                orderInfo.title
              }}</text>
              <text class="service-subtitle white-space-nowrap"
                >服务范围：{{
                  orderInfo.first_class_title +
                  "   " +
                  orderInfo.second_class_title.join("、")
                }}</text
              >
            </view>
            <view class="service-price">
              <text>单价：{{ orderInfo.price }}元/10分钟</text>
            </view>
          </view>
        </view>
        <view class="service-real">
          <view class="card_time"
            >预约开始时间：{{
              formatDateAndAddMinutes(orderInfo.reserve_start_time).original
            }}
          </view>
          <view class="card_time"
            >预约结束时间：{{
              formatDateAndAddMinutes(orderInfo.reserve_end_time).original
            }}
          </view>
        </view>
      </view>
      <!-- 订单信息 -->
      <view class="order-card">
        <view class="card_title">订单信息</view>
        <view class="info-item">
          <text class="label">订单编号</text>
          <text class="value">{{ orderInfo.number }}</text>
        </view>
        <view class="info-item">
          <text class="label">下单时间</text>
          <text class="value">{{ orderInfo.add_time }}</text>
        </view>
        <view class="info-item" v-if="orderInfo.state != 1">
          <text class="label">支付方式</text>
          <text class="value">{{
            orderInfo.pay_kind == 1
              ? "账户余额"
              : orderInfo.pay_kind == 2
              ? "微信支付"
              : orderInfo.pay_kind == 3
              ? "支付宝支付"
              : ""
          }}</text>
        </view>
        <view class="info-item" v-if="orderInfo.state != 1">
          <text class="label">支付小计</text>
          <text class="value" style="color: #E8101E"
            >{{ orderInfo.order_money }}元</text
          >
        </view>
        <view class="info-item" v-if="orderInfo.state != 1">
          <text class="label">支付时间</text>
          <text class="value">{{ orderInfo.pay_time }}</text>
        </view>
      </view>
      <!-- 到家订单 客户以及手艺人信息 -->
      <view class="shop_card">
        <view class="card_title">店铺信息</view>
        <view class="shop_title_box">
          <image class="shop_photo" :src="orderInfo.head_photo" />
          <view class="shop_title">{{ orderInfo.name }}</view>
        </view>
        <view class="service_content"
          >服务范围详情：{{
            orderInfo.first_class_title +
            "   " +
            orderInfo.second_class_title.join("、")
          }}</view
        >
        <view class="shop_address">
          <image
            class="shop_icon"
            src="@/static/images/icons/address_gray.png"
          />
          <text>{{ orderInfo.dependency }}{{ orderInfo.address }}</text>
        </view>
        <view class="shop_address mt_10">
          <image class="shop_icon" src="@/static/images/icons/phone_gray.png" />
          <text>{{ orderInfo.phone }}</text>
        </view>
      </view>
    </view>

    <!-- 底部按钮 -->
    <view class="bottom-buttons">
      <view
        class="handel-button btn-border"
        v-if="orderInfo.state == 2 || orderInfo.state == 3"
        @click.stop="cancelOrder($event, orderInfo)"
      >
        <text class="button-text">取消订单</text>
      </view>
      <view
        class="handel-button btn-bg"
        v-if="orderInfo.state == 2"
        @click.stop="confirmOrder($event, orderInfo)"
      >
        <text class="button-text">接单</text>
      </view>
      <view
        class="handel-button btn-bg"
        v-if="orderInfo.state == 3"
        @click.stop="startOrder($event, orderInfo)"
      >
        <text class="button-text">开始服务</text>
      </view>
      <view
        class="handel-button btn-bg"
        v-if="orderInfo.state == 4"
        @click.stop="endOrder($event, orderInfo)"
      >
        <text class="button-text">服务完成</text>
      </view>
    </view>

    <serviceCodeInput
      :show="showInput"
      @close="showInput = false"
      @confirm="onConfirm"
    />

    <!-- 获取权限提示匡内容 -->
    <view class="permission" :class="{ transform: isShowPer }">
      <view class="per-tit">美融融plus 对拨打电话权限申请说明</view>
      <view class="per-cont"
        >当您需要联系商家或平台客服的时候，需要获取拨打电话权限。</view
      >
    </view>
  </view>
</template>

<script>

import request from "../../utils/request";
import _public from "../../utils/public";
import serviceCodeInput from "../../components/service-code-input/service-code-input.vue";
import locationService from "../../utils/locationService";
import permissionUtils from "../../utils/per";
export default {
  components: { serviceCodeInput },
  data() {
    return {
      isShowPer: false,
      id: "",
      staffInfo: {
        avatar: "/static/images/staff.jpg",
        name: "中医理疗谢飞",
        rating: 5,
      },
      showInput: false,
      userInfo: {},
      orderInfo: {},
      reservation_address_arr: {},
      user_syr: {},
      scrollTop: 0,
    };
  },
  async onLoad(options) {
    this.id = options.id;
    if (options.id) {
      // 请求订单详情
      const { data } = await request.post("/user/getuser", { type: 2 });
      this.userInfo = data;
      this.getOrderDetail();
    }
  },
  onPageScroll(e) {
    this.scrollTop = e.scrollTop;
  },
  computed: {
    backgroundColor() {
      if (this.scrollTop > 10) {
        return `rgba(255, 255, 255, ${0.02 * this.scrollTop});`;
      }
      return "transparent";
    },
    stateItem() {
      const list = [
        { text: "待支付", icon: "/static/images/icons/pay.png", state: "1" },
        {
          text: "待接单",
          icon: "/static/images/icons/pending.png",
          state: "2",
        },
        {
          text: "待服务",
          icon: "/static/images/icons/pendingService.png",
          state: "3",
        },
        {
          text: "服务中",
          icon: "/static/images/icons/pendingService.png",
          state: "4",
        },
        { text: "已完成", icon: "/static/images/icons/payOk.png", state: "5" },
        {
          text: "待评价",
          icon: "/static/images/icons/pending.png",
          state: "6",
        },
        { text: "已取消", icon: "/static/images/evaluate/cancel.png", state: "7" },
      ];
      const item = list.find((it) => it.state == this.orderInfo.state) || {};
      return item;
    },
    photo() {
      return JSON.parse(this.orderInfo.photo);
    },
  },
  methods: {
    formatDateAndAddMinutes(dateStr, addMinutes = 0) {
		if(!dateStr){
		        return {
		        original: '',
		        afterAddingMinutes: '',
		        };
		      }
      const originalDate = new Date(dateStr.replace(/-/g,'/'));
      function format(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        const hours = String(date.getHours()).padStart(2, "0");
        const minutes = String(date.getMinutes()).padStart(2, "0");
        return `${year}年${month}月${day}日 ${hours}:${minutes}`;
      }
      const formattedOriginal = format(originalDate);
      const newDate = new Date(originalDate);
      newDate.setMinutes(newDate.getMinutes() + addMinutes);
      const formattedNew = format(newDate);
      return {
        original: formattedOriginal,
        afterAddingMinutes: formattedNew,
      };
    },
    getOrderDetail() {
      const res = {
        code: 200,
        msg: "success!",
        data: {
          order: {
            id: 1,
            number: "GS2025072817001653692514",
            add_time: "2025-07-28 17:00:16",
            pay_kind: 2,
            order_money: "10.99",
            pay_money: "0.00",
            pay_time: "2025-07-28 15:40:00",
            work_hour_id: 1,
            reserve_start_time: "2025-07-28 15:30:00",
            reserve_end_time: "2025-07-28 15:40:00",
            state: 2,
            order_userid: "10",
          },
          work_hour: {
            id: 1,
            title: "快洗、漂染",
            first_class_id: 18,
            second_class_ids: "81,82",
            price: "10.99",
            user_syr_id: 24,
            photo: JSON.stringify([
              "https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/syr/24_syr_1749636052644.jpg",
            ]),
            first_class_title: "美发",
            second_class_title: ["快洗", "漂染"],
          },
          user_sj: {
            id: 1,
            head_photo:
              "https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/sj/38_sj_1749647806565.jpg",
            name: "美业协会",
            phone: "18102036346",
            dependency: "河北省-沧州市-黄骅市",
            address: "恬恬夏雪(黄骅建设大街海银店)",
            longitude: "117.335718",
            latitude: "38.365762",
          },
        },
      };
      this.orderInfo = res.data
        ? {
            ...res.data.order,
            ...res.data.work_hour,
            ...res.data.user_sj,
            work_hour_id: res.data.work_hour.id,
            order_id: res.data.order.id,
            user_sj_id: res.data.user_sj.id,
          }
        : {};
    },
    cancelOrder(e, order) {
      // #ifdef APP-PLUS
      e.preventDefault();
      e.stopPropagation();
      // #endif
      uni.showModal({
        title: "取消订单",
        content: "确定要取消该订单吗？（订单取消后，支付金额将原路退回）",
        success: (res) => {
          if (res.confirm) {
            let data = {
              orderNo: order.number,
              amount: order.pay_money,
              syrid: this.userInfo.id,
            };
            let url = "";
            if (order.pay_kind == 1) {
              url = "";
            } else if (order.pay_kind == 2) {
              url = "/syr/yhwechatrefund";
            } else if (order.pay_kind == 3) {
              url = "/syr/yhalirefund";
            }
            request
              .post(url, data)
              .then((res) => {
                if (res.state == 1  || res.code == 1  || res.code == 200) {
                  uni.showToast({ title: "取消成功！", icon: "none" });
                  this.getOrderDetail();
                  const pages = getCurrentPages();
                  const prevPage = pages[pages.length - 2];
                  if (prevPage) {
                    prevPage.$vm.getOrderNumber();
                    prevPage.$vm.getOrderList();
                  }
                } else {
                  uni.showToast({ title: res.msg, icon: "none" });
                }
              })
              .catch((err) => console.log(err));
          }
        },
      });
    },
    confirmOrder(e, order) {
      // #ifdef APP-PLUS
      e.preventDefault();
      e.stopPropagation();
      // #endif
      request
        .post("/syr/yhordersure", { id: order.id, syrid: this.userInfo.id })
        .then((res) => {
          uni.showToast({ title: "已接单", icon: "none" });
          this.getOrderDetail();
          const pages = getCurrentPages();
          const prevPage = pages[pages.length - 2];
          if (prevPage) {
            prevPage.$vm.getOrderNumber();
            prevPage.$vm.getOrderList();
          }
        });
    },
    startOrder(e, order) {
      // #ifdef APP-PLUS
      e.preventDefault();
      e.stopPropagation();
      // #endif
      this.showInput = true;
    },
    onConfirm(code) {
      this.showInput = false;
      request
        .post("/syr/yhstartserver", {
          id: this.orderInfo.id,
          server_code: code,
          syrid: this.userInfo.id,
        })
        .then((res) => {
          if (res.state == 1) {
            uni.showToast({ title: res.msg, icon: "none" });
            this.getOrderDetail();
            const pages = getCurrentPages();
            const prevPage = pages[pages.length - 2];
            if (prevPage) {
              prevPage.$vm.getOrderNumber();
              prevPage.$vm.getOrderList();
            }
          } else if (res.state == 2) {
            uni.showToast({ title: res.msg, icon: "none" });
          }
          this.handelOrder = {};
        });
    },
    endOrder(e, order) {
      // #ifdef APP-PLUS
      e.preventDefault();
      e.stopPropagation();
      // #endif
      request.post("/syr/yhendserver", { id: order.id }).then((res) => {
        if (res.code == 200) {
          uni.showToast({ title: res.msg, icon: "none" });
          this.getOrderDetail();
          const pages = getCurrentPages();
          const prevPage = pages[pages.length - 2];
          if (prevPage) {
            prevPage.$vm.getOrderNumber();
            prevPage.$vm.getOrderList();
          }
        }
      });
    },
    showPermissionDialog(title, content) {
      return new Promise((resolve) => {
        uni.showModal({
          title,
          content,
          confirmText: "去开启",
          success(res) {
            resolve(res.confirm);
          },
        });
      });
    },
    async contactService(phone) {
      const systemInfo = uni.getSystemInfoSync();
      if (systemInfo.platform === "ios") {
        uni.makePhoneCall({ phoneNumber: phone });
      } else {
        let permission =
          systemInfo.platform === "ios"
            ? "phone"
            : "android.permission.CALL_PHONE";
        this.isShowPer = true;
        const firstRequest = !plus.storage.getItem(`perm_${permission}`);
        if (firstRequest) this.isShowPer = true;
        const { granted } = await permissionUtils.checkPermission(
          "phone",
          "需要拨打电话权限，方便您联系商家或平台"
        );
        if (granted) {
          this.isShowPer = false;
          uni.makePhoneCall({ phoneNumber: phone });
          return;
        }
        this.isShowPer = false;
        const confirm = await this.showPermissionDialog(
          "拨打电话权限申请",
          "我们需要拨打电话权限，方便您联系商家或平台"
        );
        if (!confirm) return;
        const result = await permissionUtils.requestPermission(
          "phone",
          "需要拨打电话权限，方便您联系商家或平台"
        );
        if (result) {
          uni.makePhoneCall({ phoneNumber: phone });
        } else {
          locationService.openAppSettings();
        }
      }
    },
    openMap() {
      // #ifdef MP-WEIXIN
      uni.openLocation({
        success: () => console.log("打开系统位置地图成功"),
        fail: (error) => console.log(error),
      });
      // #endif
      // #ifdef APP-PLUS
      _public.goMap({
        latitude: parseFloat(this.reservation_address_arr.latitude),
        longitude: parseFloat(this.reservation_address_arr.longitude),
        name: this.reservation_address_arr.house_number,
        address: this.reservation_address_arr.server_address,
      });
      // #endif
    },
  },
};
</script>

<style lang="less">
page {
  position: relative;
  background-color: #fff;
}
.detail-page::before {
  content: "";
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 1200rpx !important;
  background-image: url("/static/images/bg.png");
  background-size: cover;
  background-position: center top;
  background-repeat: no-repeat;
  z-index: 1;
}
.content-part {
  position: relative;
  left: 0;
  right: 0;
  z-index: 9;
}

/* 状态区域 */
.status-section {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 20rpx;
  padding-top: 55rpx;
  padding-bottom: 50rpx;
  .status-section-image {
    width: 52rpx;
  }
}
.status-text {
  font-size: 44rpx;
  color: #333333;
  font-weight: 600;
}

/* 预约信息卡片 */
.booking-card {
  margin: 0rpx 30rpx 20rpx;
  background-color: #ffffff;
  border-radius: 20rpx;
  padding: 34rpx 30rpx 40rpx 20rpx;
  box-shadow: 0 4rpx 16rpx 0 rgba(210, 213, 224, 0.5);
  .card_title {
    font-weight: 500;
    font-size: 32rpx;
    color: #333333;
    margin-bottom: 40rpx;
  }
}
.service-item {
  display: flex;
  flex-flow: row nowrap;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 32rpx;
}
.service-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 16rpx;
  margin-right: 24rpx;
  background-color: #e2e2e2;
}
.service-info {
  flex: 1;
  height: 160rpx;
  display: flex;
  flex-flow: column nowrap;
  justify-content: space-between;
  align-items: flex-start;
  margin-right: 24rpx;
  .service-box {
    width: 100%;
    gap: 18rpx;
    display: flex;
    flex-direction: column;
    .service-subtitle {
      font-size: 26rpx;
      color: #666666;
    }
  }
}
.service-name {
  font-size: 30rpx;
  line-height: 30rpx;
  font-weight: 500;
  color: #333333;
}
.service-price {
  font-size: 26rpx;
  color: #333333;
}
.service-real {
  display: flex;
  flex-direction: column;
  padding-top: 24rpx;
  border-top: 1rpx solid rgba(0, 0, 0, 0.05);
}
.card_time {
  font-size: 28rpx;
  color: #666666;
  margin-top: 8rpx;
}

/* 订单信息卡片 */
.order-card {
  margin: 30rpx;
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 36rpx 20rpx 40rpx;
  box-shadow: 0 4rpx 16rpx 0 rgba(210, 213, 224, 0.5);
  .card_title {
    font-weight: 500;
    font-size: 32rpx;
    color: #333333;
    padding-bottom: 10rpx;
  }
}
.shop_card {
  margin: 30rpx;
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 36rpx 20rpx 40rpx;
  box-shadow: 0 4rpx 16rpx 0 rgba(210, 213, 224, 0.5);
  .card_title {
    font-weight: 500;
    font-size: 32rpx;
    color: #333333;
  }
  .shop_title_box {
    display: flex;
    align-items: center;
    gap: 14rpx;
    padding-top: 40rpx;
    padding-bottom: 24rpx;
    border-bottom: 2rpx solid #f6f5f5;
    .shop_photo {
      width: 94rpx;
      height: 94rpx;
      border-radius: 10rpx;
    }
    .shop_title {
      font-size: 32rpx;
      color: #333333;
    }
  }
  .service_content {
    padding-top: 30rpx;
    padding-bottom: 60rpx;
    font-size: 28rpx;
    color: #666666;
  }
  .shop_address {
    display: flex;
    gap: 10rpx;
    color: #666666;
    font-size: 26rpx;
    .shop_icon {
      width: 30rpx;
      height: 30rpx;
      flex-shrink: 0;
      transform: translateY(4rpx);
    }
  }
}
.info-item {
  display: flex;
  justify-content: space-between;
  margin-top: 30rpx;
}
.label {
  font-size: 28rpx;
  color: #999999;
}
.value {
  font-size: 28rpx;
  color: #333333;
}

/* 底部按钮 */
.bottom-buttons {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 128rpx;
  background-color: #ffffff;
  display: flex;
  flex-flow: row nowrap;
  align-items: center;
  justify-content: flex-end;
  box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.05);
  padding: 0 24rpx 0 78rpx;
  /* #ifdef H5 */
  padding-bottom: env(safe-area-inset-bottom);
  /* #endif */
  z-index: 999;
}
.handel-button {
  width: 186rpx;
  height: 72rpx;
  display: flex;
  flex-flow: row nowrap;
  justify-content: center;
  align-items: center;
  border-radius: 36rpx;
  margin-left: 60rpx;
}
.btn-border {
  border: 1rpx solid #E8101E;
  background-color: #fff;
  box-sizing: border-box;
  margin-left: 60rpx;
}
.btn-bg {
  background-color: #E8101E;
}
.button-text {
  font-size: 28rpx;
  font-weight: 400;
  color: #ffffff;
}
.btn-border .button-text {
  font-size: 28rpx;
  font-weight: 400;
  color: #E8101E;
}

/* 权限提示 */
/* #ifdef APP-PLUS */
.permission.transform {
  top: calc(var(--status-bar-height) + 88rpx + 20rpx);
  opacity: 1;
  visibility: visible;
}
.detail-page {
  padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
}
/* #endif */
/* #ifdef H5 */
.detail-page {
  padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
}
/* #endif */

.mt_10 {
  margin-top: 10rpx;
}
</style>
