<template>
	<view class="order-pages" v-if="detail.id">
		<!-- 开始服务倒计时 -->
		<view class="fix" style="top:-100%;left: -100%;" v-if="detail.pay_type==6">
			<min-countdown :targetTime="detail.start_service_time_unix * 1000" :isPlay="true"></min-countdown>
		</view>

		<view class="item-child  pd-lg fill-base f-paragraph c-base" :style="{background:primaryColor}">
			<view class="text-bold">{{statusType[detail.pay_type]}}</view>
			<view class="f-caption mt-sm" v-if="detail.pay_type == 1 && detail.end_time > 0">请在<min-countdown
					:targetTime="over_time_text" @callback="countEnd"></min-countdown>内完成支付，逾期未支付，订单将自动取消</view>
			<view class="space-lg"></view>
		</view>

		<!-- // pay_type 1待支付，2待服务，3技师接单，4技师出发，5技师到达，6服务中，7服务完成，8待评价 -->
		<view
			class="menu-list flex-warp rel ml-lg mr-lg pt-lg pb-lg pl-md pr-md fill-base f-paragraph c-caption radius-16">
			<view class="menu-line abs b-1px-b"></view>
			<view class="item-child flex-center flex-column f-icontext c-paragraph"
				:style="{color:detail.pay_type > item.pay_type -1?primaryColor:''}" v-for="(item,index) in lineList"
				:key="index">
				<view class="item-img fill-base flex-center mb-sm radius"
					:style="{borderColor:detail.pay_type > item.pay_type -1?primaryColor:''}">
					<i class="iconfont" :class="item.icon"></i>
				</view>
				<view>{{item.title}}</view>
			</view>
		</view>


		<view class="item-child mt-md ml-lg mr-lg pd-lg fill-base radius-16">
			<view class="flex-between pb-lg">
				<view class="f-paragraph c-title max-380 ellipsis">预约内容</view>
			</view>
			<view class="flex-center" :class="[{'mb-lg':aindex != detail.order_goods.length -1}]"
				v-for="(aitem,aindex) in detail.order_goods" :key="aindex">
				<image mode="aspectFill" class="avatar lg radius-16" :src="aitem.goods_cover"></image>
				<view class="flex-1 ml-md">
					<view class="flex-between">
						<view class="goods-title f-title c-title ellipsis" :class="[{'max-300':aitem.refund_num>0}]">
							{{aitem.goods_name}}
						</view>
						<view class="f-caption c-warning" v-if="aitem.refund_num>0">已退x{{aitem.refund_num}}</view>
					</view>
					<view class="f-caption c-caption mt-md">服务时间：{{detail.start_time}}</view>
					<view class="flex-between">
						<view class="flex-y-baseline f-caption c-warning">¥<view class="f-title text-bold">
								{{aitem.price}}
							</view>
						</view>
						<view class="c-paragraph">x{{aitem.num}}</view>
					</view>
				</view>
			</view>
		</view>

		<view class="mt-md ml-lg mr-lg pd-lg fill-base f-paragraph c-caption radius-16">
			<view class="flex-between">
				<view>下单人</view>
				<view class="c-title">{{detail.address_info.user_name}}</view>
			</view>
			<view class="flex-between mt-md">
				<view>联系方式</view>
				<view class="c-title">{{detail.address_info.mobile}}</view>
			</view>
			<view class="mt-md">
				<view>服务地址</view>
				<view class="flex-center">
					<view class="c-title mt-sm flex-1 mr-md">
						{{`${detail.address_info.address}${detail.address_info.address_info}`}}
					</view>
					<view @tap="toMap" class="flex-center flex-column f-icontext" :style="{color:primaryColor}">
						<i class="iconfont icon-dingwei" style="font-size: 42rpx;"></i>
						<view>立刻导航去</view>
					</view>
				</view>
			</view>
			<view class="mt-md" v-if="detail.text">
				<view>订单备注</view>
				<view class="c-title mt-sm">{{detail.text}}</view>
			</view>
		</view>

		<view class="mt-md ml-lg mr-lg pd-lg fill-base f-paragraph c-caption radius-16">
			<view class="flex-between mt-md">
				<view>下单时间</view>
				<view class="c-title">{{detail.create_time}}</view>
			</view>
			<view class="flex-between mt-md">
				<view>服务时间</view>
				<view class="c-title">{{detail.start_time}}</view>
			</view>
			<view class="flex-between mt-md">
				<view>服务时长</view>
				<view class="c-title">{{detail.time_long}}分钟</view>
			</view>
			<view class="flex-between mt-md">
				<view>车费详情</view>
				<view class="flex-y-center c-title">{{carType[detail.car_type]}}
					<view class="ml-md" v-if="detail.car_type == 1">全程{{detail.distance}}</view>
				</view>
			</view>
			<view class="flex-between mt-md" v-if="detail.car_type == 1">
				<view>出行费用</view>
				<view class="c-warning">出租车 ¥{{detail.car_price}}</view>
			</view>
			<view class="flex-between mt-md">
				<view>服务项目费用</view>
				<view class="c-warning">¥{{detail.init_service_price}}</view>
			</view>
			<view class="flex-between mt-md" v-if="detail.discount*1 > 0">
				<view>卡券优惠</view>
				<view class="c-warning">-¥{{detail.discount}}</view>
			</view>
			<view class="flex-between mt-md">
				<view>支付方式</view>
				<view class="flex-y-baseline c-title"><i class="iconfont mr-sm" :class="payType[detail.is_balance].icon"
						:style="{color:detail.is_balance == 1 ?  primaryColor : ''}"></i>{{payType[detail.is_balance].text}}
				</view>
			</view>
			<view class="flex-between mt-md pt-md b-1px-t">
				<view></view>
				<view class="flex-y-baseline c-title">总计：<view class="c-warning">¥{{detail.pay_price}}</view>
				</view>
			</view>
		</view>

		<view class="mt-md ml-lg mr-lg pd-lg fill-base f-paragraph c-caption radius-16">
			<view class="flex-between pb-lg c-title">订单编号：{{detail.order_code}}
			</view>
			<timeline :list="lineList" :info="detail"></timeline>
		</view>

		<view class="space-max-footer"></view>
		<view class="footer-info fix fill-base" v-if="statusPayType.includes(detail.pay_type)">
			<view class="flex-between pd-lg">
				<view></view>
				<view class="flex-center f-desc c-title">
					<!-- // pay_type 2待接单，5待服务，6服务中，7服务完成 -->
					<!-- 待接单 -->
					<block v-if="detail.pay_type == 2">
						<button @tap.stop="toRefuse" class="clear-btn order">拒绝接单</button>
						<button @tap.stop="toConfirm(3)" class="clear-btn order"
							:style="{color:'#fff',background:primaryColor,borderColor:primaryColor}">确认接单</button>
					</block>
					<!-- 待服务 -->
					<block v-if="detail.pay_type == 3 || detail.pay_type == 4 || detail.pay_type == 5">
						<button @tap.stop="toTel" class="clear-btn order">咨询</button>
						<button @tap.stop="toConfirm(detail.pay_type*1+1 )" class="clear-btn order"
							:style="{color:'#fff',background:primaryColor,borderColor:primaryColor}">{{detail.pay_type == 3 ? '已出发': detail.pay_type == 4 ?'拍照确认到达' : '开始服务'}}</button>
					</block>
					<!-- 服务中 -->
					<block v-if="detail.pay_type == 6">
						<button @tap.stop="toConfirm(7)" class="clear-btn order"
							:style="{color:'#fff',background:primaryColor,borderColor:primaryColor}">完成服务</button>
					</block>
				</view>
			</view>
			<view class="space-safe"></view>
		</view>

		<uni-popup ref="refuse_item" type="center" :custom="true">
			<view class="common-popup-content fill-base pd-lg radius-34">
				<view class="title">拒绝接单</view>
				<view class="desc">请确认是否拒接接单</view>
				<textarea v-model="coach_refund_text" class="pd-lg textarea f-desc c-title mt-lg radius-20"
					maxlength="200" placeholder="请输入拒单原因" placeholder-class="f-desc c-caption"></textarea>
				<view class="flex-center mt-md" style="width: 540rpx">
					<view class="flex-1"></view>
					<view>{{coach_refund_text.length>200?200:coach_refund_text.length}}/200</view>
				</view>
				<view class="button">
					<view @tap.stop="$refs.refuse_item.close()" class="item-child">取消</view>
					<view @tap.stop="confirmRefuse" class="item-child c-base"
						:style="{background: primaryColor,color:'#fff'}">确定</view>
				</view>
			</view>
		</uni-popup>

	</view>
