<script setup>
	// 发起售后

	import {
		reactive,
		ref,
		computed,
	} from 'vue';
	import {
		onLoad,
		onUnload,
		onReachBottom,
		onPullDownRefresh,
		onPageScroll
	} from '@dcloudio/uni-app';
	import {
		useStore
	} from 'vuex';
	// api
	import api from '@/api/index.js'
	// util
	import util from '@/common/js/util';
	// 物流信息
	import logisticsVue from '@/components/shop/order/logistics';
	// 仓库
	const store = useStore();

	// 订单详情
	const detail = reactive({
		createTime: '',
		coutDownTime: '',
		// 订单商品列表信息
		orderDetailList: [],
		// 物流信息
		logistics: {
			info: [],
		},
	})
	// 物流信息
	const logistics = computed(() => detail.logistics.info ? detail.logistics.info[0] : {
		logisticsTraceDetailList: []
	})
	// 订单id
	const orderId = ref('')
	// 当前模式 select选择 form表单
	const mode = ref('select')
	// 类型列表
	const typeList = computed(() => {
		let result = []

		// 待收货
		if ([4].includes(detail.status)) {
			result.push({
				type: 1,
				name: '我要退款(无需退货)',
				text: '未收到货，或与商家协商之后申请',
			})
		}

		// 已收货 及后面的状态
		if ([5, 6].includes(detail.status)) {
			result.push({
				type: 2,
				name: '已收到货，我要退货退款',
				text: '已收到货，需要退还已收到的货物',
			})
		}
		return result
	})
	// 退款列表
	const typeIndex = ref('')
	// 申请原因列表
	const reasonList = reactive([])
	// 申请原因下标
	const reasonIndex = ref('')
	// 表单
	const form = reactive({
		// 退款说明
		refundReasonContent: '',
		// 退款图片
		refundReasonWapImg: [],
	})
	// 用户信息
	const userinfo = computed(() => store.state.userinfo)

	onLoad((option) => {
		if (option.orderId) orderId.value = option.orderId
		// 获取订单详情
		getDetail()
		// 获取分类字典
		getDictList()
	})

	// 获取分类字典
	function getDictList() {
		api.getDict({
			path: ['refund_reason'],
		}).then(res => {
			if (res.code == 200) {
				Object.assign(reasonList, {}, res.data)
				return
			}
			util.alert({
				content: res.msg,
				showCancel: false,
			})
		})
	}

	// 获取订单详情
	function getDetail() {
		api.shop.getOrderDetail({
			query: {
				id: orderId.value
			}
		}).then(res => {
			if (res.code == 200) {
				let result = res.data
				result.status = Number(result.status)
				Object.assign(detail, {}, result)
				return
			}
			util.alert({
				content: res.msg,
				showCancel: false,
			})
		})
	}
	/**
	 * 选择售后
	 * @param {Object} index 选择的下标
	 */
	function handleType(index) {
		if (typeIndex.value === index) return
		typeIndex.value = index
		mode.value = 'form'
		uni.setNavigationBarTitle({
			title: '申请售后',
		})
	}

	/**
	 * 原因切换
	 * @param {Object} event 默认事件
	 */
	function handleReason(event) {
		let index = event.detail.value
		if (reasonIndex.value === index) return
		reasonIndex.value = index
	}

	// 图片上传
	function uploadImg() {
		util.upload_image({
			count: 1,
			success: (res) => {
				form.refundReasonWapImg.push(res.value)
			}
		})
	}

	/**
	 * @param {Object} index
	 */
	function handleRemoveImg(index) {
		util.alert({
			content: '确定删除该图片吗？',
			success: (res) => {
				if (!res.confirm) return
				form.refundReasonWapImg.splice(index, 1)
			}
		})
	}

	/**
	 * 订单发起售后
	 * @param {Object} event 事件对象
	 */
	function handleSubmit() {
		const data = {
			...form
		}

		// 验证必填项
		if (reasonIndex.value === '') {
			util.alert('请选择退款原因')
			return
		}
		if (!data.refundReasonContent) {
			util.alert('申请说明不能为空')
			return
		}
		// 图片
		if (data.refundReasonWapImg) data.refundReasonWapImg = data.refundReasonWapImg.join(',')

		// 
		api.shop.orderAfterSales({
			data: {
				// 订单
				orderId: detail.id,
				// 售后类型：1-仅退款，2-退货退款
				afterSalesType: typeList.value[typeIndex.value].type,
				// 退款原因-数据字典refund_reason
				refundReasonWap: reasonList[reasonIndex.value].dictLabel,
				// 退款图片
				refundReasonWapImg: data.refundReasonWapImg,
				// 退款内容
				refundReasonContent: data.refundReasonContent,
			},
		}).then(res => {
			if (res.code == 200) {
				// 触发自定义事件
				uni.$off('updateOrderList')
				uni.$off('updateOrderDetail')
				uni.navigateBack()
				return
			}
			util.alert({
				content: res.msg,
				showCancel: false,
			})
		})
	}
