<!-- 客服 -->
<template>
    <el-card style="margin-bottom: 0.5vh;background-color: rgb(243,250,254);">
        <div class="condition">
            <div class="item1">
                <el-text size="large" style="width:4vw;">{{ t('common.jwcode') }}</el-text>
                <el-input v-model="searchForm.jwcode" :placeholder="t('common.jwcodePlaceholder')" style="width:9vw;"
                    clearable />
            </div>
            <div class="item1">
                <el-text size="large" style="width:4vw;">{{ t('common.customerName') }}</el-text>
                <el-input v-model="searchForm.name" :placeholder="t('common.customerNamePlaceholder')"
                    style="width:9vw;" clearable />
            </div>
            <div class="item1">
                <el-text size="large" style="width:4vw;">{{ t('common.productName') }}</el-text>
                <el-cascader v-model="searchForm.goodsName" :props="{ multiple: false, emitPath: false }" :show-all-levels="false" :options="productList" style="width: 10vw;" :placeholder="t('common.productNamePlaceholder')" clearable />
            </div>
            <div class="item1" v-if="isHeadquarters">
                <el-text size="large" style="width:4vw;">{{ t('common.market') }}</el-text>
                <el-cascader style="width: 9vw;" v-model="searchForm.market" :options="market"
                    :placeholder="t('common.marketPlaceholder')" clearable @change="handleMarketChange" />
            </div>
            <div class="item1">
                <el-text size="large" style="width:4vw;" multiple>{{ t('common.orderStatus') }}</el-text>
                <el-select v-model="searchForm.statuses" style="width:9vw;" clearable>
                    <el-option v-for="item in statusList" :key="item" :label="item" :value="item" />
                </el-select>
            </div>
        </div>
        <div class="condition">
            <div class="item2">
                <el-text size="large" style="width:4vw;">{{ t('common.payCurrency') }}</el-text>
                <el-select v-model="searchForm.paymentCurrency" style="width:9vw;" clearable>
                    <el-option v-for="item in currencies" :key="item" :label="item" :value="item" />
                </el-select>
            </div>
            <div class="item2">
                <el-text size="large" style="width:4vw;">{{ t('common.payModel') }}</el-text>
                <el-select v-model="searchForm.payType" style="width:9vw;" clearable>
                    <el-option v-for="item in channelOptions" :key="item" :label="item" :value="item" />
                </el-select>
            </div>
            <div class="item2" style="width: 28.5vw;">
                <el-text size="large" style="width:4vw;">{{ t('common.payTime') }}</el-text>
                <el-date-picker v-model="dateRange" type="datetimerange" :range-separator="t('common.to')"
                    :start-placeholder="t('common.startTime')" :end-placeholder="t('common.endTime')"
                    style="width:22vw;" :disabled-date="disabledDate" :default-time="defaultTime" clearable />
            </div>
            <div>
                <el-button type="primary" @click="getRefund">{{ t('common.search') }}</el-button>
                <!-- <el-button type="warning">导出excel</el-button>
                <el-button type="primary">查看导出列表</el-button> -->
                <el-button type="success" @click="reset">{{ t('common.reset') }}</el-button>
            </div>
        </div>
    </el-card>

    <el-card style="margin-top: 0.5vh;background-color: rgb(231,244,253);">
        <el-table ref="tableRef" :data="tableData" style="height:73vh;width:82vw;background-color: rgb(243,250,254);">
            <el-table-column type="index" :label="t('common_list.id')" width="60" fixed="left">
                <template #default="scope">
                    {{ scope.$index + 1 + (pagination.pageNum - 1) * pagination.pageSize }}
                </template>
            </el-table-column>
            <el-table-column prop="jwcode" label="Homily ID" width="120" fixed="left" />
            <el-table-column prop="name" :label="t('common_list.name')" width="120" fixed="left"
                show-overflow-tooltip />
            <el-table-column prop="marketName" :label="t('common_list.market')" width="120" />
            <el-table-column prop="activity" :label="t('common_list.activity')" width="120px" show-overflow-tooltip />
            <el-table-column prop="goodsName" :label="t('common_list.productName')" width="130" show-overflow-tooltip />
           <el-table-column prop="goodsNum" :label="t('common_list.productNum')" width="130px">
                            <template #default="scope">
                                <span v-if="scope.row.goodsName == t('common_list.goldRecharge')">{{
                                    scope.row.permanentGold }} {{ t('cash.unit') }}</span>
                                <span v-else>{{ scope.row.goodsNum }} {{ scope.row.numUnit }}</span>
                            </template>
            </el-table-column>
            <el-table-column prop="paymentCurrency" :label="t('common_add.payCurrency')" width="120" />
            <el-table-column prop="paymentAmount" :label="t('common_add.payAmount')" width="120" />
            <el-table-column prop="payType" :label="t('common_add.payMethod')" width="140" />
            <el-table-column prop="payTime" :label="t('common_add.payTime')" width="180" />
            <el-table-column prop="voucher" :label="t('common_add.transferVoucher')" width="110px">
                <template #default="scope">
                    <div v-if="scope.row.voucher"
                        style="display: flex; justify-content: center; align-items: center; cursor: pointer;"
                        @click="previewImage(scope.row.voucher)">
                        <img :src="scope.row.voucher" alt="转账凭证" style="width: auto; height: 40px;">
                    </div>
                    <div v-else style="display: flex; justify-content: center; align-items: center; height: 40px;">{{
                        t('common_add.noTransferVoucher') }}
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="remark" :label="t('common_list.remark')" width="150" show-overflow-tooltip />
            <el-table-column prop="status" :label="t('common_list.orderStatus')" width="120">
                <template #default="scope">
                    {{
                        [10].includes(scope.row.status) ? t('cash.statusList.submitted') :
                            [20, 30, 40].includes(scope.row.status) ? t('cash.statusList.inProgress') :
                                [12, 22, 32].includes(scope.row.status) ? t('cash.statusList.rejected') :
                                    [11].includes(scope.row.status) ? t('cash.statusList.recalled') :
                                        scope.row.status === 41 ? t('cash.statusList.refunded') : scope.row.status
                    }}
                </template>
            </el-table-column>
            <el-table-column prop="operation" :label="t('common_list.operation')" fixed="right" width="140px">
                <template #default="scope">
                    <div class="operation">
                        <!-- <el-button v-if="scope.row.status === 10" type="primary" text
                            @click="showBackDialog(scope.row)">
                            {{ t('common.withdraw') }}
                        </el-button> -->
                        <el-button v-if="scope.row.status === 11" type="primary" text
                            @click="showEditDialog(scope.row)">
                            {{ t('common.edit') }}
                        </el-button>
                        <el-button v-if="[12, 22, 32].includes(scope.row.status)" type="primary" text
                            @click="showRejectReasonDialog(scope.row)">
                            {{ t('common.viewRejectReason') }}
                        </el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination v-model:current-page="pagination.pageNum" v-model:page-size="pagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
            @size-change="handlePageSizeChange" @current-change="handleCurrentChange"
            style="margin-top: 1vh;"></el-pagination>
    </el-card>

    <el-dialog v-model="showEdit" :title="t('common_add.refund')" class="editDialog" overflow draggable
        style="width: 40vw; background-color: #F3FAFE !important;">
        <div style="display: flex;">
            <div class="left">
                <div class="add-item">
                    <el-text style="width:4vw;">{{ t('common_add.jwcode') }}</el-text>
                    <el-input v-model="editRow.jwcode" style="width:10vw;" disabled />
                </div>
                <div class="add-item">
                    <el-text style="width:4vw;">{{ t('common_add.customerName') }}</el-text>
                    <el-input v-model="editRow.name" style="width:10vw;" disabled />
                </div>
                <div class="add-item">
                    <el-text style="width:4vw;">{{ t('common_add.market') }}</el-text>
                    <el-input v-model="editRow.marketName" style="width:10vw;" disabled />
                </div>
                <div class="add-item">
                    <el-text style="width:4vw;">{{ t('common_add.activity') }}</el-text>
                    <el-input v-model="editRow.activity" style="width:10vw;" disabled />
                </div>
                <div class="add-item">
                    <el-text style="width:4vw;">{{ t('common_add.productName') }}</el-text>
                    <el-input v-model="editRow.goodsName" style="width:10vw;" disabled />
                </div>
                <div class="add-item" v-if="editRow.goodsName !== t('cash.coinRecharge')">
                    <el-text style="width:4vw;">{{ t('common_add.productNum') }}</el-text>
                    <el-input v-model="editRow.goodsNum" style="width:10vw;" disabled />
                    &nbsp;{{ editRow.numUnit }}
                </div>
                <div class="add-item" v-if="editRow.goodsName == t('cash.coinRecharge')">
                    <el-text style="width:4vw;">{{ t('refund.permanentGold') }}</el-text>
                    <el-input v-model="editRow.gold" style="width:10vw;" disabled />
                    &nbsp;{{ t('cash.unit') }}
                </div>
                <div class="add-item" v-if="editRow.goodsName == t('cash.coinRecharge')">
                    <el-text style="width:4vw;">{{ t('refund.freeGold') }}</el-text>
                    <el-input v-model="editRow.free" style="width:10vw;" disabled />
                    &nbsp;{{ t('cash.unit') }}
                </div>
                <div class="add-item">
                    <el-text style="width:4vw;">{{ t('common_add.payCurrency') }}</el-text>
                    <el-input v-model="editRow.paymentCurrency" style="width:10vw;" disabled />
                </div>
                <div class="add-item">
                    <el-text style="width:4vw;">{{ t('common_add.payAmount') }}</el-text>
                    <el-input v-model="editRow.paymentAmount" style="width:10vw;" disabled />
                </div>
                <div class="add-item">
                    <el-text style="width:4vw;">{{ t('common_add.payMethod') }}</el-text>
                    <el-input v-model="editRow.payType" style="width:10vw;" disabled />
                </div>
                <div class="add-item">
                    <el-text style="width:4vw;">{{ t('common_add.payTime') }}</el-text>
                    <el-date-picker v-model="editRow.payTime" type="datetime" style="width:10vw;" disabled />
                </div>
                <div class="add-item">
                    <el-text style="width:4vw;">{{ t('common_add.transferVoucher') }}</el-text>
                    <img v-if="editRow.voucher" :src="editRow.voucher"
                        style="width: 80px; height: 80px; object-fit: cover;">
                    <div v-else>
                        {{ t('common_add.noTransferVoucher') }}
                    </div>
                </div>
                <div class="add-item">
                    <el-text style="width:4vw;">{{ t('common_add.remark') }}</el-text>
                    <el-input v-model="editRow.remark" style="width:10vw;" :rows="3" type="textarea" maxLength="100"
                        disabled show-word-limit />
                </div>
            </div>
            <div class="right">
                <div class="add-item">
                    <el-text style="width:4vw;">{{ t('common_add.refundType') }}</el-text>
                    <el-radio-group v-model="editForm.refundModel">
                        <el-radio value="0">{{ t('common_add.refundModelAll') }}</el-radio>
                        <el-radio value="1">{{ t('common_add.refundModelPart') }}</el-radio>
                    </el-radio-group>
                </div>
                <div class="add-item" v-show="editRow.goodsName == t('cash.coinRecharge') && editForm.refundModel === '1'">
                    <el-text style="width:4vw;">{{ t('common_add.permanentGold') }}</el-text>
                    <el-input v-model="editForm.partRefundGold" style="width:5vw;" />&nbsp;&nbsp;{{ t('cash.unit') }}
                </div>
                <div class="add-item" v-show="editRow.goodsName == t('cash.coinRecharge') && editForm.refundModel === '1'">
                    <el-text style="width:4vw;">{{ t('common_add.freeGold') }}</el-text>
                    <el-input v-model="editForm.partRefundFree" style="width:5vw;" />&nbsp;&nbsp;{{ t('cash.unit') }}
                </div>
                <div class="add-item">
                    <el-text style="width:4vw;">{{ t('common_add.refundReason') }}</el-text>
                    <el-input v-model="editForm.refundReason" style="width:10vw;" :rows="5" maxlength="150"
                        show-word-limit type="textarea" />
                </div>
                <div>{{ t('common_add.tip') }}</div>
                <div style="display:flex;justify-content: center;margin-top: 5vh;">
                    <el-button type="default" @click="cancelEdit">{{ t('common.cancel') }}</el-button>
                    <el-button type="primary" @click="submitEdit">{{ t('common.submit') }}</el-button>
                </div>
            </div>
        </div>
    </el-dialog>

    <ConfirmDialog v-model="showBack" :message="t('common.willRecallOrder')" @confirm="recall"
        @cancel="showBack = false" @close="showBack = false" />

    <el-dialog v-model="showError" overflow draggable class="back-dialog" :style="{
        backgroundImage: `url(${RefundRecallBackground})`,
        backgroundSize: 'cover',
        backgroundPosition: 'center'
    }">
        <div class="back-text">{{ t('elmessage.refundAmountError') }}</div>
        <div class="back-btn">
            <el-button type="default" @click="showError = false">{{ t('common.cancel') }}</el-button>
            <el-button type="primary" @click="" style="margin-left: 2vw;">{{ t('common.confirm') }}</el-button>
        </div>
    </el-dialog>

    <el-dialog v-model="showRejectReason" :title="t('common.viewRejectReason')" width="40%" style="background-color: rgb(243,250,254);">
        <div>{{ rejectReason }}</div>
    </el-dialog>
