<template>
  <view style="width:100%;height: 100%">
    <view class="shopping-wrapper">
      <view class="list-item display-flex-content-center mt10">
        <image
            :src="courseInfo.cover"
            class="course-image"
        ></image>
        <view class="list-item-content ml15">
          <view class="list-item-content-title mb6">
            {{ courseInfo.goods_name }}
          </view>
          <view class="list-item-content-read display-flex">
            <text class="fw700 color-333  fs11 ">￥
              <text class="fw700 color-333  fs16 mb8">{{ courseInfo.price_selling }}</text>
            </text>
          </view>
        </view>
      </view>
      <view class="display-flex mt15 mb10" v-if="orderTimeFalg&&courseInfo.status!=9">
        <view class="tubiao mr10">
        </view>
        <view class="title">
          到店时间
        </view>
      </view>
      <view class="list-item  mt10" v-if="orderTimeFalg&&courseInfo.status!=9">
        <view class="display-flex-between" style="width: 100%">
          <view  class="display-flex-common">
            <view v-for="(date, index) in futureDates" :key="index"  @click="SetWeekSelect(date)" :class="[date.datetime==order_date?'list-item-week-Selected' :'list-item-week' ,'mr10','flex-center-column']"  >
              <view class="fs12 lh18 mb5r" style="display: block">
                {{ date.time}}
              </view>
              <view class="fs14 lh16" style="display: block">
                {{ date.week}}
              </view>
            </view>
          </view>
          <view @click="show=true" style="width: 100%;height: 112rpx;" class="display-flex-end">
            <u-icon name="arrow-right" bold color="#333333" size="14"  ></u-icon>
          </view>
        </view>
        <u-divider ></u-divider>
        <view class="display-flex" style="width: 100%;">
          <view v-for="(date, index) in yvyueData" :key="index" :style="[ date.date+' '+date.time==dateTimeSelect? { border: '1rpx solid #ca9359',width: '193rpx',height: '70rpx' }:{} ]"  @click="SetDateTimeSelect(date)"   :class="[getDateTimeSelectClass(date),'list-item-date-text'
        ,index<3?'':'mt15'
        ,(index+1)%3==0?'':'mr10','flex-center-column']"  >
            <view class="fs12 lh16 " style="display: block">
              {{ date.time+"~"+date.period_end }}
            </view>
            <view class="fs12 lh16 " style="display: block">
              ({{ date.remark}})
            </view>
          </view>
        </view>
      </view>
      <view class="display-flex mt15 mb10">
        <view class="tubiao mr10">
        </view>
        <view class="title">
          预约信息
        </view>
      </view>
      <view class="list-item">
        <view class="display-flex-between" v-if="!orderTimeFalg||courseInfo.status==9" >
          <text class="left-title">预约时间</text>
          <view class="h-view">
            {{form.order_date+" "+form.order_time}}
          </view>
        </view>
        <u-divider  v-if="!orderTimeFalg||courseInfo.status==9"></u-divider>
        <view class="display-flex-between" v-if="!orderTimeFalg||courseInfo.status==9" >
          <text class="left-title">预约状态</text>
          <view class="h-view">
            {{statusDisplay}}
          </view>
        </view>
        <u-divider  v-if="!orderTimeFalg||courseInfo.status==9"></u-divider>
        <view class="display-flex-between" >
          <text class="left-title">预约人</text>
          <view class="h-view">
            <u-input v-model="form.user_name" placeholder="请输入预约人" border="none" inputAlign="right" :auto-height="true"
                     />
          </view>
        </view>
        <u-divider  ></u-divider>
        <view class="display-flex-between" >
          <text class="left-title">联系方式</text>
          <view class="h-view" >
            <u-input type="number" v-model="form.user_phone" placeholder="请输入联系方式" border="none" :auto-height="true"
                     inputAlign="right"  />
          </view>
        </view>
        <u-divider  ></u-divider>
        <view class="display-flex-between" >
          <text class="left-title">人数</text>
          <view class="h-view">
            <u-number-box v-if="type=='add'" min="1"
                          :max="10" v-model="form.order_num"
                          @change="numChange" button-size="24">
              <view
                  slot="minus"
                  class="minus"
              >
                <u-icon
                    name="minus"
                    size="12"
                ></u-icon>
              </view>
              <text
                  slot="input"
                  style="width: 48rpx;text-align: center;line-height: 48rpx;font-size: 24rpx"
                  class="input"
              >{{form.order_num}}</text>
              <view
                  slot="plus"
                  class="plus"
              >
                <u-icon
                    name="plus"
                    size="12"
                ></u-icon>
              </view>
            </u-number-box>
            <view v-else>
              {{form.order_num}}
            </view>
          </view>
        </view>
        <u-divider  ></u-divider>
        <view class="display-flex-between" >
          <text class="left-title">备注</text>
          <view class="h-view">
            <u-input v-model="form.order_remark" placeholder="请输入您的要求" border="none" :auto-height="true"
                     inputAlign="right"  />
          </view>
        </view>
      </view>
      <u-calendar :formatter="formatter" :defaultDate="order_date" :show="show"  :show-title="false"  mode="single" @confirm="confirm" monthNum="4" color="#E2B98E" @close="close"></u-calendar>
    </view>
    <view class="bottom-navigation" v-if="orderTimeFalg&&courseInfo.status!=9">
      <button  v-if="type=='add'" class="activity-button"   @click="onsubmit()">立即报名</button>
      <view  v-if="type=='set'"  class="activity-button"  :style="{background:'#F9F2E6',color:'#C29556',border: '1rpx solid #F9F2E6' ,width: '336rpx',margin:'0rpx 9rpx'}" @click="yvyueOrderCancel()">取消预约订单</view>
      <view  v-if="type=='set'"  class="activity-button" :style="{width: '336rpx' ,margin:'0rpx 9rpx'}" @click="setyvyueOrder()">修改预约信息</view>
    </view>
  </view>


