<!-- 申请退款页 -->
<template>
	<view>
		<view class="edgeInsetTop"></view>
		<!-- 商品信息 -->
		<view class="bg-white padding-bj flex">
			<view class="cu-avatar xl margin-right-bj" :style="{backgroundImage: 'url(' + $appKit.oss(goods.image, 70, 70) + ')'}"></view>
			<view class="text-sm" style="width: calc(100% - 128rpx);">
				<view class="margin-bottom-xs">
					<view class="text-cut-2">{{ goods.title }}</view>
				</view>
				<view class="wanl-gray">{{$t('cart.spec')}}：{{ goods.difference }}</view>
			</view>
		</view>

		<!-- 退款表单 -->
		<view class="margin-top-bj">
			<view class="cu-form-group">
				<view class="title">{{$t('apply.logisticsStatus')}}</view>
				<picker @change="expressChange" :value="refund.expressType" :range="expressList">
					<view class="picker">
						<text v-if="refund.expressType > -1">{{ expressList[refund.expressType] }}</text>
						<text class="wanl-gray-light" v-else>{{$t('apply.whetherReceived')}}</text>
					</view>
				</picker>
			</view>
			<view class="cu-form-group">
				<view class="title">{{$t('apply.refundType')}}</view>
				<picker @change="typeChange" :value="refund.type" :range="typeList">
					<view class="picker">
						<text v-if="refund.type > -1">{{ typeList[refund.type] }}</text>
						<text class="wanl-gray-light" v-else>{{$t('apply.selectRefundType')}}</text>
					</view>
				</picker>
			</view>
			<view class="cu-form-group">
				<view class="title">{{$t('apply.refundReason')}}</view>
				<picker @change="reasonChange" :value="refund.reason" :range="reasonList">
					<view class="picker">
						<text v-if="refund.reason > -1">{{ reasonList[refund.reason] }}</text>
						<text class="wanl-gray-light" v-else>{{$t('apply.pleaseSelectReason')}}</text>
					</view>
				</picker>
			</view>
			<view class="cu-form-group margin-top-bj">
				<view class="title">{{$t('apply.refundAmount')}}</view>
				<input type="digit" :placeholder="amount.placeholder" @input="moneyInput" :disabled="amount.total == 0" />
			</view>

			<!-- 上傳憑證 -->
			<view class="bg-white margin-top-bj">
				<view class="cu-form-group">
					<view class="title">{{$t('apply.uploadProof')}}</view>
				</view>
				<view class="grid col-4 grid-square flex-sub padding-lr">
					<view class="bg-img" v-for="(item, index) in refund.images" :key="index" @tap="viewImage(index)">
						<image :src="item" mode="aspectFill"></image>
						<view class="cu-tag bg-red" @tap.stop="delImg(index)"><text class="wlIcon-31guanbi"></text></view>
					</view>
					<view class="dashed" @tap="chooseImage" v-if="refund.images.length < 4">
						<text class="wlIcon-31paishe"></text>
					</view>
				</view>
			</view>

			<view class="cu-form-group margin-top-bj">
				<view class="title">{{$t('apply.refundDescription')}}</view>
				<input :placeholder="$t('apply.optional')" v-model="refund.refund_content" />
			</view>
		</view>

		<view class="edgeInsetBottom"></view>
		<!-- 提交按鈕 -->
		<view class="wanlian cu-bar tabbar foot flex flex-direction">
			<button class="cu-btn wanl-bg-orange lg" @tap="addData">{{$t('apply.confirm')}}</button>
		</view>
	</view>
</template>

<script>
import { postRefundApply } from '@/features/mall/mall-gateway'

