<template>
    <view class="service-detail-page">
        <view class="order-main-top">
            <view class="order-main-left">
                <view class="order-detail-status">
                    {{ orderBook.status == 3 || orderBook.status == 4 ? '订单已完成' : orderBook.status == 6 ? '订单已取消' : '订单服务中' }}
                </view>
                <view class="order-detail-des" v-if="orderBook.status == 2 && bookCount >= 1">您剩余{{ bookCount }}次保洁次卡可预约</view>
            </view>
            <view class="order-main-right">
                <view class="service-times">
                    <text class="current-times">{{ orderBook.servicedTimes }}</text>
                    /{{ orderBook.serviceTimes }}
                </view>
            </view>
        </view>
        <!-- 订单详情信息 -->
        <view class="service-info">
            <view class="info-title">{{ orderBook.goodsName }} 鲸致生活</view>
            <view class="info-content">
                <image mode="aspectFill" class="product-img" :src="goods.picUrl"></image>
                <view class="info-detail">
                    <view>规格：1</view>
                    <view>服务次数：{{ orderBook.serviceTimes }}</view>
                    <view>未预约次数：{{ noAppoint }}</view>
                    <view>单价：¥ {{ product.price }} 元</view>
                </view>
            </view>
        </view>

        <!-- 次卡列表 -->

        <!-- <van-tabs active="{{ activeTab }}" color="#09afff" bind:change="onTabChange">
    <van-tab title="未使用" name="1"></van-tab>
    <van-tab title="已使用" name="2"></van-tab>

  </van-tabs> -->
        <view class="appoint-tabs-wrapper">
            <view :class="'appoint-tab-item ' + (activeTab == 1 ? 'active' : '')" data-tab="1" @tap="onTabChange">未使用</view>
            <view :class="'appoint-tab-item ' + (activeTab == 2 ? 'active' : '')" data-tab="2" @tap="onTabChange">已使用</view>
        </view>

        <view class="service-list">
            <view class="service-item" v-for="(item, index) in serList" :key="index">
                <view class="service-item-top">
                    <view class="item-left">
                        <image mode="aspectFit" class="ci-img" src="/static/images/icon-ci.png"></image>
                        <text>服务次卡</text>
                    </view>
                    <!-- <view class="service-item-status">{{activeTab=='2'?'服务已完成':(item.status===0?"未预约":(item.status===7?"匹配中":'待履约'))}}</view> -->
                    <view class="service-item-status">{{ activeTab == '2' ? '服务已完成' : item.status == 0 ? '未预约' : '待履约' }}</view>
                </view>

                <view class="service-item-bottom">
                    <view class="service-time">
                        <text>预约时间：</text>
                        <text>{{ item.bookTime }}</text>
                    </view>
                    <!-- <view class="service-time">
          <text>服务者：</text>
          <text>{{item.servantName}}</text>
        </view> -->
                    <!-- 0-未预约，1-已预约，2-服务中，3-服务已提供，4-服务已完成，5-取消 未付款，6-退款   orderChannel==25 -->
                    <view
                        class="go-appoint"
                        v-if="item.status === 0 && activeTab == '1' && aftersaleStatus != 1 && aftersaleStatus != 2"
                        @tap="showAppoint"
                        :data-id="item.id"
                        :data-status="item.status"
                    >
                        预约
                    </view>
                    <view
                        class="go-appoint"
                        v-if="(item.status == 1 || item.status == 7) && activeTab == '1'"
                        @tap="showAppoint"
                        :data-id="item.id"
                        :data-status="item.status"
                        :data-time="item.bookTime"
                    >
                        修改预约
                    </view>
                    <view class="go-appoint" v-if="item.checkAcceptState == 1" @tap="goReVisit" :data-id="item.id">去验收</view>
                </view>
            </view>
        </view>
        <view class="no-list" v-if="serList.length == 0">没有更多了</view>

        <!-- custom-style="height: 80%" -->

        <view class="appoint-overlay-wrapper" v-if="choosePopup" @tap="onClose"></view>
        <!-- <van-popup show="{{ choosePopup }}" round position="bottom" bind:click-overlay="onClose"> -->
        <view class="popup-wrapper popup-wrapper-special" v-if="choosePopup">
            <!-- 标题 -->
            <view class="popup-title popup-title-special">选择服务者上门时段</view>

            <block>
                <view class="popup-content popup-content-special">
                    <view class="time-select-left">
                        <view
                            class="time-select-left-item"
                            @tap="dateCheck"
                            :data-index="index"
                            :data-week="item.week"
                            :data-date="item.date"
                            :data-isbook="item.isBook"
                            v-for="(item, index) in dateList"
                            :key="index"
                        >
                            <view>
                                <!-- <view hidden="{{index>1}}" class="date-tag">{{index==0?'明天':'后天'}}</view>
              <text  wx:if="{{index<=1||(index<=7&&(item.week=='周六'||item.week=='周日'))}}" class="full-time">约满</text> -->
                                <text v-if="item.name" class="date-tag">{{ item.name }}</text>
                                <text v-if="item.mark" class="full-time">{{ item.mark }}</text>
                            </view>

                            <view :class="dateIndex == index ? 'current-date' : ''">{{ item.date + ' ' + item.week }}</view>
                        </view>
                    </view>
                    <view class="time-select-right">
                        <view class="time-select-right-item" @tap="timeCheck" :data-stock="item.stock" :data-index="index" v-for="(item, index) in timeList" :key="index">
                            <view :class="item.stock <= 0 ? 'zero-stock' : ''">
                                <text :class="timeIndex === index ? 'current-date' : ''">{{ item.time }}</text>
                                <!-- <text class="stock-text">(库存:{{item.stock}})</text> -->
                            </view>

                            <view v-if="timeIndex == index" class="date-tag">已选</view>
                        </view>
                    </view>
                </view>
            </block>

            <!-- 确认按钮 -->
            <view class="popup-btn-wrapper">
                <view @tap="confirmTime" class="confirm-btn">确定</view>
            </view>
        </view>

        <!-- </van-popup> -->
    </view>
