<template>
    <view class="apply-container">
        <!-- 确认退款信息弹窗 -->
        <view class="refund-info-container">
            <view class="refund-item">
                <view class="refund-label">服务类型<text class="required">*</text></view>
                <view class="refund-value" @click="openAfterSalePopup2('serviceType')">
                    {{ selectedServiceType || '请选择服务类型' }}
                    <text class="arrow-right"></text>
                </view>
            </view>
            <view class="refund-item">
                <view class="refund-label">退款原因<text class="required">*</text></view>
                <view class="refund-value" @click="openAfterSalePopup2('refundReason')">
                    {{ selectedRefundReason || '请选择退款原因' }}
                    <text class="arrow-right"></text>
                </view>
            </view>
            <view class="refund-item" style="border-bottom: none;">
                <view class="refund-label">退款金额<text class="required">*</text></view>
                <view class="refund-value">
                    <text class="price">¥{{ refundAmount || '0.00' }}</text>
                    <text class="modify-btn" @click="modifyRefundAmount">修改</text>
                    <view class="refund-hint">可修改，最多¥{{ maxRefundAmount || '0.00' }}，含发货邮费¥{{ postage || '0.00' }}
                    </view>
                </view>
            </view>
            <view class="hr"></view>
            <view class="refund-item2">
                <view class="refund-label">补充描述和凭证</view>
                <textarea class="refund-description" placeholder="补充描述，有助于商家更好的处理售后问题" v-model="refundDescription"
                    maxlength="200"></textarea>
                <u-upload :fileList="imgList" @afterRead="afterReadImg" @delete="deletePic" name="1" multiple
                    :maxCount="3">
                    <view class="imgCon">
                        <image
                            src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/property-img-file/com_imageImg.png"
                            mode="widthFix"></image>
                        上传凭证
                    </view>
                </u-upload>
            </view>
            <view class="hr"></view>
            <view class="refund-item">
                <view class="refund-label">退款方式</view>
                <view class="refund-value" style="margin-bottom: 10rpx;">
                    {{ refundMethod || '自行寄回' }}
                    <view class="refund-hint">您可自行安排将商品退回商家</view>
                </view>
            </view>
            <view class="refund-item">
                <view class="refund-label">商家地址</view>
                <view class="refund-value" @click="viewAddressDetails">
                    {{ merchantAddress || '未设置' }}
                    <text class="arrow-right"></text>
                </view>
            </view>
            <view class="contact-info">
                <text>{{ merchantContact || '未设置' }}</text>
            </view>
        </view>
        <button class="submit-btn" @click="submitRefundApplication">提交申请</button>

        <!-- 选择退款原因弹窗 -->
        <u-popup ref="popup2" :show="afterSalePopup2" :round="10" @close="closeAfterSalePopup2"
            :mask-close-able="false">
            <view class="cancel-reason-container">
                <view class="title">选择退款原因</view>
                <view class="asTabs2">
                    <view :class="['asTab2', selectedAfterSaleType2 === 0 ? 'active' : '']"
                        @click="selectAfterSaleType2(0)">
                        退货退款</view>
                    <view :class="['asTab2', selectedAfterSaleType2 === 1 ? 'active' : '']"
                        @click="selectAfterSaleType2(1)">
                        退款
                    </view>
                </view>
                <view class="reason-list" v-if="selectedAfterSaleType2 === 0">
                    <view v-for="(reason, index) in applyRefundReasons" :key="index" class="reason-item"
                        @click="selectAsReason(index)">
                        <view :class="['radio', selectedAsReason === index ? 'active' : '']"></view>
                        <text>{{ reason }}</text>
                    </view>
                </view>
                <view class="reason-list" v-if="selectedAfterSaleType2 === 1">
                    <view v-for="(reason, index) in cancelReasons" :key="index" class="reason-item"
                        @click="selectAsReason(index)">
                        <view :class="['radio', selectedAsReason === index ? 'active' : '']"></view>
                        <text>{{ reason }}</text>
                    </view>
                </view>
                <button class="confirm-btn" @click="confirmAfterSaleCancel2">确定</button>
            </view>
        </u-popup>
    </view>
</template>

<script>
import {
    isPhone,
    picUrl,
    request,
    upload,
    NavgateTo
} from '../../../utils';
import { apiArr } from "../../../api/afterSale";