</template>
<script setup>
import { ref, onMounted, computed, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import API from '@/util/http.js'
const uploadUrl = 'https://api.homilychart.com/hljw/api/aws/upload'
import { useAdminStore } from "@/store/index.js"
import { storeToRefs } from "pinia"
import dayjs from 'dayjs'
const adminStore = useAdminStore()
const { adminData, menuTree } = storeToRefs(adminStore)
import { permissionMapping, findMenuById, hasMenuPermission } from "@/utils/menuTreePermission.js"
import ConfirmDialog from '@/components/dialogs/ConfirmDialog.vue'
import { pa } from 'element-plus/es/locales.mjs'
import { productList, CurrencyForId } from '@/views/moneyManage/receiveDetail/utils/staticData.js'
import RefundRecallBackground from '@/assets/images/refund-recall.png'
import { isNumber } from 'lodash'
import { re } from 'mathjs'
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
const isHeadquarters = computed(() => {
    const m = adminData.value.markets
    return m === t('common.markets.headquarters') || m === '总部' || m === 'Headquarters'
})

const dateRange = ref([])
const searchForm = ref({
    jwcode: '',
    market: [],
    statuses: [],
    goodsName: []
})
const market = ref([])
const backRow = ref({})// 撤回存数据
const editRow = ref({})// 编辑存数据
const rejectReason = ref('')// 驳回理由
const showRejectReason = ref(false)
const editForm = ref({
    refundModel: '',
    refundReason: ''
})
const auditForm = ref({
    refundType: ''
})
const pagination = ref({
    pageNum: 1,
    pageSize: 50,
    total: 0
})
const tableData = ref([])
const tableRef = ref(null)
const scrollTableTop = () => {
    tableRef.value?.setScrollTop?.(0)
}
const showEdit = ref(false)
const uploadRef = ref(null)
const showBack = ref(false)
const showError = ref(false)
const isKF = adminData.value.adminName.includes('客服')
const statusList = computed(() => [
    t('cash.statusList.submitted'),
    t('cash.statusList.recalled'),
    t('cash.statusList.inProgress'),
    t('cash.statusList.refunded'),
    t('cash.statusList.rejected')
])
// 查全部
const getRefund = async function () {
    if (!hasMenuPermission(menuTree.value, permissionMapping.view_customer_service_refund_pending)) {
        ElMessage.error(t('elmessage.noPermission'))
        return
    }
    try {
        const statusParam = ref([])
        if (searchForm.value.statuses === t('cash.statusList.submitted')) {
            statusParam.value = [10]
        } else if (searchForm.value.statuses === t('cash.statusList.recalled')) {
            statusParam.value = [11]
        } else if (searchForm.value.statuses === t('cash.statusList.inProgress')) {
            statusParam.value = [20, 30, 40]
        } else if (searchForm.value.statuses === t('cash.statusList.refunded')) {
            statusParam.value = [41]
        } else if (searchForm.value.statuses === t('cash.statusList.rejected')) {
            statusParam.value = [12, 22, 32]
        }

        console.log('goodsName', searchForm.value.goodsName);
        
        let goodsName = searchForm.value.goodsName && searchForm.value.goodsName.length > 0
            ? [searchForm.value.goodsName] : []

        if (searchForm.value.jwcode) {
            const isPositiveInteger = /^[1-9]\d*$/.test(searchForm.value.jwcode);
            if (!isPositiveInteger) {
                ElMessage.error(t('elmessage.checkJwcodeFormat'))
                return;
            }
        }
        // 增加精网号长度限制，防止后端400错误
        if (searchForm.value.jwcode.length > 8) {
            ElMessage.error(t('elmessage.limitJwcodeLength'))
            return;
        }

        const params = {
            pageNum: pagination.value.pageNum,
            pageSize: pagination.value.pageSize,
            cashRecordDTO: {
                jwcode: searchForm.value.jwcode,//精网号
                name: searchForm.value.name,//姓名
                markets: searchForm.value.market && searchForm.value.market.length > 0 ? [searchForm.value.market[searchForm.value.market.length - 1]] : [],
                goodsNames: goodsName,//商品名
                statuses: statusParam.value,//10：地区财务待审核；12：地区财务驳回；
                // 20：地区负责人待审核；22：地区负责人驳回；
                // 30：总部财务待审核；32：总部财务驳回；
                // 40：执行人待处理；41：执行人已处理，退款完成；
                paymentCurrency: CurrencyForId(searchForm.value.paymentCurrency),//付款币种
                payType: searchForm.value.payType,//支付方式
                startTime: dateRange.value && dateRange.value[0] ? dayjs(dateRange.value[0]).format('YYYY-MM-DD HH:mm:ss') : "",
                endTime: dateRange.value && dateRange.value[1] ? dayjs(dateRange.value[1]).format('YYYY-MM-DD HH:mm:ss') : "",
                submitterId: adminData.value.id
            }
        }

        const result = await API({
            url: '/Money/selecta',
            method: 'POST',
            data: params
        })

        tableData.value = result.data.list || []
        await nextTick()
        scrollTableTop()
        pagination.value.total = result.data.total || 0
    } catch (error) {
        ElMessage.error(error.message || t('elmessage.searchFailed'))
    }
}
// 撤回
const recall = async function () {
    if (!hasMenuPermission(menuTree.value, permissionMapping.withdraw_customer_service_refund)) {
        ElMessage.error(t('elmessage.noPermission'))
        return
    }
    try {
        console.log(backRow.value)
        const params = {
            id: backRow.value.id,
            status: backRow.value.status,
            orderType: backRow.value.orderType
        }
        const result = await API({
            url: '/Money/update',
            data: params
        })
        if (result.code === 200) {
            ElMessage.success(result.msg || t('elmessage.withdrawSuccess'))
            showBack.value = false
            getRefund()
        } else {
            ElMessage.error(result.msg || t('elmessage.operationFailed'))
        }
    } catch (error) {
        ElMessage.error(error.message || t('elmessage.operationFailed'))
    }
}
// 编辑
const submitEdit = async function () {
    if (!hasMenuPermission(menuTree.value, permissionMapping.edit_customer_service_refund)) {
        ElMessage.error(t('elmessage.noPermission'))
        return
    }
    try {
        console.log(editRow.value)
        if (!editForm.value.refundModel) {
            ElMessage.error(t('elmessage.selectRefundModel'))
            return
        } else if (!editForm.value.refundReason) {
            ElMessage.error(t('elmessage.refundReasonPlaceholder'))
            return
        } else if (editRow.value.goodsName === t('cash.coinRecharge') && editForm.value.refundModel == 1) {
            if (!editForm.value.partRefundGold || !editForm.value.partRefundFree) {
                ElMessage.error(t('elmessage.inputRefundBeansBoth'))
                return
            }
            const isPositiveInteger = /^[0-9]\d*$/.test(editForm.value.partRefundGold)
            if (!isPositiveInteger) {
                ElMessage.error(t('elmessage.checkPermanentFormat'))
                return
            }
            const isPositiveInteger1 = /^[0-9]\d*$/.test(editForm.value.partRefundFree)
            if (!isPositiveInteger1) {
                ElMessage.error(t('elmessage.checkFreeFormat'))
                return
            }
            if(editForm.value.partRefundFree == 0 && editForm.value.partRefundGold == 0){
                ElMessage.error(t('elmessage.checkRefundgolds'))
                return
            }
        }
        let params = {
            id: editRow.value.id,
            status: editRow.value.status,
            refundModel: editForm.value.refundModel,
            refundReason: editForm.value.refundReason,
            jwcode: editRow.value.jwcode,
            paymentAmount: editRow.value.paymentAmount,
            paymentCurrency: editRow.value.paymentCurrency,
            newRefundGold: (editForm.value.partRefundGold * 100),
            newRefundFree: (editForm.value.partRefundFree) * 100

        }
          if(params.refundModel == 0){
              params.newRefundGold = (editRow.value.gold)*100
              params.newRefundFree = (editRow.value.free)*100    
        }
        console.log('params',params);

        if (editRow.value.goodsName != t('cash.coinRecharge')) {
            params.newRefundGold = ''
            params.newRefundFree = ''
        }
        if (editRow.value.goodsName == t('cash.coinRecharge')) {
            if (editForm.value.partRefundGold > editRow.value.gold) {
                ElMessage.error(t('elmessage.limitRefundGoldNotExceedOriginal'))
                return
            }
            if (editForm.value.partRefundFree > editRow.value.free) {
                ElMessage.error(t('elmessage.limitRefundFreeNotExceedOriginal'))
                return
            }
        }
        const result = await API({
            url: '/Money/update',
            data: params
        })
        if (result.code === 200) {
            ElMessage.success(result.msg || t('elmessage.editSuccess'))
            showEdit.value = false
            getRefund()
            cancelEdit()
        } else {
            ElMessage.error(result.msg || t('elmessage.editFailed'))
        }
    } catch (error) {
        ElMessage.error(error.message || t('elmessage.editFailed'))
    }
}
const getMarket = async function () {
    try {
        const result = await API({

            url: '/market/selectMarket',
        })
        console.log('看看地区树', result)

        const transformTree = (nodes) => {
            const allChildren = nodes.flatMap(node => node.children || []);

            return allChildren.map(child => {
                const grandchildren = child.children && child.children.length
                    ? transformTree([child])
                    : null;

                return {
                    value: child.id,
                    label: child.name,
                    children: grandchildren
                };
            });
        };
        market.value = transformTree(result.data)
        console.log('转换后的地区树==============', market.value)
    } catch (error) {
        console.log('请求失败', error)
    }
}

// 预览图片函数
// const previewImage = (imageUrl) => {
//     // 使用 element-plus 的 el-image 组件实现图片预览功能
//     const imageElement = document.createElement('img');
//     imageElement.src = imageUrl;
//     imageElement.style.maxWidth = '80vw';
//     imageElement.style.maxHeight = '80vh';

//     const viewer = document.createElement('div');
//     viewer.style.position = 'fixed';
//     viewer.style.top = '0';
//     viewer.style.left = '0';
//     viewer.style.width = '100vw';
//     viewer.style.height = '100vh';
//     viewer.style.backgroundColor = 'rgba(0, 0, 0, 0.7)';
//     viewer.style.display = 'flex';
//     viewer.style.justifyContent = 'center';
//     viewer.style.alignItems = 'center';
//     viewer.style.zIndex = '9999';
//     viewer.style.overflow = 'auto';

//     viewer.appendChild(imageElement);
//     document.body.appendChild(viewer);

//     viewer.addEventListener('click', () => {
//         document.body.removeChild(viewer);
//     });
// };
const previewImage = (imageUrl) => {
    if (!imageUrl) return;

    const imageElement = document.createElement('img');
    imageElement.src = imageUrl;
    imageElement.style.maxWidth = '90vw';
    imageElement.style.maxHeight = '90vh';
    imageElement.style.display = 'block'; 
    
    imageElement.style.transition = 'transform 0.2s ease-out';
    imageElement.style.cursor = 'zoom-in';
    imageElement.style.transformOrigin = 'center center'; // 缩放中心点

    const viewer = document.createElement('div');
    viewer.style.position = 'fixed';
    viewer.style.top = '0';
    viewer.style.left = '0';
    viewer.style.width = '100vw';
    viewer.style.height = '100vh';
    viewer.style.backgroundColor = 'rgba(0, 0, 0, 0.7)';

    viewer.style.display = 'flex';
    viewer.style.justifyContent = 'center';
    viewer.style.alignItems = 'center';
    
    viewer.style.overflow = 'hidden'; 
    
    viewer.style.zIndex = '999999'; 
    viewer.appendChild(imageElement);

    let currentScale = 1;
    const scaleStep = 0.2; 
    const handleWheel = (e) => {
        e.preventDefault();
        if (e.deltaY > 0) {
            currentScale -= scaleStep; 
        } else {
            currentScale += scaleStep; 
        }
        if (currentScale < 0.5) currentScale = 0.5;
        imageElement.style.transform = `scale(${currentScale})`;
        imageElement.style.cursor = currentScale > 1 ? 'zoom-out' : 'zoom-in';
    };

    viewer.addEventListener('wheel', handleWheel, { passive: false });
    viewer.addEventListener('click', (e) => {
        if (e.target === viewer) {
            document.body.removeChild(viewer);
            viewer.removeEventListener('wheel', handleWheel);
        }
    });

    document.body.appendChild(viewer);
};
const cancelEdit = function () {
    editForm.value = {
        refundModel: '',
        refundReason: '',
        partRefundGold: '',
        partRefundFree: ''
    }
    showEdit.value = false
}
const currencies = computed(() => [
    t('cash.currency.usd'),
    t('cash.currency.hkd'),
    t('cash.currency.sgd'),
    t('cash.currency.myr'),
    t('cash.currency.thb'),
    t('cash.currency.cad'),
    t('cash.currency.vnd'),
    t('cash.currency.krw'),
    t('cash.currency.rmb'),
])
const channelOptions = computed(() => [
  t('cash.payMethods.stripe'),      // Stripe
  t('cash.payMethods.paymentAsia'), // PaymentAsia
  t('cash.payMethods.stripe2'),    // Stripe2
  t('cash.payMethods.ipay88'),      // Ipay88
  t('cash.payMethods.grabpay'),     // Grabpay
  t('cash.payMethods.nets'),        // Nets
  t('cash.payMethods.transfer'),    // E-Transfer
  t('cash.payMethods.paypal'),      // PayPal
  t('cash.payMethods.paysolution'), // Paysolution
  t('cash.payMethods.bankTransfer'),// 银行转账
  t('cash.payMethods.card'),        // 刷卡
  t('cash.payMethods.cash'),        // 现金
  t('cash.payMethods.check'),        // 支票
])

const reset = function () {
    searchForm.value = {
        jwcode: '',
        market: [],
        statuses: [],
        goodsName: []
    }
    // 重置页码
    pagination.value.pageNum = 1
    dateRange.value = []
    getRefund()
}
const showBackDialog = function (row) {
    backRow.value = row
    showBack.value = true
}
const showEditDialog = function (row) {
    editRow.value = row
    showEdit.value = true
}
const handlePageSizeChange = function (val) {
    pagination.value.pageSize = val
    getRefund()
}
const handleCurrentChange = function (val) {
    pagination.value.pageNum = val
    getRefund()
}
const disabledDate = (time) => {
    const limitDate = new Date(2025, 0, 1);
    return time.getTime() < limitDate.getTime();
}
const handleMarketChange = (value) => {
    searchForm.value.market = value || []
}
const defaultTime = [
    new Date(2000, 1, 1, 0, 0, 0),
    new Date(2000, 2, 1, 23, 59, 59),
]
	const showRejectReasonDialog = function (row) {
    rejectReason.value = row.rejectReason
    showRejectReason.value = true
}
onMounted(() => {
    getRefund()
    getMarket()
    console.log('???????????????????', adminData.value)
})
</script>
<style scoped lang="scss">
:deep(.el-table__header-wrapper),
:deep(.el-table__body-wrapper),
:deep(.el-table__cell),
:deep(.el-table__body td) {
    background-color: #F3FAFE !important;
}

:deep(.el-table__header th) {
    background-color: #F3FAFE !important;
}

.condition {
    width: 82vw;
    display: flex;
    align-items: center;
    height: 4vh;

    .item1 {
        width: 18%;
        display: flex;
        align-items: center;
        margin-bottom: 1vh;
        margin-right: 0.5vw;
    }

    .item2 {
        width: 18%;
        display: flex;
        align-items: center;
        margin-right: 0.5vw;
    }
}

.editDialog {
    .left {
        width: 50%;
        height: 70vh;
        padding: 0 2vw;

        .add-item {
            display: flex;
            align-items: center;
            margin-bottom: 1vh;
        }

        .image {
            width: 4vw !important;
            height: 4vw !important;
        }
    }

    .right {
        width: 50%;
        height: 50vh;

        .add-item {
            display: flex;
            align-items: center;
            margin-bottom: 1vh;
        }
    }
}

.back-dialog {
    width: 700px;
    height: auto;

    .back-text {
        font-size: 60px;
        font-weight: bold;
        color: #000000;
        text-align: center;
        justify-content: center;
        margin-top: 22vh;
    }

    .back-btn {
        height: 20vh;
        display: flex;
        justify-content: center;
        align-items: center;
    }
}
</style>