</template>

<script>
import {getGoodsDetail} from "../../common/api";
import {
  CreateItem,
  getYvyueOrderList,
  itemTimes,
  yvyueOrderCancel,
  getYvyueOrderInfo, updateItem
} from "../../common/api/yvyeService"
var  yvyueOrderList={}
export default {
  components: {},
  data() {
    return {
      page: 1,
      pageSize: 10,
      goods_code: 0,
      courseInfo: {},
      orderTimeFalg:false,
      futureDates: [],
      yvyueData: [],
      yvyueOrderList: {},
      form:{
        order_num:1
      },
      orderId:0,
      setid:null,
      show:false,
      status:"",
      order_date: "",
      dateTimeSelect: "",
      now_date: "",
      type:"add"
    };
  },

  onLoad: function (option) {
    this.goods_code = option.code
    if ( option.setid){
      this.type="set"
      this.setid =option.setid
    }
  },
  onShow() {


    this.getCourseDetail()
    if (this.setid ){
      this.orderId=this.setid
      getYvyueOrderInfo({id: this.orderId}). then(({data}) => {
        this.orderInfo = data
        // 获取今天的日期
        const today = new Date(); // 当前日期时间
        today.setHours(0, 0, 0, 0); // 清除时间部分，只保留日期
        if (data.order_date >= today.toISOString().split('T')[0]) {
          this.orderTimeFalg = true;
          this.getFutureDates(data.order_date)
          this.getitemTimes()
          this.getYvyueOrderList()
        } else {

          this.orderTimeFalg = false;
        }
        this.status = data.status
        this.order_date=data.order_date
        this.dateTimeSelect = data.order_date+" "+data.order_time
        this.form.order_time = data.order_time
        this.form.order_date = data.order_date
        this.form.user_name = data.user_name
        this.form.user_phone = data.user_phone
        this.form.order_num = data.order_num
        this.form.order_remark = data.order_remark
        this.form.customer_id = data.customer_id
        this.form.id = data.id
        this.form.tech_uid = data.tech_uid
        this.setid=null

      });
    }else{
      this.getFutureDates()
      this.getitemTimes()
      this.getYvyueOrderList()
      this.dateTimeSelect=""
      this.form={
        order_num:1
      }
    }




  },
  created() {
    const configs = uni.getStorageSync("configs");
    if (configs) {
      this.store_name = configs.store_name
      this.phoneNumber = configs.store_phone
      this.store_position = configs.store_position
      this.business_hours = configs.business_hours
      this.latlng = configs.latlng
    }
  },
  computed: {
    statusDisplay() {
      switch (this.status) {
        case -1:
          return '已违约'
        case -2:
          return '已取消'
        case 0:
          return '预订单'
        case 1:
          return '待支付'
        case 2:
          return '支付中'
        case 3:
          return '已支付'
        case 4:
          return '已签到'
        case 9:
          return '已完成'
        default:
          return ''
      }
    },
  },
  watch: {},
  methods: {
    numChange(item) {
      const {
        name,
        value
      } = item

    },
    verifyData(){
      if (!this.form.order_time){
        return {msg:"请选择预约时间",status:true}
      }
      if (!this.form.user_name){
        return {msg:"请输入预约人名称",status:true}
      }
      if (!this.form.user_phone){
        return {msg:"请输入联系方式",status:true}
      }
      if (!this.form.order_num){

        return {msg:"请输入预约人数",status:true}
      }
      if (!this.form.order_remark){
        return {msg:"请输入你的要求",status:true}
      }
      return false;
    },
    setyvyueOrder() {
      this.form.goods_code=this.goods_code;
      this.form.order_date=this.order_date;
      this.form.order_time=this.order_time;
      let verifyData1 = this.verifyData();
      if (verifyData1){
        uni.showToast({
          title:verifyData1.msg,
          icon: 'none'
        })
      }
      updateItem(this.form).then(({data})=>{
        yvyueOrderList[data.order_date][data.order_time].order_num=this.form.order_num
        yvyueOrderList[data.order_date][data.order_time].user_name=this.form.user_name
        yvyueOrderList[data.order_date][data.order_time].user_phone=this.form.user_phone
        yvyueOrderList[data.order_date][data.order_time].order_date=this.form.order_date
        yvyueOrderList[data.order_date][data.order_time].order_remark=this.form.order_remark
        uni.showToast({
          title:"修改成功",
          icon: 'none'
        })
      })
    },
    forceReload() {
      // 强制组件重新渲染
      this.$forceUpdate();
    },
    SetWeekSelect(item) {
      this.order_date = item.datetime
      this.getitemTimes()
    },
    formatter(day) {
      const year = day.date.getFullYear();
      let month = day.date.getMonth() + 1; // 月份+1
      let date = day.date.getDate();
      month=  month>10?month:'0'+month;
      date= date>10?date:'0'+date;
      const dateStr = `${year}-${month}-${date}`;
      // 2. 有效数据检查
      if (!yvyueOrderList) return day;
      if (yvyueOrderList[dateStr]){
        day.bottomInfo = '有预约';
        day.dot = true;
      }
      return day;
    },
    yvyueOrderCancel() {
      yvyueOrderCancel({id: this.orderId}).then(({data}) => {
        uni.showToast({
          title:"取消成功",
          icon: 'none'
        })
      });
      // 重新刷新页面
      uni.redirectTo({
        url: '/subPages/service/serviceSave?code=' + this.goods_code
      });
      //

    },
    getDateTimeSelectClass(date){
      if (date.date+' '+date.time==this.dateTimeSelect || yvyueOrderList[date.date] &&yvyueOrderList[date.date][date.period_start]){
        return 'list-item-date-Selected';
      }
      return date.num==0?'list-item-date-prohibit' :'list-item-date'
    },
    onsubmit(){
      this.form.goods_code=this.goods_code;
      this.form.order_date=this.order_date;
      this.form.order_time=this.order_time;
      let verifyData1 = this.verifyData();
      if (verifyData1){
        uni.showToast({
          title:verifyData1.msg,
          icon: 'none'
        })
      }
      CreateItem(this.form).then(({data})=>{
        uni.navigateTo({
          url: `/subPages/service/settlement?code=${this.goods_code}&orderId=${data.id}`
        })
      })
    },
    SetDateTimeSelect(item) {
      if (item.num==0){
        uni.showToast({
          title:"该时间段无法选择",
          icon: 'none'
        })
        return
      }
      if ( this.dateTimeSelect == item.date+" "+item.time){
        this.dateTimeSelect=""
        this.order_time=""
      }else {
        this.dateTimeSelect = item.date+" "+item.time
        this.order_time=item.period_start
      }
      if (!yvyueOrderList[item.date]){
        yvyueOrderList[item.date]={}
      }
      if (yvyueOrderList[item.date]&&yvyueOrderList[item.date][item.period_start]){
        this.type="set"
        this.getYvyueOrderInfo(yvyueOrderList[item.date][item.period_start])
      }else {
        if (this.type=="set"){
          this.form={order_num:1};
        }
        this.orderId=0
        this.type="add"
      }
    },
    getYvyueOrderInfo(item) {
      this.orderId=item.id
      this.form.order_time = item.order_time
      this.form.user_name = item.user_name
      this.form.user_phone = item.user_phone
      this.form.order_num = item.order_num
      this.form.order_remark = item.order_remark
      this.form.customer_id = item.customer_id
      this.form.id = item.id
      this.form.tech_uid = item.tech_uid
    },
    getitemTimes(){
      this.yvyueData=[]
      itemTimes({goods_code: this.goods_code, order_date: this.order_date}).then(({data}) => {
        data.times.forEach(item => {
          this.yvyueData.push({
            time: item.period_start,
            period_end: item.period_end,
            period_start: item.period_start,
            date: this.order_date,
            remark: item.remark,
            num: item.num,
          })
        });
      });
    },
    getYvyueOrderList(){
      yvyueOrderList= {}
      getYvyueOrderList({order_date: this.now_date}).then(({data}) => {
        if (data&&data.list) {
          data.list.forEach(item => {
              if (item.status ==1||item.status ==2||item.status ==9 ){
                if (!yvyueOrderList[item.order_date]){
                yvyueOrderList[item.order_date]={}
                }
                yvyueOrderList[item.order_date][item.order_time]=item
              }
          })
          console.log(yvyueOrderList)
          this. forceReload()
        }
      });

    },
    confirm(e) {
      this.order_date = e[0];
      let num =0
      for (let i = 0; i < this.futureDates.length; i++) {
        if (this.futureDates[i].datetime == e[0]) {
          num++
        }
      }
      if (num == 0){
       this. getFutureDates(this.order_date)
      }
      this.getitemTimes()
      this.show = false
    },
    close(){
      this.show = false
    },
    getCourseDetail() {
      getGoodsDetail({goods_code: this.goods_code}).then(({data}) => {
        this.courseInfo = data.goods
      });
    },
    // 获取未来五天的日期
    getFutureDates(startDateStr = null) {
      const today = startDateStr ? new Date(startDateStr) : new Date();
      this.futureDates = []; // 清空数组
      for (let i = 0; i < 5; i++) {
        let data = {};
        data.date = new Date(today);
        data.date.setDate(today.getDate() + i);
        this.formatDate(data); // 格式化日期并存储
      }
    },
// 格式化日期，返回“今天”、“明天”、“后天”或具体日期，并存储 time 和 week
    formatDate(data) {
      const today = new Date();
      const tomorrow = new Date(today);
      tomorrow.setDate(today.getDate() + 1);
      const dayAfterTomorrow = new Date(today);
      dayAfterTomorrow.setDate(today.getDate() + 2);

      // 格式化 datetime 为 YYYY-MM-DD
      const year = data.date.getFullYear();
      const month = String(data.date.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，需要加 1
      const day = String(data.date.getDate()).padStart(2, '0');
      data.datetime = `${year}-${month}-${day}`;
      if (!this.order_date){
        this.order_date= `${year}-${month}-${day}`;
        this.now_date= `${year}-${month}-${day}`;
      }
      if (data.date.toDateString() === today.toDateString()) {
        data.time = "今天";
        data.week = "周" + "日一二三四五六".charAt(new Date().getDay());
      } else if (data.date.toDateString() === tomorrow.toDateString()) {
        data.time = "明天";
        data.week = "周" + "日一二三四五六".charAt((new Date().getDay() + 1) % 7);
      } else if (data.date.toDateString() === dayAfterTomorrow.toDateString()) {
        data.time = "后天";
        data.week = "周" + "日一二三四五六".charAt((new Date().getDay() + 2) % 7);
      } else {
        data.time = month+"/"+day;
        data.week = "周" + "日一二三四五六".charAt(data.date.getDay());
      }

      // 将格式化后的数据添加到 futureDates 数组中
      this.futureDates.push(data);
    }

  },
};
</script>

<style lang="scss" scoped>
.shopping-wrapper {
  width: 690rpx;
  margin: 20rpx auto 0rpx;
  padding: 0rpx 20rpx 400rpx;
  .list-item {
    background: #FFFFFF;
    border-radius: 16rpx 16rpx 16rpx 16rpx;
    width: calc(100% - 54rpx);
    padding: 30rpx 27rpx;

    &-content {
      width: calc(100% - 210rpx);

      &-title {
        width: 100%;
        font-family: PingFang SC, PingFang SC;
        font-weight: 400;
        font-size: 28rpx;
        color: #333333;
        line-height: 40rpx;
        text-align: left;
        font-style: normal;
        text-transform: none;
        white-space: nowrap; /* 防止文本换行 */
        overflow: hidden; /* 隐藏溢出的文本 */
        text-overflow: ellipsis;
      }
    }

    .course-image {
      width: 176rpx;
      height: 176rpx;
      border-radius: 10rpx;
    }

    &-week {
      width: 96rpx;
      height: 112rpx;
      background: #F8F9FA;
      border-radius: 20rpx 20rpx 20rpx 20rpx;
    }

    &-week-Selected {
      background: linear-gradient(315deg, #CA9359 0%, #E2B98E 100%);
      width: 96rpx;
      height: 112rpx;
      border-radius: 20rpx 20rpx 20rpx 20rpx;
      color: #FFFFFF;
    }

    &-date{
      width: 193rpx;
      height: 70rpx;
      background: #F8F9FA;
      border-radius: 20rpx 20rpx 20rpx 20rpx;
      border: 1rpx solid #CCCCCC;
    }
    &-date-Selected {
      width: 193rpx;
      height: 70rpx;
      background: #F9F2E6;
      border-radius: 16rpx 16rpx 16rpx 16rpx;
      border: 1rpx solid #F9F2E6;
      color: #C29556;
    }
    &-date-prohibit{
      width: 193rpx;
      height: 70rpx;
      background: #F6F6F6;
      border: 1rpx solid #F6F6F6;
      border-radius: 16rpx 16rpx 16rpx 16rpx;
      color: #999999;
    }

    &-date-test{
      font-size: 24rpx;
      line-height: 40rpx;
      text-align: center;
      font-style: normal;
      text-transform: none;
      color: #333333;
    }



  }

  .tubiao {
    width: 6rpx;
    height: 28rpx;
    background: #C29556;
    border-radius: 0rpx 0rpx 0rpx 0rpx;
  }

  .title {
    font-weight: 500;
    font-size: 28rpx;
    color: #333333;
    line-height: 40rpx;
    text-align: left;
    font-style: normal;
    text-transform: none;
  }
}
.h-view {
  flex: 1;
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  align-items: center;
}

.left-title {
  font-size: 28rpx;
}
.minus {
  width: 48rpx;
  height: 48rpx;
  background: #FFFFFF;
  border-radius: 8rpx 0rpx 0rpx 8rpx;
  border: 1rpx solid #CCCCCC;
  @include flex;
  justify-content: center;
  align-items: center;
}

.input {
  height: 48rpx;
  width: 48rpx;
  background: #FFFFFF;
  border-radius: 0rpx 0rpx 0rpx 0rpx;
  border: 1rpx solid #CCCCCC;
}

.plus {
  width: 48rpx;
  height: 48rpx;
  background-color: #FFFFFF;
  border-radius:  0rpx 8rpx 8rpx 0rpx;
  border: 1rpx solid #CCCCCC;
  display: flex;
  justify-content: center;
  align-items: center;
}
.bottom-navigation{
  position: fixed;
  // 文字垂直居中
  display: flex;
  align-items: center;
  bottom: 0;
  height: 100rpx;
  width: calc(100% - 40rpx);
  background: #FFFFFF;
  box-shadow: 0rpx -2rpx 0rpx 0rpx #F1F3F6;
  border-radius: 24rpx 24rpx 0rpx 0rpx;
  border: 0rpx solid #979797;
  padding: 20rpx 20rpx 68rpx 20rpx ;
  z-index: 2;
  .activity-button {
    width: 670rpx;
    height: 88rpx;
    background: linear-gradient(315deg, #CA9359 0%, #E2B98E 100%);
    border-radius: 292rpx 292rpx 292rpx 292rpx;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 28rpx;
    color: #FFFFFF;
    line-height: 36rpx;
    text-align: center;
    font-style: normal;
    text-transform: none;
    // 文字垂直居中
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

</style>