export default {
    data() {
        return {
            currentAfterSale: null,
            afterSalePopup2: false,
            selectedAfterSaleType2: 0, // 0:退货/退款, 1:退款
            selectedAsReason: 0,
            selectedServiceType: '',
            selectedRefundReason: '',
            refundAmount: 0,
            maxRefundAmount: 0,
            postage: 0,
            refundDescription: '',
            refundMethod: '自行寄回',
            merchantAddress: '',
            merchantContact: '',
            imgList: [],
            afterSalesType: 2,
            applyRefundReasons: [
                '商品质量问题',
                '商品与描述不符',
                '商品破损',
                '商品错发/漏发',
                '其他原因'
            ],
            cancelReasons: [
                '不想要了',
                '拍错了',
                '商品质量问题',
                '其他原因'
            ]
        };
    },
    onLoad(options) {
        const item = JSON.parse(options?.item);
        console.log("🚀 ~ onLoad ~ item:", item)
        this.currentAfterSale = item;
        // 设置初始退款金额等数据
        if (item) {
            this.refundAmount = item.refund_amount || 0;
            this.maxRefundAmount = item.sales_price || 0;
            this.merchantAddress = item.supplier_address || '未设置';
            this.merchantContact = `${item.supplier_name} ${item.supplier_phone}` || '未设置';
        }
    },
    methods: {
        // 关闭弹窗
        closeAfterSalePopup2() {
            this.afterSalePopup2 = false;
        },

        // 选择售后类型
        selectAfterSaleType2(index) {
            if (index == 0) {
                this.afterSalesType = 2;
            } else {
                this.afterSalesType = 1;
            }
            this.selectedAfterSaleType2 = index;
        },

        // 选择退款原因
        selectAsReason(index) {
            this.selectedAsReason = index;
        },

        // 确认退款原因选择
        confirmAfterSaleCancel2() {
            const afterSaleTypes = ['退货退款', '退款'];
            const selectedType = afterSaleTypes[this.selectedAfterSaleType2];
            console.log('选中的售后类型:', selectedType);

            let selectedReasonText = '';
            if (selectedType == '退货退款') {
                selectedReasonText = this.applyRefundReasons[this.selectedAsReason];
            } else {
                selectedReasonText = this.cancelReasons[this.selectedAsReason];
            }
            console.log('退款原因:', selectedReasonText);

            // 设置选中的服务类型和退款原因
            this.selectedServiceType = selectedType;
            this.selectedRefundReason = selectedReasonText;

            this.selectAsReason(0);
            this.afterSalePopup2 = false;
        },

        // 打开选择服务类型或退款原因弹窗
        openAfterSalePopup2(type) {
            this.afterSalePopup2 = true;
        },

        // 上传图片
        afterReadImg(e) {
            e.file.forEach(item => {
                upload(item.url, res => {
                    this.imgList.push({ url: picUrl + res.data.path });
                    console.log('imgList:', this.imgList);
                });
            });
        },

        // 删除图片
        deletePic(e) {
            this.imgList.splice(e.index, 1);
        },

        // 修改退款金额
        modifyRefundAmount() {
            console.log('修改退款金额');
        },

        // 查看地址详情
        viewAddressDetails() {
            console.log('查看地址详情');
        },

        // 提交修改申请
        submitRefundApplication() {
            if (!this.selectedServiceType || !this.selectedRefundReason) {
                uni.showToast({
                    title: '请选择服务类型和退款原因',
                    icon: 'none'
                });
                return;
            }

            const params = {
                id: this.currentAfterSale.id,
                after_sales_type: this.afterSalesType,
                after_sales_reason: this.selectedRefundReason,
                refund_amount: this.refundAmount,
                application_description: this.refundDescription,
                application_images: this.imgList && this.imgList.length > 0 ?
                    this.imgList.map(img => img.url).join(',') : '',
                receiving_address: this.merchantAddress
            }
            console.log("🚀 ~ submitRefundApplication ~ params:", params)
            request(apiArr.updateApply, "POST", params).then((res) => {
                uni.showToast({
                    title: '申请提交成功',
                    icon: 'success'
                });

                // 构造更新后的数据
                const updatedAfterSale = {
                    ...this.currentAfterSale,
                    after_sales_type: this.afterSalesType,
                    after_sales_reason: this.selectedRefundReason,
                    refund_amount: this.refundAmount,
                    application_description: this.refundDescription,
                    application_images: this.imgList && this.imgList.length > 0 ?
                        this.imgList.map(img => img.url).join(',') : ''
                };

                setTimeout(() => {
                    this.currentAfterSale = updatedAfterSale;
                    uni.setStorageSync('afterSaleItem', updatedAfterSale);
                }, 1500);
            });
        }
    }
};
</script>

<style>
@import url('./index.css');
</style>