</template>

<script>
var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
var check = require('../../../utils/check.js');
var app = getApp();
export default {
    data() {
        return {
            noAppoint: '',
            aftersaleStatus: '',
            orderId: '',
            serviceId: '',
            bookCount: 0,
            orderStatusText: '订单服务中',
            activeTab: 1,

            orderBook: {
                status: '',
                servicedTimes: '',
                goodsName: '',
                serviceTimes: ''
            },

            orderChannel: 0,
            jzOrderBookDetails: [],
            unusedSerList: [],
            usedSerList: [],
            serList: [],
            choosePopup: false,

            // timeList: check.getTimeList(1),
            timeList: [],

            dateList: util.getDateList(new Date(new Date().getTime() + 3600000 * 24 * 0), 1, 30),
            timeIndex: '',

            //选中的时间段
            dateIndex: 0,

            //选中的日期
            product: {
                price: ''
            },

            goods: {
                picUrl: ''
            }
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad: function (options) {
        this.setData({
            orderId: options.orderId
        });
        // this.getServiceDetail();
    },
    onShow: function (options) {
        if (this.orderId) {
            this.getServiceDetail();
        }
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */

    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {},
    methods: {
        /**
         * 生命周期函数--监听页面隐藏
         */
        getServiceDetail: function () {
            // wx.showLoading({
            //   title: '加载中',
            // });

            // setTimeout(function() {
            //   wx.hideLoading();
            // }, 2000);

            util.request(api.ServiceDetail, {
                order_id: this.orderId
                // order_id: '1342922'
            }).then((res) => {
                // wx.hideLoading();
                if (res.errno === 0) {
                    let jzOrderBookDetails = res.data.jzOrderBookDetails;
                    let unusedSerList = jzOrderBookDetails.filter((item) => {
                        return item.status === 0 || item.status == 1 || item.status == 7;
                    });
                    let usedSerList = jzOrderBookDetails.filter((item) => {
                        return item.status == 3 || item.status == 4;
                    });
                    // let timeList = check.getTimeList(res.data.goods.serviceDuration);
                    this.setData({
                        aftersaleStatus: res.data.order ? res.data.order.aftersaleStatus : '',
                        noAppoint: res.data.noAppoint,
                        goods: res.data.goods,
                        orderBook: res.data.orderBook,
                        jzOrderBookDetails: jzOrderBookDetails,
                        // activeTab: 1,
                        unusedSerList: unusedSerList,
                        usedSerList: usedSerList,
                        serList: this.activeTab == 1 ? unusedSerList : usedSerList,
                        // timeList: timeList,
                        orderChannel: res.data.orderChannel,
                        product: res.data.product
                    });
                }
            });
        },

        onTabChange(e) {
            let tab = e.currentTarget.dataset.tab;
            this.setData({
                activeTab: tab
            });
            if (this.activeTab == 1) {
                this.setData({
                    serList: this.unusedSerList
                });
            } else {
                this.setData({
                    serList: this.usedSerList
                });
            }
        },

        showAppoint(e) {
            let status = e.currentTarget.dataset.status;
            if (status == 1) {
                let time = e.currentTarget.dataset.time;
                let str = time.substr(0, 16).replace(/-/g, '/');
                let isNear = new Date(str).getTime() - new Date().getTime() - 7200 * 1000;
                console.log(isNear);
                if (isNear < 0) {
                    uni.showToast({
                        title: '服务时间小于2小时，不能修改预约',
                        icon: 'none',
                        duration: 2000
                    });
                    return false;
                }
            }
            this.setData({
                choosePopup: true,
                serviceId: e.currentTarget.dataset.id
            });
            this.getDayStock();
        },

        getDayStock() {
            if (this.dateIndex < 0) {
                return false;
            }
            let params = {
                day: this.dateList[this.dateIndex].date,
                goodsId: this.orderBook.goodsId,
                lng: this.orderBook.lng,
                lat: this.orderBook.lat,
                productId: this.orderBook.productId
            };
            uni.showLoading({
                title: '加载中'
            });
            util.request(api.EveryDayStock, params, 'GET')
                .then((res) => {
                    uni.hideLoading();
                    if (res.errno == 0) {
                        this.setData({
                            timeList: res.data,
                            timeIndex: 0
                        });
                        // let validList = this.data.timeList.filter(item => {
                        //   return item.stock > 0;
                        // });
                        // if (validList.length > 0) {
                        //   this.setData({
                        //     timeIndex: validList[0].id - 1
                        //   });
                        // } else {
                        //   this.setData({
                        //     timeIndex: ''
                        //   });
                        // }
                    } else {
                        uni.showToast({
                            title: res.errmsg,
                            icon: 'none',
                            duration: 2000
                        });
                        this.setData({
                            timeList: [],
                            timeIndex: ''
                        });
                    }
                })
                .catch(function (err) {
                    console.log(err);
                    uni.hideLoading();
                    uni.showToast({
                        title: err.errMsg,
                        icon: 'none'
                    });
                    this.setData({
                        timeList: [],
                        timeIndex: ''
                    });
                });
        },

        onClose() {
            this.setData({
                choosePopup: false
            });
        },

        dateCheck(e) {
            let index = e.currentTarget.dataset.index;
            let date = e.currentTarget.dataset.date;
            let week = e.currentTarget.dataset.week;
            let isbook = e.currentTarget.dataset.isbook;

            // if (index >= 7 || (index >= 2 && index < 7 && (week != '周六' && week != '周日'))) {
            // 	this.setData({
            // 		dateIndex: index
            // 	});
            // }

            if (isbook) {
                this.setData({
                    dateIndex: index
                });
                this.getDayStock();
            }
        },

        timeCheck(e) {
            let index = e.currentTarget.dataset.index;
            // if (e.currentTarget.dataset.stock == 0) {
            //   wx.showToast({
            //     title: '所选时间无库存，请选择其他时间',
            //     icon: 'none',
            //     duration: 2000
            //   });
            //   return;
            // }
            this.setData({
                timeIndex: index
            });
        },

        confirmTime() {
            if (this.timeIndex === '') {
                uni.showToast({
                    title: '请选择服务时间',
                    icon: 'none',
                    duration: 2000
                });
                return false;
            }
            let date = this.dateList[this.dateIndex].date;
            let week = this.dateList[this.dateIndex].week;
            let time = this.timeList[this.timeIndex].time;
            console.log(date, week, time);
            let params = {
                detail_id: this.serviceId,
                date: date,
                startTime: time.split('-')[0],
                endTime: time.split('-')[1]
            };
            util.request(api.ServiceOrderBook, params, 'GET').then((res) => {
                console.log(res);
                if (res.errno == 0) {
                    uni.showToast({
                        title: '预约成功',
                        icon: 'none',
                        duration: 2000
                    });
                    this.setData({
                        // oneTimeAppoint:date+' '+week+' '+time,
                        choosePopup: false
                    });
                    this.getServiceDetail();
                } else {
                    util.showErrorToast(res.errmsg);
                }
            });
        },

        goReVisit(e) {
            let id = e.currentTarget.dataset.id;
            uni.navigateTo({
                url: '/pages/extra/newRevisit/newRevisit?id=' + id,
                success: (res) => {},
                fail: (res) => {}
            });
        }
    }
};
</script>
<style>
page {
    background: #f6f5f5;
}

/* 服务详情顶部 */
.order-main-top {
    height: 160rpx;
    background: url('https://mall.zhaijieshi.cc/file/jzmall/weixin/service-detail-bg.png') no-repeat center;
    background-size: 100% 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 0 0 20rpx;
    padding: 0 24rpx;
}
.order-main-top view,
.order-main-top text {
    color: #fff;
    font-size: 28rpx;
}
.order-main-top .order-detail-status {
    font-size: 36rpx;
    font-weight: bold;
    margin-bottom: 10rpx;
}
.order-main-right {
    text-align: right;
}
.order-main-right .view-service {
    width: 148rpx;
    height: 44rpx;
    line-height: 44rpx;
    border-radius: 44rpx;
    border: 1rpx solid #fff;
    text-align: center;
    margin: 10rpx 0 0;
}
.order-main-right .current-times {
    font-size: 40rpx;
    font-weight: bold;
}
.service-info {
    margin: 20rpx 24rpx;
    border-radius: 40rpx;
    background: #fff;
    height: 322rpx;
    padding: 32rpx 40rpx;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}
.info-content {
    height: 180rpx;
    display: flex;
    align-items: center;
}
.service-info view.info-title {
    font-size: 32rpx;
    color: #000;
}
.product-img {
    width: 180rpx;
    height: 180rpx;
    margin-right: 20rpx;
}
.info-detail view {
    color: #999;
    font-size: 28rpx;
    line-height: 46rpx;
}
.van-tabs view {
    color: #666;
}
.van-tab--active view {
    color: #09afff;
}

.service-list {
    border-top: 1rpx solid #ddd;
    padding: 20rpx 24rpx;
}
.service-item {
    /* height: 180rpx; */
    border-radius: 20rpx;
    margin: 0 0 20rpx;
    padding: 42rpx 24rpx 34rpx;
    background: #fff;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}
.service-time {
    display: flex;
    justify-content: space-between;
}
.service-time text {
    color: #999;
    font-size: 28rpx;
}
.item-left .service-item-status {
    font-size: 28rpx;
}

.service-item-top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 42rpx;
    margin-bottom: 10rpx;
}
.item-left {
    display: flex;
    align-items: center;
}
.service-item-top .item-left text {
    color: #333;
    font-weight: bold;
    font-size: 28rpx;
}
.ci-img {
    width: 32rpx;
    height: 32rpx;
    margin-right: 16rpx;
}
.service-item view.go-appoint {
    margin-top: 10rpx;
    float: right;
    width: 136rpx;
    height: 44rpx;
    line-height: 44rpx;
    text-align: center;
    border-radius: 44rpx;
    border: 1rpx solid #09afff;
    font-size: 28rpx;
    margin-left: 20rpx;
}
.full-time {
    color: #09afff;
}
.service-detail-page .no-list {
    margin: 56rpx 0 0;
    text-align: center;
    color: #999;
    font-size: 28rpx;
}

/* 选择时间 */

view.popup-wrapper view {
    color: #888;
    font-size: 30rpx;
}

.popup-content {
    flex: 1;
}
.popup-title {
    height: 96rpx;
    line-height: 96rpx;
    text-align: center;
    border-bottom: 1rpx solid #ddd;
}
.popup-content {
    display: flex;
}
.time-select-left {
    flex: 2;
    border-right: 1rpx solid #ddd;
    padding: 0 20rpx;
}
.time-select-right {
    flex: 3;
    padding: 0 8rpx;
    height: 468px;
    overflow-y: auto;
}
.time-select-left-item {
    height: 108rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
}
.popup-content .current-date {
    color: #09afff;
    font-weight: bold;
}
view.popup-wrapper .time-select-right-item {
    height: 104rpx;
    border-bottom: 1rpx solid #ddd;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 24rpx;
}
.time-select-right-item view {
    color: #6d7278;
    font-weight: bold;
}
view.popup-btn-wrapper {
    margin: 20rpx 0 0;
    padding: 0 24rpx 20rpx;
}
view.popup-btn-wrapper button > view {
    color: #fff;
}
view.popup-wrapper .date-tag {
    color: #09afff;
    height: 44rpx;
    line-height: 42rpx;
    width: 90rpx;
    border: 2rpx solid #09afff;
    border-radius: 44rpx;
    text-align: center;
    font-weight: normal;
    font-size: 24rpx;
    display: inline-block;
}
view.popup-wrapper .full-time {
    color: #09afff;
    font-size: 24rpx;
    margin: 0 0 0 20rpx;
    height: 44rpx;
    line-height: 44rpx;
    float: right;
    padding-right: 40rpx;
}
.first-appoint-date-item {
    height: 108rpx;
    display: flex;
    align-items: center;
    padding: 0 0 0 240rpx;
}
.first-time-selected {
    margin: 0 0 0 60rpx;
}

.select-week-times {
    border-top: 1rpx solid #ddd;
}
.week-select-left {
    flex: 1.2;
}
.week-select-left > view.time-select-left-item {
    padding: 0 0 0 60rpx;
    display: flex;
    align-items: flex-start;
    justify-content: flex-start;
    flex-direction: row;
    padding: 10rpx 0 0 60rpx;
}
.week-select-left > view.time-select-left-item .week-str {
    padding: 12rpx 0 0 0;
}
view.popup-wrapper view.select-num-tag {
    width: 32rpx;
    height: 32rpx;
    line-height: 32rpx;
    background: #09afff;
    border-radius: 34rpx;
    font-size: 20rpx;
    color: #fff;
    text-align: center;
    margin: 0 0 0 6rpx;
}
.popup-content-special {
    position: relative;
}
.popup-title-special {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    background: #fff;
}
.popup-content-special {
    height: 900rpx;
    margin-top: 96rpx;
}
.popup-content-special .time-select-left {
    height: 900rpx;
    overflow-y: scroll;
}
.stock-text {
    font-size: 20rpx;
    font-weight: normal;
    color: #888;
}
.zero-stock {
    color: #ccc;
}
.appoint-overlay-wrapper {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.7);
    z-index: 999;
}
/* 选择时间 */
view.popup-wrapper {
    /* padding: 0 0 20rpx; */
    color: #333;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    /* height: 80%; */
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    background: #fff;
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);
    z-index: 9999;
}
view.popup-wrapper view.confirm-btn {
    background: #09afff;
    height: 88rpx;
    line-height: 88rpx;
    border-radius: 88rpx;
    text-align: center;
    color: #fff;
}
.go-pay-wrapper {
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);
}
.go-pay-wrapper view {
    background: #09afff;
    height: 88rpx;
    line-height: 88rpx;
    border-radius: 88rpx;
    text-align: center;
    color: #fff;
}
.appoint-tabs-wrapper {
    height: 88rpx;
    display: flex;
    align-items: center;
    line-height: 88rpx;
    justify-content: space-around;
}
.appoint-tab-item {
    /* width:80rpx; */
}
.appoint-tab-item.active {
    color: #09afff;
    border-bottom: 4rpx solid #09afff;
}
</style>