export default {
	data() {
		return {
			freight_type: 0,
			goods: {},
			goods_number: 0,
			refund: {
				order_id: 0,
				order_type: 'goods',
				expressType: -1,
				type: -1,
				reason: -1,
				goods: 0,
				money: 0,
				images: [],
				refund_content: ''
			},
			amount: {
				total: 0,
				placeholder: '',
				info: ''
			}
		}
	},
	computed: {
		expressList() {
			return [this.$t('apply.notReceived'), this.$t('apply.received')]
		},
		typeList() {
			return [this.$t('apply.refundOnly'), this.$t('apply.refundAndReturn')]
		},
		reasonList() {
        return [this.$t('apply.dislike'), this.$t('apply.emptyPackage'), this.$t('apply.notDelivered'), this.$t('apply.colorSizeMismatch'), this.$t('apply.qualityIssue'), this.$t('apply.missingItems'), this.$t('apply.counterfeitBrand')]
    }
	},
	onLoad(option) {
		let data = JSON.parse(option.data)
		this.goods = data.goods
		this.refund.order_id = data.order_id
		this.refund.order_type = data.order_type
		this.refund.goods = data.goods.id
		this.freight_type = data.freight_type
		this.goods_number = data.goods_number
		// 計算退款金額
		if (this.goods_number == 1 || this.freight_type == 2) {
			let price = this.bcadd(data.goods.actual_payment, data.goods.freight_price)
			this.amount.placeholder = this.$t('apply.maxRefundAmount', { price })
			this.amount.total = Number(price)
		} else {
			let price = data.goods.actual_payment
			this.amount.placeholder = this.$t('apply.maxRefundAmount', { price })
			this.amount.total = Number(price)
		}
	},
	methods: {
		/** 提交退款申請 */
		async addData() {
			if (this.refund.money > this.amount.total) {
				uni.showToast({ title: this.amount.info || this.$t('apply.refundAmountExceedsLimit'), icon: 'none' })
				return
			}
			if (this.refund.expressType == -1) {
				uni.showToast({ title: this.$t('apply.pleaseSelectLogistics'), icon: 'none' })
				return
			}
			if (this.refund.type == -1) {
				uni.showToast({ title: this.$t('apply.pleaseSelectRefundType'), icon: 'none' })
				return
			}
			if (this.refund.reason == -1) {
				uni.showToast({ title: this.$t('apply.pleaseSelectReason'), icon: 'none' })
				return
			}
			uni.showLoading({ title: '提交中' })
			try {
				const res = await postRefundApply(this.refund)
				uni.hideLoading()
				uni.navigateTo({ url: `/pages/user/refund/details?id=${res}` })
			} catch (e) {
				uni.hideLoading()
				uni.showToast({ title: '提交失敗', icon: 'none' })
			}
		},

		/** 選擇圖片 */
		chooseImage() {
			uni.chooseImage({
				count: 4,
				sizeType: ['original', 'compressed'],
				sourceType: ['album'],
				success: res => {
					for (let i = 0; i < res.tempFilePaths.length; i++) {
						this.refund.images.push(res.tempFilePaths[i])
					}
				}
			})
		},

		expressChange(e) { this.refund.expressType = e.detail.value },
		typeChange(e) { this.refund.type = e.detail.value },
		reasonChange(e) { this.refund.reason = e.detail.value },

		/** 退款金額輸入 */
		moneyInput(e) {
			let money = e.detail.value
			if (money > this.amount.total) {
				uni.showToast({ title: this.$t('apply.refundAmountCannotExceed'), icon: 'none' })
			}
			this.refund.money = e.detail.value
		},

		/** 預覽圖片 */
		viewImage(key) {
			uni.previewImage({ urls: this.refund.images, current: this.refund.images[key] })
		},

		/** 刪除圖片 */
		delImg(key) {
			this.refund.images.splice(key, 1)
		},

		/** 精確加法 */
		bcadd(a, b) {
			let r1, r2, m
			try { r1 = a.toString().split('.')[1].length } catch (e) { r1 = 0 }
			try { r2 = b.toString().split('.')[1].length } catch (e) { r2 = 0 }
			m = Math.pow(10, Math.max(r1, r2))
			return (a * m + b * m) / m
		}
	}
}
</script>

<style scoped>
.edgeInsetTop { height: var(--status-bar-height); }
.dashed::after { border: 1px dashed #666; }
.wanlian.cu-bar.tabbar.foot { background: rgba(255, 255, 255, 0.96) !important; backdrop-filter: blur(10px); border-top: 1px solid rgba(0, 0, 0, 0.06); }
.wanlian.cu-bar.tabbar.foot .cu-btn { width: calc(100% - 50rpx); background: linear-gradient(135deg, #ff6b35, #ff3d2e) !important; border: none !important; color: #fff !important; font-size: 32rpx; height: 86rpx; }
.wanl-bg-orange { background: linear-gradient(135deg, #ff6b35, #ff3d2e) !important; color: #fff !important; }
.wanl-gray-light { color: #9ca3af; }
.wanl-gray { color: #667085; }
.edgeInsetBottom { height: 100rpx; }
</style>