</script>

<template>
	<view class="app">
		<template v-if="mode === 'select'">
			<view class="detail">
				<logisticsVue :logistics="logistics" :detail="detail" />
			</view>

			<!-- 列表类型 -->
			<view class="typeList plr20">
				<view class="list rows mtb30 ptb30 plr20 bfff br10" v-for="(item,index) in typeList" :key="index"
					@click="handleType(index)">
					<image class="wh45" src="/static/shop-sales.png" mode="aspectFit" />
					<view class="col f1 ml30">
						<view class="c333 f32">{{item.name}}</view>
						<view class="txt mt10 c999 f28">{{item.text}}</view>
					</view>
				</view>
			</view>
		</template>

		<template v-else-if="mode === 'form'">
			<!-- 商品信息 -->
			<view class="goods df mtb20 ptb20 plr20 bfff" v-for="(item,index) in detail.orderDetailList">
				<!-- 产品图 -->
				<image class="wh180 br10" :src="item.productInfo.sliderImage.split(',')[0]" mode="aspectFill" />
				<!-- 产品信息 -->
				<view class="f1 ml20 mr10">
					<view class="name f30 t2hd">{{item.productName}}</view>
					<view class="spec mt10 c999 f26">升级款 {{item.sku}}</view>
				</view>
				<!-- 其他 -->
				<view class="tar">
					<view class="price">
						<text class="f20">￥</text>
						<text class="f30">{{item.price}}</text>
					</view>
					<view class="c999 f28">x{{item.payNum}}</view>
				</view>
			</view>

			<!-- 申请信息 -->
			<view class="apply container">
				<view class="line ptb20">
					<picker :range="typeList" :value="typeIndex" range-key="name"
						@change="handleType($event.detail.value)">
						<view class="rows">
							<view class="key">申请类型</view>
							<view class="value f1 mlr20">{{typeList[typeIndex].name}}</view>
							<uni-icons type="right" color="#999" />
						</view>
					</picker>
				</view>

				<view class="line ptb20">
					<picker :range="reasonList" range-key="dictLabel" @change="handleReason($event,'reasonIndex')">
						<view class="rows">
							<view class="key">申请原因</view>
							<view class="value f1 mlr20">
								<text v-if="reasonIndex !== ''">{{reasonList[reasonIndex].dictLabel}}</text>
								<text v-else class="placeholderStyle">点击选择申请原因</text>
							</view>
							<uni-icons type="right" color="#999" />
						</view>
					</picker>
				</view>
			</view>

			<!-- 申请金额 -->
			<view class="price container ptb30">
				<view class="title f30">申请金额</view>
				<view class="value df mt10 c333 f60">
					<text>￥</text>
					<text class="input f1 c333 f60">{{detail.totalPrice}}</text>
					<!-- <input type="text" class="input f1 c333 f60" :value="89" /> -->
				</view>
			</view>

			<!-- 申请说明 -->
			<view class="form container">
				<view class="title mtb20 f30">申请说明</view>
				<textarea type="text" class="input mtb20 c333 f30" placeholder="必填,请您详细填写申请说明"
					v-model="form.refundReasonContent" placeholder-class="placeholderStyle" auto-height="true" />

				<view class="imgList df fww">
					<view class="imgs" v-for="(item,index) in form.refundReasonWapImg" :key="index">
						<image class="wh140" :src="item" mode="aspectFill" />
						<view class="close" @click="handleRemoveImg(index)">
							<uni-icons type="clear" color="#f00" size="40rpx" />
						</view>
					</view>
					<view class="imgs upload wh140" @click="uploadImg">
						<image class="wh140" src="/static/shop-upload-image.png" mode="aspectFill" />
					</view>
				</view>
			</view>

			<view class="other container">
				<view class="line df mtb30">
					<view class="key w200">联系电话</view>
					<view class="value f1">{{userinfo.phoneNumber}}</view>
				</view>
			</view>

			<view class="fill" style="height: 120rpx;"></view>

			<view class="footer plr30 bfff shadow">
				<view class="btn lg primary" @click="handleSubmit">提交申请</view>
			</view>
		</template>
	</view>
</template>

<style lang="scss" scoped>
	.container {
		overflow: hidden;
		margin: 20rpx 0;
		padding-left: 20rpx;
		padding-right: 20rpx;
		color: #333;
		font-size: 32rpx;
		background-color: #fff;
	}

	// 
	.apply {
		.line+.line {
			border-top: 2rpx solid #eee;
		}
	}
</style>