<template>
  <view class="body-background" :style="{
		backgroundImage:'url('+staticImage.wallpaperBgImage+')'
		}"></view>
	<HeaderNav title="预约服务" :is-back="true"></HeaderNav>
	<view class="app-wallpaper">
    <view class="addr-container">
      <view class="addr-content-container">
        <view class="addr-content">
          <view class="addr-content-main row" :style="{
          backgroundImage:'url('+staticImage.addrBg+')'
          }" @click="navTo('/pages/Addr/index?type=select')">
            <view class="main-img">
              <image mode="widthFix" class="img" :src="staticImage.addrAvatar"/>
            </view>
            <view class="main-content">
              <image mode="heightFix" class="img" :src="staticImage.addrFw"/>
              <view class="main-content-text" style="max-width:300rpx;">
                <u-text :text="address.info || '请输入具体地址'" color="#131313" size="30"></u-text>
              </view>
            </view>
            <view class="main-select-btn ">
              <view class="main-select-btn-gun"></view>
              <view class="main-select-btn-content row">
                <view class="content-img col-12">
                  <image mode="widthFix" class="img" :src="staticImage.addrBook"/>
                </view>
                <view class="content-text col-12">
                  选择地址
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="addr-background-container">
        <view class="addr-background-content"></view>
      </view>
    </view>
    <view class="order-container">
      <view class="order-content-container">
        <view class="order-content">
          <view class="order-content-main row">
            <view class="order-item row">
              <view class="item-title">
                服务日期
              </view>
              <view class="item-content row col">
                <view class="item-content-tag" v-for="(item,index) in timeList" v-if="timeList.length !== 0">
                  <view class="tag-text" style="margin-bottom:10rpx ;">
                    {{ item.date }} {{(item.time)?'/'+item.time:''}}
                  </view>
                  <view class="tag-close" @click="delTime(index)">
                    <image mode="heightFix" class="img" :src="staticImage.tagClose"/>
                  </view>
                </view>
                <view class="" v-else @click="showCalendar">
                  <u-text text="请选择服务日期" size="28" color="#636363"></u-text>
                </view>
              </view>
              <view class="item-icon" @click="showCalendar">
                <u-icon name="arrow-right"></u-icon>
              </view>
            </view>
            <view class="order-item row">
              <view class="item-title">
                增值服务
              </view>
              <view class="item-content row col">
                <view class="item-content-tag" v-for="(item,index) in addServiceChecked" v-if="addServiceChecked.length !== 0">
                  <view class="tag-text">
                    {{item.name}}
                  </view>
                  <view class="tag-close" @click="delAddService(index)">
                    <image mode="heightFix" class="img" :src="staticImage.tagClose"/>
                  </view>
                </view>
                <view v-else>
                  <u-text text="请选择增值服务" size="28" color="#636363" @click="showAddServicePopup"></u-text>
                </view>

              </view>
              <view class="item-icon" @click="showAddServicePopup">
                <u-icon name="arrow-right"></u-icon>
              </view>
            </view>
            <view class="order-item row" @click="navTo('/pages/UserCoupons/index?type=select')">
              <view class="item-title">
                选择优惠
              </view>
              <view class="item-content row col">
                <view class="item-content-text" v-if="coupons.title">
                  {{coupons.title}}
                </view>
                <view class="item-content-text" v-else>
                  <u-text text="请选择优惠券" size="28" color="#636363"></u-text>
                </view>
              </view>
              <view class="item-icon">
                <u-icon name="arrow-right"></u-icon>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="order-background-container">
        <view class="order-background-content"></view>
      </view>
    </view>
    <view class="order-container">
      <view class="order-content-container">
        <view class="order-content">
          <view class="order-content-main row">
            <view class="order-content-main-title-img">
              <image mode="heightFix" class="img" :src="staticImage.selectPet"/>
            </view>
            <view class="order-item pet-page-item row">
              <PetPage class="pet-page" :showCancel="true" type="lists" @change="selectPet" @del="delPet"></PetPage>
            </view>


          </view>
        </view>
      </view>
      <view class="order-background-container">
        <view class="order-background-content"></view>
      </view>
    </view>
    <view class="order-container">
      <view class="order-content-container">
        <view class="order-content">
          <view class="order-content-main row">
            <view class="order-content-main-title-img col-12">
              <image mode="heightFix" class="img" :src="staticImage.selectService"/>
            </view>
            <view class="order-item pet-page-item row">
              <view class="order-item-container row" >

                <view class="order-item-col col-4" @click="radioChange(item)" v-for="(item,index) in basicServiceList">
                  <view class="order-item-content-group">
                    <view class="count-group-content">
                      <image mode="heightFix" class="img" :src="item.logo||staticImage.groupImg"/>
                      <view class="group-title">{{item.name}}</view>
                      <view class="group-desc">{{parseFloat(item.price)}}/次</view>
                      <view class="group-checkbox">
                        <u-checkbox
                            :customStyle="{marginBottom: '8px'}"
                            :key="index"
                            :name="item"
                            :checked="item.id === this.basicServiceChecked"
                            @change="radioChange"
                            shape="circle"
                            size="32"
                            icon-size="30"
                            custom-style="justify-content:center;"
                            active-color="#4DC3B8"
                        >
                        </u-checkbox>
                      </view>
                    </view>
                    <view class="count-group-background">
                      <view class="count-background"></view>
                    </view>
                  </view>
                </view>

              </view>
            </view>

          </view>
        </view>
      </view>
      <view class="order-background-container">
        <view class="order-background-content"></view>
      </view>
    </view>
	</view>
  <view class="footer-menu row">
    <view class="row col">
      <view class="foot-menu-main-title row">
        <view class="main-title">费用共计</view>
        <view class="main-price">￥{{price.all_price}}</view>
        <view class="main-title">元</view>
      </view>
      <view class="foot-menu-checkbox-group row col">
        <view class="foot-menu-checkbox">
          <u-checkbox
              shape="circle"
              size="26"
              custom-style="margin-top:0;margin-bottom:0;"
              icon-size="24"
              active-color="#4DC3B8"
              :checked="readInfo"
              @change="readInfo = !readInfo"
          ></u-checkbox>
        </view>
        <view class="foot-menu-title">
          <text>阅读并同意</text><text class="foot-menu-url" @click="showAgreement">《上门喂养协议》</text>
        </view>
      </view>
    </view>
   <view class="">
     <MzButton
         title="立即下单"
         button-color="#4DC3B8"
         font-color="#FFFFFF"
         button-width="200rpx"
         @click="readInfo ? orderPay() :$u.toast('请先同意协议')"
     >
     </MzButton>
   </view>
  </view>
  <uv-calendar ref="calendar" mode="multiple" title="选择服务日期" color="#4DC3B8" round="40rpx">
    <template #footer>
        <MzButton button-color="#4DC3B8" button-width="90%" font-color="#fff" class="row" style="justify-content: center" @click="timeSelect">确定</MzButton>
    </template>
  </uv-calendar>

  <uv-popup ref="agreement" mode="bottom" round="20rpx" closeable safeAreaInsetTop safeAreaInsetBottom custom-style="position:relative;">
    <view class="title row" style="position:absolute;justify-content: center;width:100%;top:20rpx;left:0;">
      <view class="value col" style="position: relative;text-align: center;">