</template>

<script>
	import {
		mapState,
		mapActions,
		mapMutations
	} from "vuex"
	import timeline from '@/components/timeline.vue'
	export default {
		components: {
			timeline
		},
		data() {
			return {
				options: {},
				statusPayType: [2, 3, 4, 5, 6],
				statusType: {
					'-1': '已拒单',
					2: '待接单',
					3: '已接单',
					4: '已出发',
					5: '已到达',
					6: '服务中',
					7: '已完成',
				},
				carType: {
					0: '公交/地铁',
					1: '出租车'
				},
				payType: {
					0: {
						icon: 'iconweixinzhifu1 c-success',
						text: '微信支付'
					},
					1: {
						icon: 'iconqianbao',
						text: '账户余额'
					},
				},
				lineList: [{
					pay_type: 3,
					title: '技师接单',
					time: 'receiving_time',
					icon: 'iconjishijiedan'
				}, {
					pay_type: 4,
					title: '技师出发',
					time: 'serout_time',
					icon: 'iconjishichufa'
				}, {
					pay_type: 5,
					title: '技师到达',
					time: 'arrive_time',
					icon: 'iconjishidaoda'
				}, {
					pay_type: 6,
					title: '开始服务',
					time: 'start_service_time',
					icon: 'iconjishifuwu'
				}, {
					pay_type: 7,
					title: '服务完成',
					time: 'order_end_time',
					icon: 'iconjishiwancheng'
				}],
				detail: {
					pay_type: 0
				},
				popupInfo: {},
				coach_refund_text: '',
				lockTap: false
			}
		},
		computed: mapState({
			primaryColor: state => state.config.configInfo.primaryColor,
			subColor: state => state.config.configInfo.subColor,
			configInfo: state => state.config.configInfo,
			userInfo: state => state.user.userInfo,
			over_time_text() {
				return new Date().getTime() + this.detail.end_time * 1000
			}
		}),
		onLoad(options) {
			this.options = options
			this.initIndex()
			// this.toPlayAudio1(2)
		},
		onUnload(){
			this.toPlayAudio(true)
		},
		methods: {
			...mapActions(['getConfigInfo','toPlayAudio']),
			...mapMutations(['']),
			async initIndex(refresh = false) {
				// #ifdef H5
				if (!refresh && this.$jweixin.isWechat()) {
					await this.$jweixin.initJssdk();
					this.$jweixin.wxReady(() => {
						this.$jweixin.hideOptionMenu()
					})
				}
				// #endif
				if (!this.configInfo.id || refresh) {
					await this.getConfigInfo()
				}
				let {
					id
				} = this.options
				let data = await this.$api.order.orderInfo({
					id
				})
				this.$util.setNavigationBarColor({
					bg: this.primaryColor
				})
				data.is_balance = data.balance * 1 > 0 ? 1 : 0
				let {
					pay_type,
					time_long,
					start_service_time,
				} = data
				if (pay_type == 6) {
					data.start_service_time_unix = this.$util.DateToUnix(start_service_time) + time_long * 60
				}
				this.detail = data
			},
			initRefresh() {
				this.initIndex(true)
			},
			countEnd() {
				this.$util.log("倒计时完了")
				setTimeout(() => {
					this.initRefresh()
					this.$util.back()
				}, 1000)
			},
			// 拒绝接单
			async toRefuse() {
				this.coach_refund_text = ''
				this.$refs.refuse_item.open()
			},
			// 确认：拒绝接单
			async confirmRefuse() {
				let {
					coach_refund_text
				} = this
				coach_refund_text = coach_refund_text.length > 0 ? coach_refund_text.replace(/(^\s*)|(\s*$)/g, "") : ''
				if (coach_refund_text.length == 0) {
					this.$util.showToast({
						title: `请输入拒单原因`
					})
					return
				}
				this.coach_refund_text = this.coach_refund_text.substring(0, 200)
				this.toConfirm(-1)
			},
			// type: -1拒绝接单，3确定接单，4已出发，5已到达，6开始服务，7完成服务
			async toConfirm(type) {
				let {
					id: order_id,
				} = this.detail
				let param = {
					order_id,
					type
				}
				if (type == -1) {
					param.coach_refund_text = this.coach_refund_text
				}
				if (type == 5 || type == 7) {
					let [res_upload, {
						tempFiles = [],
						tempFilePath = ''
					}] = await uni.chooseImage({
						count: 1,
						sourceType: ['camera'],
					})

					let {
						attachment_path
					} = await this.$api.base.uploadFile({
						filePath: tempFiles[0].path,
						filetype: 'picture'
					})
					if (!attachment_path) return
					// this.$util.showToast({
					// 	title: `获取定位中，请耐心等待～`
					// })
					// #ifdef H5
					if (this.$jweixin.isWechat()) {
						this.$util.showLoading()
						// await this.$jweixin.initJssdk();
						await this.$jweixin.wxReady2();
						let {
							latitude: lat = 0,
							longitude: lng = 0
						} = await this.$jweixin.getWxLocation()
						if (!lat) {
							this.$util.hideAll()
							this.$util.showToast({
								title: `请授权定位当前地址`
							})
							return
						}
						if (lat && lng) {
							let key = `${lat},${lng}`
							let data = await this.$api.base.getMapInfo({
								location: key
							})
							let {
								status,
								result
							} = JSON.parse(data)
							if (status == 0) {
								let {
									address
								} = result
								this.toConfirmUpdate(type, param, {
									lat,
									lng,
									address,
									attachment_path
								})
							}
						}
					}
					// #endif
					// #ifndef H5
					let {
						lat = '',
							lng = '',
							address = ''
					} = await this.$util.getBmapLocation()
					if (!lat) {
						this.$util.showToast({
							title: `请授权定位当前地址`
						})
						return
					}
					this.toConfirmUpdate(type, param, {
						lat,
						lng,
						address,
						attachment_path
					})
					// #endif
				} else {
					this.toConfirmUpdate(type, param)
				}
			},
			async toConfirmUpdate(type, param, location = {}) {
				if (type == 5 || type == 7) {
					let {
						lat,
						lng,
						address,
						attachment_path
					} = location
					if (type == 5) {
						param.arrive_img = attachment_path
						param.arr_lat = lat
						param.arr_lng = lng
						param.arr_address = address
					} else {
						param.end_img = attachment_path
						param.end_lat = lat
						param.end_lng = lng
						param.end_address = address
					}
				}
				let msg = {
					'-1': '已拒绝接单',
					3: '接单成功',
					4: '已成功出发',
					5: '已成功到达',
					6: '已开始服务',
					7: '服务已完成'
				}
				if (this.lockTap) return;
				this.lockTap = true;
				this.$util.showLoading()
				try {
					await this.$api.technician.updateOrder(param)
					if (type == -1) {
						this.$refs.refuse_item.close()
						// this.$util.back()
					}
					this.$util.hideAll()
					this.$util.showToast({
						title: msg[type]
					})
					this.lockTap = false;
					this.initRefresh()
					this.$util.back()
				} catch (e) {
					setTimeout(() => {
						this.lockTap = false
						this.$util.hideAll()
					}, 2000)
					return
				}
			},
			// 咨询
			toTel() {
				let {
					mobile: url
				} = this.detail.address_info
				this.$util.goUrl({
					url,
					openType: `call`
				})
			},
			// 查看定位
			async toMap(key) {
				let {
					address,
					address_info,
					lat,
					lng
				} = this.detail.address_info
				await this.$util.checkAuth({
					type: 'userLocation'
				})
				await uni.getLocation({
					type: 'gcj02',
				})
				await uni.openLocation({
					latitude: lat * 1,
					longitude: lng * 1,
					name: `${address} ${address_info}`,
					scale: 28
				})
			},
		}
	}
</script>


<style lang="scss">
</style>
