<template>
    <view>
        <!-- 选择售后商品 -->
        <view>
            <u-popup ref="popup" :show="afterSalePopup" :round="10" @close="closeAfterSalePopup"
                :mask-close-able="false">
                <view class="cancel-reason-container">
                    <view class="title">选择退款原因</view>
                    <view class="asType">
                        <text>请选择售后类型</text>
                        <view class="asTabs">
                            <view :class="['asTab', selectedAfterSaleType === 0 ? 'active' : '']"
                                @click="selectAfterSaleType(0)">
                                退货/退款</view>
                            <view :class="['asTab', selectedAfterSaleType === 1 ? 'active' : '']"
                                @click="selectAfterSaleType(1)">换货
                            </view>
                        </view>
                    </view>
                    <view class="asGoodsInfo" v-for="(item, index) in afterSaleGoods" :key="index">
                        <view class="asGoodInfo" @click="selectAsGood(item)">
                            <view :class="['radio asGoodRadio', selectedAsGood == item.goods_id ? 'active' : '']">
                            </view>
                            <view class="asGoodTag tag-img" v-if="item.is_support_same_day === 1">当日达</view>
                            <image :src="item.commodity_pic" class="asGoodImg"></image>
                            <view class="asGoodDetail">
                                <view class="asGoodTitle">
                                    <text class="asGoodTag asGoodTag1" v-if="item.is_support_same_day === 1">当日达</text>
                                    {{ item.goods_name }}
                                </view>
                                <view class="asGoodDesc">{{ item.goods_spec }}</view>
                                <view class="asGoodPrice">¥{{ item.cost_price }}/个</view>
                            </view>
                            <view class="asGoodNum">x{{ item.count }}</view>
                        </view>
                    </view>
                    <button class="confirm-btn" @click="confirmAfterSaleCancel">下一步</button>
                </view>
            </u-popup>
        </view>

        <!------------------------ 退货退款逻辑 ------------------------>
        <!-- 选择退款原因 -->
        <view v-if="selectedAfterSaleType === 0">
            <u-popup ref="popup" :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>
        <!-- 确认退款信息 -->
        <view v-if="selectedAfterSaleType === 0">
            <u-popup ref="popup" :show="afterSalePopup3" :round="10" @close="closeAfterSalePopup3"
                :mask-close-able="false">
                <view class="refund-info-container">
                    <view class="refund-title">确认退款信息</view>
                    <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: 30rpx;">
                            {{ 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>
                    <button class="submit-btn" @click="submitRefundApplication">提交申请</button>
                </view>
            </u-popup>
        </view>

        <!------------------------ 换货逻辑 ------------------------>
        <!-- 选择退款原因 -->
        <view v-if="selectedAfterSaleType === 1">
            <u-popup ref="popup" :show="afterSalePopup2" :round="10" @close="closeAfterSalePopup2"
                :mask-close-able="false">
                <view class="cancel-reason-container">
                    <view class="title">选择换货原因</view>
                    <view class="reason-list">
                        <view v-for="(reason, index) in exchangeReasons" :key="index" class="reason-item"
                            @click="selectReason(index)">
                            <view :class="['radio', selectedReason === index ? 'active' : '']"></view>
                            <text>{{ reason }}</text>
                        </view>
                    </view>
                    <button class="confirm-btn" @click="confirmChange">下一步</button>
                </view>
            </u-popup>
        </view>
        <!-- 确认退款信息 -->
        <view v-if="selectedAfterSaleType === 1">
            <u-popup ref="popup" :show="afterSalePopup3" :round="10" @close="closeAfterSalePopup3"
                :mask-close-able="false">
                <view class="refund-info-container">
                    <view class="refund-title">申请退换</view>
                    <view class="refund-item">
                        <view class="refund-label">换货原因<text class="required">*</text></view>
                        <view class="refund-value" @click="openAfterSalePopup2('refundReason')">
                            {{ changeRefundReason || '请选择退换原因' }}
                            <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="changeGood()">
                            {{ changeServiceName || '请选择需要换的商品' }}
                            <text class="arrow-right"></text>
                        </view>
                    </view>
                    <view class="text-wrapper_8">
                        <text class="text_41">{{ orderItem.receiving_name }}</text>
                        <text class="text_42">{{ orderItem.receiving_phone }}</text>
                    </view>
                    <view class="block_15">
                        <view class="address-view">
                            <text> {{ orderItem.receiving_address }} </text>
                            <view class="copy-icon" @click="copyRefundNo"></view>
                        </view>
                        <image src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/af_update_address.png"
                            class="icon_2"></image>
                    </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>
                    <button class="submit-btn" @click="submitRefundApplication">提交申请</button>
                </view>
            </u-popup>
        </view>

        <!-- 选择商品 -->
        <u-popup :show="showSize" round="20rpx" mode="bottom" @close="closeSize">
            <view class="popup-header">
                <h3 class="popup-header-h3">选择款式</h3>
                <view class="popup-header-view" @click="closeSize">取消</view>
            </view>
            <view class="itemSize_top">
                <image :src="currentGG.commodity_pic" class="itemSize-img"></image>
                <view class="itemSize_info">
                    <view class="itemSize_name">{{ currentGG.goods_name }}</view>
                    <view class="itemSize_price">￥{{ currentGG.sales_price }}/{{ currentGG.goods_unit }}
                    </view>
                </view>
            </view>
            <view class="itemSize" v-for="(item, index) in changeGoodsList" :key="item.id"
                @click="changeGG(item, index)" :class="index == currentGGIndex ? 'itemSize_active' : ''">
                {{ item.goods_name }} {{ item.goods_spec }} / {{ item.goods_unit }}
            </view>
        </u-popup>
    </view>
</template>

<script>

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

export default {
    name: 'AfterSalePopup',
    props: {
        orderItem: {
            type: Object,
            default: () => ({})
        },
        afterSaleGoods: {
            type: Array,
            default: () => []
        }
    },
    data() {
        return {
            afterSalePopup: false,
            afterSalePopup2: false,
            afterSalePopup3: false,
            selectedAsGood: '',
            selectedAfterSaleType: 0, // 0:退货/退款, 1:换货
            selectedAfterSaleType2: 0, // 0:退货/退款, 1:退款
            selectedAsReason: 0,
            selectedReason: 0,//换货原因
            selectedServiceType: '',
            selectedRefundReason: '',
            changeRefundReason: '', // 换货原因回显
            changeServiceName: '', // 换货商品回显
            changeServiceId: '', // 换货商品id
            changeGoodsList: [], // 换货商品列表
            showSize: false,//选择款式弹窗
            currentGG: {},//当前选择的款式
            currentGGIndex: 0,
            afterSalesType: 2, // 服务类型 1:仅退款 2:退货退款 3:换货

            merchantContact: '', // 商家信息
            merchantAddress: '', // 商家地址

            refundDescription: '',
            refundMethod: '自行寄回',
            imgList: [],
            applyRefundReasons: [
                '商品质量问题',
                '商品与描述不符',
                '商品破损',
                '商品错发/漏发',
                '其他原因'
            ],
            cancelReasons: [
                '不想要了',
                '拍错了',
                '商品质量问题',
                '其他原因'
            ],
            exchangeReasons: [
                '不想要了，无理由换货',
                '商品信息拍错',
                '没用/少用优惠',
                '缺货',
                '其他'
            ],
        };
    },
    methods: {
        // 打开售后弹窗
        openAfterSalePopup() {
            this.$nextTick(() => {
                if (this.afterSaleGoods && this.afterSaleGoods.length > 0) {
                    this.selectedAsGood = this.afterSaleGoods[0].goods_id;
                    this.afterSalePopup = true;
                }
            })
        },

        // 选择售后商品
        selectAsGood(item) {
            this.selectedAsGood = item.goods_id;
        },

        // 关闭弹窗
        closeAfterSalePopup() {
            this.afterSalePopup = false;
        },

        // 关闭弹窗
        closeAfterSalePopup() {
            this.afterSalePopup = false;
        },

        closeAfterSalePopup2() {
            if (this.selectedReason !== null && this.selectedReason !== undefined) {
                this.changeRefundReason = this.exchangeReasons[this.selectedReason];
            }
            this.afterSalePopup2 = false;
        },

        closeAfterSalePopup3() {
            this.afterSalePopup3 = false;
        },

        // 选择售后类型
        selectAfterSaleType(index) {
            if (index === 1) {
                this.afterSalesType = 3;
            }
            this.selectedAfterSaleType = index;
        },

        selectAfterSaleType2(index) {
            if(index === 1) {
                this.afterSalesType = 1;
            }else{
                this.afterSalesType = 2;
            }
            this.selectedAfterSaleType2 = index;
        },

        // 确认售后商品选择
        confirmAfterSaleCancel() {
            const afterSaleTypes = ['退货/退款', '换货'];
            const selectedType = afterSaleTypes[this.selectedAfterSaleType];
            console.log('售后商品 - 选中的售后类型:', selectedType);
            console.log('选中的售后商品:', this.selectedAsGood);

            this.merchantContact = `${this.orderItem.supplier_name} ${this.orderItem.supplier_phone}`;
            this.merchantAddress = this.orderItem.supplier_address;

            this.afterSalePopup = false;
            this.afterSalePopup2 = true;
        },

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

        // 换货原因
        selectReason(index) {
            this.selectedReason = index;
        },

        // 选择换货原因
        confirmChange() {
            let selectedReasonText = '';
            selectedReasonText = this.exchangeReasons[this.selectedReason];
            console.log('换货原因:', selectedReasonText);

            // 将选中的换货原因赋值给changeRefundReason变量以回显
            this.changeRefundReason = selectedReasonText;

            this.afterSalePopup2 = false;
            this.afterSalePopup3 = true;
        },

        // 关闭换货原因弹窗时保存选择
        closeAfterSalePopup2() {
            if (this.selectedReason !== null && this.selectedReason !== undefined) {
                this.changeRefundReason = this.exchangeReasons[this.selectedReason];
            }
            this.afterSalePopup2 = false;
        },

        // 确认退款原因选择
        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;
            this.afterSalePopup3 = true;
        },

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

        // 选择换货商品
        changeGood() {
            const params = {
                goods_id: this.selectedAsGood,
            }
            request(apiArr.changeGoodsList, "POST", params).then((res) => {
                res.change_goods_list.forEach(item => {
                    item.commodity_pic = picUrl + item.commodity_pic;
                })
                this.changeGoodsList = res.change_goods_list;
                console.log("🚀 ~ changeGood ~ this.currentGG:", this.currentGG)
                if (!this.currentGG.goods_name) {
                    this.currentGG = this.changeGoodsList.find(item => item.id == this.selectedAsGood);
                    this.currentGGIndex = this.changeGoodsList.indexOf(this.currentGG);
                    this.changeServiceName = this.currentGG.goods_name
                    this.changeServiceId = this.currentGG.id
                }

                this.afterSalePopup3 = false;
                this.showSize = true;
            });
        },

        closeSize() {
            this.showSize = false;
        },

        // 切换规格
        changeGG(item, index) {
            this.currentGG = item;
            this.currentGGIndex = index;
            this.changeServiceName = this.currentGG.goods_name
            this.changeServiceId = this.currentGG.id

            this.afterSalePopup3 = true;
            this.showSize = false;
        },

        // 上传图片
        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.afterSalesType !== 3) {
                if (!this.selectedServiceType || !this.selectedRefundReason) {
                    uni.showToast({
                        title: '请选择服务类型和退款原因',
                        icon: 'none'
                    });
                    return;
                }
            }

            // 输出弹窗中的所有内容
            const refundInfo = {
                afterSalesType: this.afterSalesType,
                serviceType: this.selectedServiceType,
                refundReason: this.selectedRefundReason || this.changeRefundReason,
                refundAmount: this.orderItem.total_amount,
                maxRefundAmount: this.orderItem.total_amount,
                postage: 0, // 假设邮费为0
                refundDescription: this.refundDescription,
                refundMethod: this.refundMethod,
                merchantAddress: this.orderItem.supplier_address,
                merchantContact: `${this.orderItem.supplier_name} ${this.orderItem.supplier_phone}`,
                imgList: this.imgList,
                changeServiceId: this.changeServiceId,
            };
            console.log('提交退款申请:', refundInfo);

            this.afterSalePopup3 = false;
            // 触发父组件事件，传递退款信息
            this.$emit('refundSubmitted', refundInfo);
            
            // 重置弹窗中的数据为默认值
            this.resetAfterSaleData();
        },
        
        // 重置售后数据为默认值
        resetAfterSaleData() {
            this.selectedAsGood = '';
            this.selectedAfterSaleType = 0; // 0:退货/退款, 1:换货
            this.selectedAfterSaleType2 = 0; // 0:退货/退款, 1:退款
            this.selectedAsReason = 0;
            this.selectedReason = 0; // 换货原因
            this.selectedServiceType = '';
            this.selectedRefundReason = '';
            this.changeRefundReason = ''; // 换货原因回显
            this.changeServiceName = ''; // 换货商品回显
            this.changeServiceId = ''; // 换货商品id
            this.changeGoodsList = []; // 换货商品列表
            this.currentGG = {}; // 当前选择的款式
            this.currentGGIndex = 0;
            this.refundDescription = '';
            this.imgList = [];
        },
    }
};
</script>

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