<!--        <u-text text="协议内容" size="38" color="#191919"></u-text>-->
        <view class="" style="position: relative;display:inline-block;">
          <view style="color:#191919;font-size:38rpx;display:inline-block;position: relative;z-index: 2;">协议内容</view>
          <view class="background" style="width:100%;height:50%;position: absolute;bottom:0;left:0;background-color:rgba(227, 191, 119, 0.6);display:inline-block;z-index:1;"></view>
        </view>
      </view>
    </view>
    <view style="padding:30rpx;max-height:700rpx;overflow: auto;">
      <u-parse :content="feedPolicy"></u-parse>
    </view>
  </uv-popup>
  <uv-popup ref="addServicePopup" mode="bottom" round="20" closeable safeAreaInsetTop safeAreaInsetBottom custom-style="position:relative;">
    <view class="title row" style="position:absolute;justify-content: center;width:100%;top:20rpx;left:0;">
      <view class="value col" style="position: relative;text-align: center;">

        <!--        <u-text text="协议内容" size="38" color="#191919"></u-text>-->
        <view class="" style="position: relative;display:inline-block;">
          <view style="color:#191919;font-size:38rpx;display:inline-block;position: relative;z-index: 2;">增值服务</view>
          <view class="background" style="width:100%;height:50%;position: absolute;bottom:0;left:0;background-color:rgba(227, 191, 119, 0.6);display:inline-block;z-index:1;"></view>
        </view>
      </view>
    </view>
    <view class="pop-service-container">
      <u-cell-group custom-style="max-height:700rpx;overflow:auto;">
        <u-cell
            size="large"
            :title="item.name"
            :label="item.info"
            isLink
            right-icon=""
            v-for="(item,index) in addServiceList"
            @click="selectAddService(index)"
        >
          <template #value>
            <view class="">
              <view class="" style="display:flex;align-items: center">
                <view class="">
                  <u-text :text="parseFloat(item.price)+'元'" size="32" style="white-space: nowrap;" line-height="32"></u-text>
                </view>
                <view class="">
                    <u-checkbox-group @change="addServiceChange">
                      <u-checkbox
                          :name="index"
                          :customStyle="{marginBottom: '0',marginTop: '0',marginLeft:'15rpx'}"
                          size="32"
                          :checked="item.checked"
                          activeColor="#4DC3B8"
                          iconSize="30"
                      >
                      </u-checkbox>
                    </u-checkbox-group>
                </view>
              </view>
            </view>
          </template>
        </u-cell>
      </u-cell-group>
      <view class="row" style="padding-top:30rpx;">
        <view class="col-6" style="padding:0 30rpx;">
          <MzButton title="取消" @click="$refs.addServicePopup.close()"></MzButton>
        </view>
        <view class="col-6" style="padding:0 30rpx;">
          <MzButton title="确认" @click="addServiceConfirm" button-color="#4DC3B8" font-color="#fff"></MzButton>
        </view>
      </view>
    </view>
  </uv-popup>
  <uv-popup ref="doDatePopup" mode="bottom" round="20" closeable safeAreaInsetTop safeAreaInsetBottom custom-style="position:relative;">
    <view class="title row" style="position:absolute;justify-content: center;width:100%;top:20rpx;left:0;">
      <view class="value col" style="position: relative;text-align: center;">

        <!--        <u-text text="协议内容" size="38" color="#191919"></u-text>-->
        <view class="" style="position: relative;display:inline-block;">
          <view style="color:#191919;font-size:38rpx;display:inline-block;position: relative;z-index: 2;">上门时间</view>
          <view class="background" style="width:100%;height:50%;position: absolute;bottom:0;left:0;background-color:rgba(227, 191, 119, 0.6);display:inline-block;z-index:1;"></view>
        </view>
      </view>
    </view>
    <view class="pop-service-container">
      <uv-vtabs
          :chain="false"
          :list="timeListTemp"
          height="700rpx"
          hdHeight="100rpx"
          keyName="date"
          :barScrollable="false"
          barItemActiveLineStyle="background:#4DC3B8;color:#4DC3B8;"
          barItemActiveStyle="color:#4DC3B8;"
          @change="changeVTab"
      >
              <uv-vtabs-item v-if="timeListTemp.length>0">
                <view class="item"
                      v-for="(item,index) in timeListTemp[vTabCurrent].time"
                      :key="index">
                  <view class="item-title" style="padding:30rpx;" @click="doTimeSelect(item,index)"
                        :style="{color:(item.checked)?'#4DC3B8':'#636363'}">
                    <text class="text">{{item.label}} ({{ item.value }})</text>
                  </view>
                </view>
              </uv-vtabs-item>
            <uv-gap bg-color="#fff" height="600"></uv-gap>
      </uv-vtabs>
      <view class="row" style="padding-top:30rpx;">
        <view class="col-6" style="padding:0 30rpx;">
          <MzButton title="取消" @click="$refs.doDatePopup.close()"></MzButton>
        </view>
        <view class="col-6" style="padding:0 30rpx;">
          <MzButton title="确认" @click="doDatePopupConfirm" button-color="#4DC3B8" font-color="#fff"></MzButton>
        </view>
      </view>
    </view>
  </uv-popup>
	<!-- <RightNav></RightNav> -->
</template>

<script>
	import {
		imghost
	} from '@/config/host.js'
	import HeaderNav from '@/components/HeaderNav/Index.vue';
	import FooterNav from '@/components/FooterNav/Index.vue';
	import RightNav from '@/components/RightNav/Index.vue';
	import MzButton from '../../components/MzButton/Index.vue';
	import PetPage from '../../components/PetPage/Index.vue';
	import api from '@/utils/functions.js';
  import {cardDetail} from "@/api/card";
  import {getAddressList} from "@/api/address";
  import image from "@/config/image";
  import {createOrderPrice, getOrderPrice, getStoreService} from "@/api/order";
  import pet from "@/pages/Pet/index.vue";
  import {getConfig} from "@/api/other";
	export default {
    computed: {
      api() {
        return api
      }
    },
		components: {
			HeaderNav,
			FooterNav,
			RightNav,
			MzButton,
      PetPage
		},
		data() {
			return {
        readInfo:false,
        price:{
          all_price:0,
          price:0,
          quan_reduce:0,
        },
        radioValue1:[],
        list: ['未付款', '待评价', '已付款'],
        curNow: 0,
        id:'',
				title: 'Hello',
				loading: true,
        timeList:[],
        timeListTemp:[],
				staticImage: image.OrderPage,
				isTop: false,
				pagePadding: 100,
				orderCardList:[
					{
						title:'成都市武侯区丰德国际4栋...',
						tags:['刷毛','洗澡'],
						do_time:'2023/05/03 15—17时',
						create_time:'2023/03/03 15:23:22',
					},
					{
						title:'成都市武侯区丰德国际4栋...',
						tags:['刷毛','洗澡'],
						do_time:'2023/05/03 15—17时',
						create_time:'2023/03/03 15:23:22',
					},
				],
        couponsList: [{
          price: '57',
          title: '57元抵扣券',
          cause: '满0.01使用',
          coupons_number:10,
          time: '满0.01元使用仅限线上预约下单使用',
          is_timeout: false,
        }],
        address:{},
        addServiceList:[],
        basicServiceList:[],
        pages:{
          page:1,
          limit:10
        },
        addServiceChecked:[],
        coupons:{},
        doTimeList:[
          {
            label:'上午',
            value:'09:00-12:00'
          },{
            label:'下午',
            value:'13:30-17:00'
          },{
            label:'晚上',
            value:'07:00-19:30'
          },
        ],
        vTabCurrent:0,
        petChecked:[],
        basicServiceChecked:'',
        feedPolicy:'',
			}
		},
		onLoad(options) {
      this.id = options.id;
		},
    updated() {

    },
    onShow(){
      this.getDefaultAddress();
      this.getUserCoupons();
    },
		methods: {
      addServiceChange(e){
        this.addServiceList[e].checked = !this.addServiceList[e].checked;
      },
      orderPay(){

        if(
            this.address
            &&this.timeList.length>0
            &&this.petChecked.length>0
            &&this.basicServiceChecked!==''
        ){
          console.log(this.basicServiceChecked)
          createOrderPrice({
            address_id: this.address.id,
            do_date: this.timeList.map(res => [res.date,res.time]),
            services: this.addServiceList.map(res => res.id).join(','),
            basic_service:this.basicServiceChecked,
            pet_ids: this.petChecked.map(res => res.id).join(','),
            store_id:this.addServiceList[0].store_id,
            user_coupon_id:this.coupons.id || 0
          }).then(res => {
            console.log(res)
            this.price = res.data;
          });
        }
      },
      checkOrderData(){
        if(
            this.address
            &&this.timeList.length>0
            &&this.petChecked.length>0
            &&this.basicServiceChecked!==''
        ){
          console.log(this.basicServiceChecked)
          getOrderPrice({
            address_id: this.address.id,
            do_date: this.timeList.map(res => [res.date,res.time]),
            services: this.addServiceList.map(res => res.id).join(','),
            basic_service:this.basicServiceChecked,
            pet_ids: this.petChecked.map(res => res.id).join(','),
            store_id:this.addServiceList[0].store_id,
            user_coupon_id:this.coupons.id || 0
          }).then(res => {
            console.log(res)
            this.price = res.data;
          });
        }
      },
      selectPet(petList){
        this.petChecked = petList;
        this.checkOrderData();
      },
      delPet(index){
        this.petChecked.splice(index,1);
        this.checkOrderData();
      },
      doDatePopupConfirm(){
        this.timeListTemp.forEach(item => {
          if(item.time === ""){
            api.error(item.date+'未指定上门时间')
            return false;
          }
        });
        this.timeListTemp.forEach(item => {
          item.time.forEach(row => {
            if(row.checked){
              this.timeList.push({date:item.date,time:row.value,label:row.label});
            }
          });
        });
        console.log(this.timeList)
        // this.timeList = this.timeListTemp;
        this.$refs.doDatePopup.close()
      },
      doTimeSelect(item,index){
        console.log(this.timeListTemp[this.vTabCurrent].time[index])
        this.timeListTemp[this.vTabCurrent].time[index].checked = !item.checked
        this.checkOrderData();
      },
      changeVTab(index){
        console.log(index)
        this.vTabCurrent = index
      },
      getUserCoupons(){
        let cacheCoupons = uni.getStorageSync('userCoupons');
        if (cacheCoupons) {
          console.log(cacheCoupons)
          this.coupons = cacheCoupons;
          uni.removeStorage({key:'userCoupons'});
        }
      },
      showAddServicePopup(){
        this.$refs.addServicePopup.open();
      },
      selectAddService(index){
       this.addServiceList[index].checked = !this.addServiceList[index].checked;
      },
      addServiceConfirm(){
        let list = [];
        this.addServiceList.map(item => {
          if(item.checked){
            list.push(item);
          }
        })
        this.addServiceChecked = list;
        this.$refs.addServicePopup.close();
      },
      delAddService(index){
        this.addServiceChecked.splice(index,1);
      },
      getStoreServiceList(){
        getStoreService({address_id: this.address.id}).then(res => {
          this.addServiceList = res.data.add_service.map(item => {
            item.checked = false;
            return item;
          });
          console.log(this.addServiceList)
          this.basicServiceList = res.data.basic_service;
        });
      },
      getDefaultAddress() {
        let cacheAddress = uni.getStorageSync('address');
        if (cacheAddress) {
          console.log('hasCacheAddress')
          console.log(cacheAddress)
          this.address = cacheAddress;
        } else {
          getAddressList(this.pages).then(res => {
            res.data.forEach(item => {
              if (item.is_default === 1) {
                this.address = item;
              }
            });
          })
        }
        if(this.address.id){
          this.getStoreServiceList();
        }
      },
      delTime(index){
        this.timeList.splice(index,1);
      },
      timeSelect(e){
        let selected = this.$refs.calendar.selected;
        this.timeListTemp = selected.map(item => {
          return {
            date:item,
            time:[{
              label:'上午',
              value:'09:00-12:00',
              checked:false,
            },{
              label:'下午',
              value:'13:30-17:00',
              checked:false,
            },{
              label:'晚上',
              value:'07:00-19:30',
              checked:false,
            },]
          }
        });
        // this.timeListTemp = this.timeList;

        this.$refs.calendar.confirm();
        this.$refs.doDatePopup.open();
      },
      showAgreement(){
        getConfig('FeedPolicy').then(res => {
          this.feedPolicy = res.data.FeedPolicy;
        })
        this.$refs.agreement.open();
      },
      navTo(url){
        uni.navigateTo({
          url:url
        })
      },
      sectionChange(index) {
        this.curNow = index;
      },
      radioChange(n) {
        this.basicServiceChecked = n.id
        this.radioValue1 = n.id
        console.log('radioChange', n);
        this.checkOrderData();
      },
      groupChange(n) {
        console.log('radioChange', n);
      },
      confirm(){},
      showCalendar(){
        this.$refs.calendar.open();
      },

		},
		onPageScroll(res) {
			if(res.scrollTop <= 20){
				uni.$emit('isTop', true);
			}else{
				uni.$emit('isTop', false);
			}
		},
		created() {
			this.pagePadding = (api.navHeight().navPaddingTop +
				api.navHeight().navHeight + (api.navHeight().headerPadding * 2))
		},
    mounted() {

    },
	}
</script>

<style lang="scss">
	@import './components/index.scss';
</style>