<template>
    <div class="content">
        <div class="div-card1">
            <el-card class="card1" style="margin-bottom: 0.5vh; min-height: 110px;">
                <div class="row1">
                    <div class="rowItem">
                        <el-text style="width: 4vw;">{{ t('common.jwcode') }}</el-text>
                        <el-input v-model="searchData.jwcode" :placeholder="t('common.jwcodePlaceholder')"
                            style="width:10vw;" clearable></el-input>
                    </div>
                    <div class="rowItem">
                        <el-text style="width: 4vw;">{{ t('common.customerName') }}</el-text>
                        <el-input v-model="searchData.name" :placeholder="t('common.customerNamePlaceholder')"
                            style="width:10vw;" clearable></el-input>
                    </div>
                    <div class="rowItem">
                        <el-text style="width: 4vw;">{{ t('common.market') }}</el-text>
                        <el-cascader style="width: 9vw;" v-model="searchData.markets" :options="market"
                            :placeholder="t('common.marketPlaceholder')" clearable @change="handleMarketChange" />
                    </div>
                    <!-- 地区财务固定显示付款币种，删除客服的订单状态 -->
                    <div class="rowItem">
                        <el-text style="width: 4vw;">{{ t('common.payCurrency') }}</el-text>
                        <el-select v-model="searchData.paymentCurrency"
                            :placeholder="t('common.payCurrencyPlaceholder')" style="width: 10vw;" clearable>
                            <el-option v-for="item in customOptions" :key="item" :label="item" :value="item" />
                        </el-select>
                    </div>
                    <div class="rowItem">
                        <el-text style="width: 4vw;">{{ t('common.payModel') }}</el-text>
                        <el-select v-model="searchData.payType" :placeholder="t('common.payModelPlaceholder')"
                            style="width: 10vw;" clearable>
                            <el-option v-for="item in paytypeList" :key="item" :label="item" :value="item" />
                        </el-select>
                    </div>
                </div>
                <div class="row2" style="margin-top: 10px;">
                    <div class="left">
                        <div class="rowItem">
                            <el-text style="width: 4vw;">{{ t('common.activityName') }}</el-text>
                            <el-select v-model="searchData.activity" :placeholder="t('common.activityNameChoose')"
                                style="width: 10vw;" clearable>
                                <el-option v-for="item in activityList" :key="item.id" :label="item.activityName"
                                    :value="item.id" />
                            </el-select>
                        </div>
                        <div class="rowItem">
                            <el-text style="width: 4vw;">{{ t('common.productName') }}</el-text>
                            <el-cascader v-model="searchData.goodsName" :options="productList" style="width: 10vw;"
                                clearable />
                        </div>
                        <div class="rowItem" style="width: 25vw">
                            <el-text style="width: 4vw; margin-left: 0.5vw;">{{ t('common.payTime') }}</el-text>
                            <el-date-picker v-model="getTime" type="datetimerange" :range-separator="t('common.to')"
                                :start-placeholder="t('common.startTime')" :end-placeholder="t('common.endTime')"
                                style="width: 22vw; " @change="handleDatePickerChange" :default-time="defaultTime"
                                :disabled-date="disabledDate" />
                        </div>
                    </div>
                    <el-button style="width: 3vw;" type="primary" @click="search">{{ t('common.search') }}</el-button>
                    <el-button style="width: 3vw;" type="success" @click="reset">{{ t('common.reset') }}</el-button>
                    <el-button v-if="activeTab == 'done'" style="width: 5vw;" type="warning" @click="exportExcel">{{
                        t('common.exportExcel') }}</el-button>
                    <el-button v-if="activeTab == 'done'" style="width: 6vw;" type="primary" @click="openExportList">{{
                        t('common.viewExportList') }}</el-button>
                </div>
            </el-card>
        </div>


        <div class="div-card2">
            <el-card class="card2">
                <div class="btns">
                    <!-- 地区财务专属标签页（待审核/已通过/已完成/已驳回） -->
                    <div class="tabs">
                        <el-button-group>
                            <el-button class="btnItem"
                                :style="{ backgroundColor: activeTab === 'wait' ? '#2741DE' : '#E5EBFE', color: activeTab === 'wait' ? 'white' : '#666' }"
                                @click="navigateTo('wait')">
                                {{ t('common.pendingAudit') }}
                            </el-button>
                            <el-button class="btnItem"
                                :style="{ backgroundColor: activeTab === 'pass' ? '#2741DE' : '#E5EBFE', color: activeTab === 'pass' ? 'white' : '#666' }"
                                @click="navigateTo('pass')">
                                {{ t('common.passed') }}
                            </el-button>
                            <el-button class="btnItem"
                                :style="{ backgroundColor: activeTab === 'done' ? '#2741DE' : '#E5EBFE', color: activeTab === 'done' ? 'white' : '#666' }"
                                @click="navigateTo('done')">
                                {{ t('common.completed') }}
                            </el-button>
                            <el-button class="btnItem"
                                :style="{ backgroundColor: activeTab === 'reject' ? '#2741DE' : '#E5EBFE', color: activeTab === 'reject' ? 'white' : '#666' }"
                                @click="navigateTo('reject')">
                                {{ t('common.rejected') }}
                            </el-button>
                        </el-button-group>
                        <div class="info-tooltip">
                            <el-popover placement="top" :title="t('cash.receiveCashDataTitle')" :width="260"
                                trigger="hover" :content="t('cash.receiveCashDataContent')"
                                popper-class="custom-popover" :show-arrow="false">
                                <template #reference>
                                    <el-icon class="service-icon">
                                        <Warning />
                                    </el-icon>
                                </template>
                            </el-popover>
                        </div>
                    </div>
                    <!-- 删除客服的“添加收款”按钮 -->
                    <div class="btnAdd"></div>
                </div>

                <div class="table">
                    <el-table :data="tableData" style="width: 80vw;height:64vh;" @sort-change="handleSortChange"
                        :row-style="{ height: '60px' }" :header-cell-style="{ textAlign: 'center' }"
                        :cell-style="{ textAlign: 'center' }">
                        <el-table-column type="index" :label="t('common_list.id')" width="100px" fixed="left">
                            <template #default="scope">
                                <span>{{ scope.$index + 1 + (pageInfo.pageNum - 1) * pageInfo.pageSize }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column fixed="left" prop="jwcode" label="Homily ID" width="110px" />
                        <el-table-column fixed="left" prop="name" :label="t('common_list.name')" width="110px" />
                        <el-table-column prop="marketName" :label="t('common_list.market')" width="80px" />
                        <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="120px" />
                        <el-table-column prop="goodNum" :label="t('common_list.productNum')" width="130px">
                            <template #default="scope">
                                <span v-if="scope.row.goodsName == t('common_list.goldRecharge')">{{
                                    scope.row.permanentGold }}</span>
                                <span v-else>{{ scope.row.goodNum }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="paymentCurrency" :label="t('common_list.payCurrency')" width="120px" />
                        <el-table-column prop="paymentAmount" :label="t('common_list.payAmount')" width="120px" />
                        <!-- 地区财务显示到账币种/金额/手续费（已通过/已完成标签页） -->
                        <el-table-column prop="receivedCurrency" :label="t('common_list.receiveCurrency')"
                            v-if="activeTab == 'pass' || activeTab == 'done'" width="150px"></el-table-column>
                        <el-table-column prop="receivedAmount" :label="t('common_list.receiveAmount')"
                            v-if="activeTab == 'pass' || activeTab == 'done'" width="150px">
                            <template #default="scope">
                                <div v-if="!scope.row.receivedAmount">
                                    <text style="color: #FA5A1E;">{{ t('common_list.toSupply') }}</text>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="handlingCharge" :label="t('common_list.fee')"
                            v-if="activeTab == 'pass' || activeTab == 'done'" width="150px">
                            <template #default="scope">
                                <div v-if="scope.row.handlingCharge == null">
                                    <text style="color: #FA5A1E;">{{ t('common_list.toSupply') }}</text>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="payType" :label="t('common_list.payModel')" width="130px" />
                        <el-table-column prop="payTime" :label="t('common_list.payTime')" width="180px" />
                        <el-table-column prop="voucher" :label="t('common_list.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="t('common_list.payVoucher')"
                                        style="width: auto; height: 40px;">
                                </div>
                                <div v-else
                                    style="display: flex; justify-content: center; align-items: center; height: 40px;">
                                    ——
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="submitterName" :label="t('common_list.submitter')" width="150px"
                            show-overflow-tooltip></el-table-column>
                        <!-- 地区财务显示审核人（已通过/已驳回/已完成标签页） -->
                        <el-table-column prop="auditName" :label="t('common_list.approver')"
                            v-if="activeTab == 'pass' || activeTab == 'reject' || activeTab == 'done'" width="150px"
                            show-overflow-tooltip></el-table-column>
                        <el-table-column prop="receivedTime" :label="t('common_list.receiveTime')"
                            v-if="activeTab == 'pass' || activeTab == 'done'" width="180px" />
                        <el-table-column prop="remark" :label="t('common_list.remark')" v-if="activeTab != 'reject'"
                            width="150px" show-overflow-tooltip></el-table-column>
                        <el-table-column prop="status" fixed="right" :label="t('common_list.orderStatus')"
                            v-if="activeTab == 'done'" width="150px" show-overflow-tooltip>
                            <template #default="scope">
                                <span style="color: rgb(242, 84, 83);" v-if="scope.row.status == 6">{{
                                    t('common_list.refund') }}</span>
                                <span style="color: rgb(127,204,133);" v-else>{{ t('common_list.normal') }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="auditTime" :label="t('common_list.rejectTime')"
                            v-if="activeTab == 'reject'" width="180px" show-overflow-tooltip></el-table-column>
                        <el-table-column prop="rejectReason" :label="t('common_list.rejectReason')"
                            v-if="activeTab == 'reject'" width="150px">
                            <template #default="scope">
                                <div class="ellipsis-container"
                                    @mouseenter="handleMouseEnter($event, scope.row.rejectReason)"
                                    @mouseleave="handleMouseLeave" @mousemove="handleMouseMove($event)">
                                    <span class="ellipsis-text">
                                        {{ scope.row.rejectReason || '—' }}
                                    </span>
                                    <!-- 自定义提示框 -->
                                    <div v-if="showTooltip && tooltipContent" class="custom-tooltip" :style="{
                                        left: `${tooltipLeft}px`,
                                        top: `${tooltipTop}px`
                                    }">
                                        {{ tooltipContent }}
                                    </div>
                                </div>
                            </template>
                        </el-table-column>
                        <!-- 地区财务表格操作（待审核→审核，已通过→编辑） -->
                        <el-table-column fixed="right" :label="t('common_list.operation')" width="120px" v-if="activeTab != 'reject'">
                            <template #default=scope>
                                <el-link v-if="activeTab == 'wait'" style="color: #2741DE;"
                                    @click="openAuditForm(scope.row)">{{ t('common.audit') }}</el-link>
                                <el-link
                                    v-else-if="activeTab == 'pass' && !(scope.row.status == 6 || scope.row.status == 4) && scope.row.receivedMarket == adminData.markets"
                                    style="color: #2741DE;" @click="openEditForm(scope.row)">{{ t('common.edit')
                                    }}</el-link>
                                <el-link
                                    v-else-if="activeTab == 'done' && scope.row.status == 4 && startsWith(scope.row.orderCode, 'GOLDCOIN')"
                                    style="color: rgb(242, 84, 83);" @click="openRefundConfirm(scope.row)">{{
                                    t('common.refund') }}</el-link>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="pagination">
                    <el-pagination background :current-page="pageInfo.pageNum" :page-size="pageInfo.pageSize"
                        :page-sizes="[5, 10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                        :total="total" @size-change="handlePagination('size', $event)"
                        @current-change="handlePagination('page', $event)"></el-pagination>
                </div>
            </el-card>
        </div>
        <!-- 退款确认弹窗 -->
        <div class="recallDialog" v-show="refundConfirmDialog">
            <div class="close">
                <button @click="closeConfirmRefund" class="Btn">{{ t('common.close') }}</button>
            </div>
            <div class="text">
                <text class="txt">{{ textContent }}</text>
            </div>
            <div class="cancle">
                <button @click="closeConfirmRefund" class="Btn">{{ t('common.cancel') }}</button>
            </div>
            <div class="confirm">
                <button @click="openRefundDialog" class="Btn">{{ t('common.confirm') }}</button>
            </div>
        </div>

        <!-- 导出列表 -->
        <el-dialog v-model="exportListVisible" :title="t('common_export.exportList')" width="60vw">
            <el-table :data="exportList" style="width: 100% ;height: 60vh;" :loading="exportListLoading">
                <el-table-column prop="fileName" :label="t('common_export.fileName')" />
                <el-table-column prop="state" :label="t('common_export.status')">
                    <template #default="scope">
                        <el-tag :type="getTagType(scope.row.state)" :effect="scope.row.state === 3 ? 'light' : 'plain'">
                            {{ getTagText(scope.row.state) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" :label="t('common_export.createTime')">
                    <template #default="scope">
                        {{ moment(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
                    </template>
                </el-table-column>
                <el-table-column :label="t('common_export.operation')">
                    <template #default="scope">
                        <el-button type="primary" size="small" @click="downloadExportFile(scope.row)"
                            :disabled="scope.row.state !== 2">
                            {{ t('common_export.download') }}
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <template #footer>
                <div class="dialog-footer">
                    <el-button text @click="exportListVisible = false">{{ t('common_export.close') }}</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 审核弹窗 -->
        <el-dialog class="adddialog" v-model="auditFormisible" width="28vw" :before-close="closeAuditForm">
            <el-form class="addForm" label-width="4vw" label-position="left">
                <el-form-item :label="t('common_add.jwcode')">
                    <el-input disabled="true" v-model="auditFormData.jwcode"
                        :placeholder="t('common_add.rejectReasonPlaceholder')" />
                </el-form-item>
                <el-form-item :label="t('common_add.customerName')">
                    <el-input disabled="true" v-model="auditFormData.name"
                        :placeholder="t('common_add.customerNamePlaceholder')" />
                </el-form-item>
                <el-form-item :label="t('common_add.market')">
                    <el-input disabled="true" v-model="auditFormData.market" />
                </el-form-item>
                <el-form-item :label="t('common_add.activity')">
                    <el-input disabled="true" v-model="auditFormData.activity"
                        :placeholder="t('common_add.activityPlaceholder')" />
                </el-form-item>
                <el-form-item :label="t('common_add.productName')">
                    <el-select disabled="true" v-model="auditFormData.goodsName" />
                </el-form-item>
                <el-form-item v-if="!isGold" :label="t('common_add.productNum')">
                    <div style="display: flex;">
                        <el-input disabled="true" style="padding-right: 30px; flex: 3;" v-model="auditFormData.goodNum"
                            :placeholder="t('common_add.productNumPlaceholder')" />
                        <CurrencySelect disabled="true" v-model="auditFormData.numUnit" :items="numUnitList"
                            style="flex: 1.5;" :placeholder="t('common_add.numUnit')" @change="handleCurrencyChange" />
                    </div>
                </el-form-item>
                <div v-show="isGold" style="margin-bottom: 15px;  display: flex;">
                    <div style=" display: flex; ">
                        <span style="color: #999999; display: flex; white-space: nowrap;align-items: center;">{{
                            t('common_add.permanentGold') }}：</span>
                        <el-input disabled="true"
                            style="padding-right: 10px; padding-left: 10px; height: 30px; width: 110px;"
                            v-model="auditFormData.permanentGold" />
                    </div>
                    <div style="padding-right: 5px; display: flex;">
                        <span style="color: #999999; display: flex; white-space: nowrap;align-items: center;">{{
                            t('common_add.freeGold') }}：</span>
                        <el-input disabled="true"
                            style="padding-right: 10px; padding-left: 10px; height: 30px; width: 110px;"
                            v-model="auditFormData.freeGold" />
                    </div>
                </div>
                <el-form-item :label="t('common_add.payCurrency')">
                    <el-select disabled="true" v-model="auditFormData.paymentCurrency"
                        :placeholder="t('common_add.payCurrencyPlaceholder')" @change="handleCurrencyChange" />
                </el-form-item>
                <el-form-item :label="t('common_add.payAmount')">
                    <el-input disabled="true" v-model="auditFormData.paymentAmount"
                        :placeholder="t('common_add.payAmountPlaceholder')" />
                </el-form-item>
                <el-form-item :label="t('common_add.payMethod')">
                    <el-select disabled="true" v-model="auditFormData.payType" :items="paytypeOptions"
                        :placeholder="t('common_add.payMethodPlaceholder')" />
                </el-form-item>
                <el-form-item :label="t('common_add.receiveArea')">
                    <el-select disabled="true" v-model="auditFormData.receivedMarket"
                        :placeholder="t('common_add.receiveArea')" />
                </el-form-item>
                <el-form-item :label="t('common_add.payTime')">
                    <el-date-picker disabled="true" type="datetime" v-model="auditFormData.payTime"
                        :placeholder="t('common_add.payTimePlaceholder')" />
                </el-form-item>
                <el-form-item :label="t('common_add.transferVoucher')">
                    <div class="pic">
                        <el-upload disabled="true" ref="uploadRef" class="uploader" :show-file-list="false"
                            list-type="picture-card" :auto-upload="false" :before-upload="beforeUpload"
                            :on-error="handelImgErr" :on-change="handleImageChange" :http-request="customUpload">
                            <img v-if="auditFormData.voucher" :src="auditFormData.voucher" class="avatar"
                                style="height: 100%; width: 100%;  object-fit: cover;" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                        <el-text class="picText">
                            {{ t('common_add.transferVoucherPlaceholder') }}
                        </el-text>
                    </div>
                </el-form-item>
                <el-form-item :label="t('common_add.remark')">
                    <el-input disabled="true" v-model="auditFormData.remark" type="textarea" :rows="3" maxlength="100"
                        show-word-limit />
                </el-form-item>
                <el-form-item :label="t('common_add.rejectReason')" v-if="ifReject" required>
                    <el-input v-model="auditFormData.rejectReason" type="textarea" :rows="3"
                        :placeholder="t('common_add.rejectReasonPlaceholder')" maxlength="100" show-word-limit />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer" v-if="!ifReject">
                    <el-button style="background-color: #7E91FF;" @click="ifReject = true">{{ t('common.reject')
                        }}</el-button>
                    <el-button :style="{
                        backgroundColor: isBtnDisabled ? '#E5E5E5FF' : '#2741DEFF',
                        marginLeft: '60px',
                        color: isBtnDisabled ? '#8A8A8A' : '#F3FAFE'
                    }" @click="handelAudit" :disabled="isBtnDisabled">{{ btnText }}</el-button>
                </span>
                <span class="dialog-footer" v-if="ifReject">
                    <el-button style="background-color: #7E91FF;" @click="closeAuditForm">{{ t('common.cancel')
                        }}</el-button>
                    <el-button style="background-color: #2741DE; margin-left: 2.5vw;" type="primary"
                        @click="throttledhandelAuditReject">{{ t('common.confirm') }}</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 编辑填手续费弹窗 -->
        <el-dialog class="editdialog" v-model="editFormisible" width="28vw" :before-close="closeEditForm">
            <div class="content">
                <div class="left">
                    <el-form class="editForm" label-width="6vw" label-position="left">
                        <el-form-item :label="t('common_add.jwcode')">
                            <el-input disabled="true" v-model="editFormData.jwcode"
                                :placeholder="t('common_add.jwcode')" />
                        </el-form-item>
                        <el-form-item :label="t('common_add.customerName')">
                            <el-input disabled="true" v-model="editFormData.name"
                                :placeholder="t('common_add.customerName')" />
                        </el-form-item>
                        <el-form-item :label="t('common_add.market')">
                            <el-input disabled="true" v-model="editFormData.marketName"
                                :placeholder="t('common_add.market')" />
                        </el-form-item>
                        <el-form-item :label="t('common_add.activity')">
                            <el-input disabled="true" v-model="editFormData.activity"
                                :placeholder="t('common_add.activity')" />
                        </el-form-item>
                        <el-form-item :label="t('common_add.productName')">
                            <el-select disabled="true" v-model="editFormData.goodsName"
                                :placeholder="t('common_add.productName')" clearable></el-select>
                        </el-form-item>
                        <!-- 金币产品特殊显示 -->
                        <el-form-item v-show="!isEditGold" :label="t('common_add.productNum')">
                            <div style="display: flex;">
                                <el-input disabled="true" style="padding-right: 30px; flex: 3;"
                                    v-model="editFormData.goodNum"
                                    :placeholder="t('common_add.productNumPlaceholder')" />
                                <CurrencySelect disabled="true" v-model="editFormData.numUnit" :items="numUnitList"
                                    style="flex: 1.5;" :placeholder="t('common_add.numUnit')"
                                    @change="handleCurrencyChange" />
                            </div>
                        </el-form-item>
                        <div v-show="isEditGold" style="margin-bottom: 15px;  display: flex;">
                            <div style=" display: flex; margin-right: 10px;">
                                <span style="color: #999999; display: flex; white-space: nowrap;align-items: center;">{{
                                    t('common_add.permanentGold') }}：</span>
                                <el-input disabled="true"
                                    style="padding-right: 10px; padding-left: 10px; height: 30px; width: 110px;"
                                    v-model="editFormData.permanentGold" />
                            </div>
                            <div style="padding-right: 5px; display: flex;">
                                <span style="color: #999999; display: flex; white-space: nowrap;align-items: center;">{{
                                    t('common_add.freeGold') }}：</span>
                                <el-input disabled="true"
                                    style="padding-right: 10px; padding-left: 10px; height: 30px; width: 110px;"
                                    v-model="editFormData.freeGold" />
                            </div>
                        </div>
                        <el-form-item :label="t('common_add.payCurrency')">
                            <CurrencySelect :disabled="!ifOnline" v-model="editFormData.paymentCurrency"
                                :items="customOptions" :placeholder="t('common_add.payCurrency')" />
                        </el-form-item>
                        <el-form-item :label="t('common_add.payAmount')">
                            <el-input :disabled="!ifOnline" v-model="editFormData.paymentAmount"
                                :placeholder="t('common_add.payAmount')" />
                        </el-form-item>
                        <el-form-item :label="t('common_add.payMethod')">
                            <el-select disabled="true" v-model="editFormData.payType"
                                :placeholder="t('common_add.payMethod')" clearable></el-select>
                        </el-form-item>
                        <el-form-item :label="t('common_add.receiveArea')">
                            <el-select disabled="true" v-model="editFormData.receivedMarket"
                                :placeholder="t('common_add.receiveArea')" clearable></el-select>
                        </el-form-item>
                        <el-form-item :label="t('common_add.payTime')">
                            <el-date-picker disabled="true" type="datetime" v-model="editFormData.payTime"
                                :placeholder="t('common_add.payTime')" />
                        </el-form-item>
                        <el-form-item :label="t('common_add.transferVoucher')">
                            <div class="pic">
                                <el-upload disabled="true" ref="uploadRef" class="uploader" :show-file-list="false"
                                    list-type="picture-card" :auto-upload="false" :before-upload="beforeUpload"
                                    :on-error="handelImgErr" :on-change="handleImageChange"
                                    :http-request="customUpload">
                                    <img v-if="editFormData.voucher" :src="editFormData.voucher" class="avatar"
                                        style="height: 100%; width: 100%;  object-fit: cover;" />
                                    <el-icon v-else class="avatar-uploader-icon">
                                        <Plus />
                                    </el-icon>
                                </el-upload>
                                <el-text class="picText">{{ t('common_add.transferVoucherPlaceholder') }}</el-text>
                            </div>
                        </el-form-item>
                        <el-form-item :label="t('common_add.remark')">
                            <el-input disabled="true" v-model="editFormData.remark" type="textarea" :rows="4"
                                :placeholder="t('common_add.remark')" maxlength="100" show-word-limit />
                        </el-form-item>
                    </el-form>
                </div>
                <div class="right">
                    <el-form ref="editFormRef" :rules="editFormRule" :model="editFormData" class="editFormRighrt"
                        label-width="6vw" label-position="left">
                        <el-form-item :label="t('common_add.receiveCurrency')">
                            <CurrencySelect v-model="editFormData.receivedCurrency" :items="customOptions"
                                :placeholder="t('common_add.receiveCurrencyPlaceholder')" />
                        </el-form-item>
                        <el-form-item :label="t('common_add.receiveAmount')" prop="receivedAmount">
                            <el-input v-model="editFormData.receivedAmount"
                                :placeholder="t('common_add.receiveAmountPlaceholder')" type="number" />
                        </el-form-item>
                        <el-form-item :label="t('common_add.fee')" prop="handlingCharge">
                            <el-input v-model="editFormData.handlingCharge"
                                :placeholder="t('common_add.feePlaceholder')" type="number" />
                        </el-form-item>
                        <el-form-item :label="t('common_add.receiveTime')">
                            <el-date-picker type="datetime" v-model="editFormData.receivedTime"
                                :placeholder="t('common_add.receiveTimePlaceholder')" />
                        </el-form-item>
                    </el-form>
                    <span class="editBtns">
                        <button class="editBtn1" @click="closeEditForm">
                            <text class="txt">{{ t('common.cancel') }}</text>
                        </button>
                        <button class="editBtn2" @click="throttledsubmitEditForm">
                            <text class="txt">{{ t('common.submit') }}</text>
                        </button>
                    </span>
                </div>
            </div>
        </el-dialog>

        <!-- 新增退款 -->
        <el-dialog v-model="refundDialog" :title="t('common_add.refund')" class="refundDialog" overflow draggable style="width: 40vw;"
            :before-close="closeRefundForm">
            <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="refundFormData.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="refundFormData.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="refundFormData.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="refundFormData.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="refundFormData.goodsName" style="width:10vw;" disabled />
                    </div>
                    <div v-show="!isRefundGold" class="add-item">
                        <el-text style="width:4vw;">{{ t('common_add.productNum') }}</el-text>
                        <el-input style="padding-right: 10px; width:6.5vw;" v-model="refundFormData.goodNum"
                            :placeholder="t('common_add.productNumPlaceholder')" disabled />
                        <CurrencySelect disabled="true" v-model="refundFormData.numUnit" :items="numUnitList"
                            style=" width: 3.5vw;" :placeholder="t('common_add.numUnit')"
                            @change="handleCurrencyChange" />
                    </div>
                    <div v-show="isRefundGold" style="display: flex; margin-bottom: 10px;">
                        <div style=" display: flex; align-items: center;justify-content: center; ">
                            <span style="color: #999999;  white-space: nowrap;">{{ t('common_add.permanentGold')
                                }}：</span>
                            <el-input style="padding-right: 10px;  height: 30px; width: 70px;"
                                v-model="refundFormData.permanentGold" disabled />
                        </div>
                        <div style=" display: flex; align-items: center;justify-content: center; ">
                            <span style="color: #999999;  white-space: nowrap;">{{ t('common_add.freeGold') }}：</span>
                            <el-input style="padding-right: 10px;  height: 30px; width: 70px;"
                                v-model="refundFormData.freeGold" disabled />
                        </div>
                    </div>
                    <div class="add-item">
                        <el-text style="width:4vw;">{{ t('common_add.payCurrency') }}</el-text>
                        <el-input v-model="refundFormData.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="refundFormData.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="refundFormData.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="refundFormData.payTime" type="datetime" style="width:10vw;" disabled />
                    </div>
                    <div class="add-item">
                        <el-text style="width:4vw;" size="small">{{ t('common_add.transferVoucher') }}</el-text>
                        <el-form-item
                            :rules="{ required: true, message: t('common_add.uploadPhoto'), trigger: 'change' }">
                            <el-upload ref="uploadRef" :auto-upload="false" list-type="picture-card"
                                :show-file-list="false">
                                <template #default>
                                    <img v-if="refundFormData.voucher" :src="refundFormData.voucher"
                                        style="width: 100%; height: 100%; object-fit: cover;">
                                    <el-icon v-else>
                                        <Plus />
                                    </el-icon>
                                </template>
                            </el-upload>
                        </el-form-item>
                    </div>
                    <div class="add-item">
                        <el-text style="width:4vw;">{{ t('common_add.remark') }}</el-text>
                        <el-input v-model="refundFormData.remark" style="width:10vw;" :rows="2" 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.refundModel') }}</el-text>
                        <el-radio-group v-model="refundFormData.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 v-show="refundFormData.refundModel == '1'" style="display: flex; margin-bottom: 10px;">
                        <div style=" display: flex; align-items: center;justify-content: center; ">
                            <span style="color: #999999;  white-space: nowrap;">{{ t('common_add.permanentGold')
                                }}：</span>
                            <el-input style="padding-right: 10px;  height: 30px; width: 70px;"
                                v-model="refundFormData.partRefundGold" dsabled />
                        </div>
                        <div style=" display: flex; align-items: center;justify-content: center; ">
                            <span style="color: #999999;  white-space: nowrap;">{{ t('common_add.freeGold') }}：</span>
                            <el-input style="padding-right: 10px;  height: 30px; width: 70px;"
                                v-model="refundFormData.partRefundFree" />
                        </div>
                    </div>
                    <div class="add-item">
                        <el-text style="width:4vw;">{{ t('common_add.refundReason') }}</el-text>
                        <el-input v-model="refundFormData.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="resetRefund">{{ t('common.reset') }}</el-button>
                        <el-button type="primary" @click="throttledsubmitRefund">{{ t('common.submit') }}</el-button>
                    </div>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
// 仅导入地区财务所需依赖
import { ref, watch, onMounted } from 'vue';
import { storeToRefs } from 'pinia';
import { ElMessage, ElMessageBox } from 'element-plus';
import API from '@/util/http.js';
import request from '@/util/http.js';
import moment from 'moment';
import _ from 'lodash';
import { Plus } from '@element-plus/icons-vue';
import { startsWith } from './utils/util.js'
import { isNumber } from 'lodash'
// 地区财务专属组件
import CurrencySelect from '@/components/MoneyManage/CurrencySelect.vue';

// 静态数据与规则（仅保留必要项）
import { editFormRule } from './utils/recriveFormRules.js';
import { productList, MarketNameForId, CurrencyForId, marketList, normalizeSubmitterMarket } from './utils/staticData.js';
import { useAdminStore } from '@/store/index.js';
import { hasMenuPermission } from '@/utils/menuTreePermission.js';

// 国际化
import { useI18n } from 'vue-i18n'
const { t } = useI18n()

// ===================== 1. 核心状态管理（仅地区财务） =====================
const adminStore = useAdminStore();
const { menuTree } = storeToRefs(adminStore);

// 角色固定：地区财务（caiwu=true，其他角色关闭）
const kefu = ref(false);
const caiwu = ref(true);
const HQcaiwu = ref(false);
const superAdmin = ref(false);

// 表格与分页数据
const tableData = ref([]);
const total = ref(0);
const pageInfo = ref({ pageSize: 10, pageNum: 1 });

// 筛选地区树
const market = ref([])

// 搜索条件
const searchData = ref({});
const defaultTime = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)];
const getTime = ref([]);

// 标签页：默认“待审核”
const activeTab = ref('wait');

// 审核弹窗状态
const auditFormisible = ref(false);
const auditFormData = ref({});
const ifReject = ref(false);
const countdown = ref(0);
const isBtnDisabled = ref(false);
const btnText = ref(t('common.pass') + '(3)');

// 编辑弹窗状态
const editFormisible = ref(false);
const editFormData = ref({});
const editFormRef = ref(null);
const isEditGold = ref(false); // 金币产品标记
const ifOnline = ref(false); // 在线支付标记

// 辅助状态：图片上传、悬浮提示
const uploadRef = ref(null);
const showTooltip = ref(false);
const tooltipContent = ref('');
const tooltipLeft = ref(0);
const tooltipTop = ref(0);

// 退款确认弹窗
const refundConfirmDialog = ref(false)
const textContent = ref('')


//退款弹窗
const refundDialog = ref(false)
const refundFormData = ref({})

const openRefundDialog = () => {
    refundDialog.value = true
    closeConfirmRefund()

}
const closeRefundForm = () => {
    refundDialog.value = false
    refundFormData.value = {}
}

const isRefundGold = ref(false)
const ifRefundGold = () => {
    if (refundFormData.value.goodsName === t('cash.coinRecharge')) {
        isRefundGold.value = true
        refundFormData.value.goodNum = 0
    } else {
        isRefundGold.value = false
    }
}



// 基础数据
const adminData = ref({});
const activityList = ref([]);
const customOptions = ref([
    t('cash.currency.usd'),   // 美元(USD)
    t('cash.currency.hkd'),   // 港币(HKD)
    t('cash.currency.sgd'),   // 新币(SGD)
    t('cash.currency.myr'),   // 马币(MYR)
    t('cash.currency.thb'),   // 泰铢(THB)
    t('cash.currency.cad'),   // 加币(CAD)
    t('cash.currency.vnd'),   // 越南盾(VND)
    t('cash.currency.krw'),    // 韩元(KRW)
    t('cash.currency.rmb'),    // 人民币(CNY)
])
const paytypeList = [
    t('cash.payMethods.stripe'),
    t('cash.payMethods.paymentAsia'),
    t('cash.payMethods.ipay88'),
    t('cash.payMethods.bankTransfer'),
    t('cash.payMethods.card'),
    t('cash.payMethods.cash'),
    t('cash.payMethods.check'),
    t('cash.payMethods.grabpay'),
    t('cash.payMethods.nets'),
    t('cash.payMethods.transfer'),
    t('cash.payMethods.paypal'),
];
const paytypeOptions = ref([...paytypeList]);

// ===================== 2. 核心功能函数（仅地区财务） =====================

//确认退款弹窗
const openRefundConfirm = (row) => {
    textContent.value = t('common.willRefundOrder') + '?'
    refundConfirmDialog.value = true
    refundFormData.value = { ...row }
    ifRefundGold()
    console.log(row);

}

const closeConfirmRefund = () => {
    refundConfirmDialog.value = false
    textContent.value = ''
}

//导出相关
const exportListVisible = ref(false)
const exportList = ref([])
const exportListLoading = ref(false)
const exportExcel = async function () {

    let payCurrencySelect = '';
    let goodsName = '';

    // 处理时间范围
    if (getTime.value && getTime.value.length === 2) {
        searchData.value.startTime = moment(getTime.value[0]).format('YYYY-MM-DD HH:mm:ss');
        searchData.value.endTime = moment(getTime.value[1]).format('YYYY-MM-DD HH:mm:ss');
    } else {
        searchData.value.startTime = '';
        searchData.value.endTime = '';
    }

    // 处理产品名称（级联选择取最后一级）
    if (searchData.value.goodsName) {
        goodsName = searchData.value.goodsName[searchData.value.goodsName.length - 1];
    }

    // 处理付款币种（转ID）
    if (searchData.value.paymentCurrency) {
        payCurrencySelect = CurrencyForId(searchData.value.paymentCurrency);
    }

    // if (searchData.value.jwcode && !isNumber(searchData.value.jwcode)) {
    //     ElMessage.error('精网号只能是数字')
    //     return
    // }

    const cashRoleId = '1';
    const submitterMarket = adminData.value.markets;
    searchData.value.status = 46;
    const params = {
        ...pageInfo.value,
        cashCollection: {
            ...searchData.value,
            submitterId: adminData.value.id,
            receivedMarket: MarketNameForId(submitterMarket),
            cashRoleId: cashRoleId,
            paymentCurrency: payCurrencySelect,
            submitterMarket: submitterMarket,
            goodsName: goodsName,
            market: MarketNameForId(searchData.value.market)
        }
    }

    const res = await API({ url: '/export/exportCash', data: params })
    if (res.code === 200) {
        ElMessage.success(t('elmessage.exportSuccess'))
    } else {
        ElMessage.error(res.msg || t('elmessage.exportFailed'))
    }
}

const openExportList = () => {
    getExportList()
    exportListVisible.value = true
}
//获取导出列表
const getExportList = async () => {
    exportListLoading.value = true
    try {
        const result = await API({ url: '/export/export' })
        if (result.code === 200) {
            const filteredData = result.data.filter(item => {
                return item.type === 13
            })
            exportList.value = filteredData
        } else {
            ElMessage.error(result.msg || t('elmessage.getExportListError'))
        }
    } catch (error) {
        console.error('获取导出列表出错:', error)
        ElMessage.error(t('elmessage.getExportListError'))
    } finally {
        exportListLoading.value = false
    }
}
const downloadExportFile = (item) => {
    if (item.state === 2) {
        const link = document.createElement('a')
        link.href = item.url
        link.download = item.fileName
        link.click()
    } else {
        ElMessage.warning(t('elmessage.exportingInProgress'))
    }
}
//根据状态返回对应的标签类型
const getTagType = (state) => {
    switch (state) {
        case 0:
            return 'info';
        case 1:
            return 'primary';
        case 2:
            return 'success';
        case 3:
            return 'danger';
        default:
            return 'info';
    }
}
//根据状态返回对应的标签文案
const getTagText = (state) => {
    switch (state) {
        case 0:
            return t('elmessage.pendingExecution');
        case 1:
            return t('elmessage.executing');
        case 2:
            return t('elmessage.executed');
        case 3:
            return t('elmessage.errorExecution');
        default:
            return t('elmessage.unknownStatus');
    }
}

// 2.1 数据加载：获取地区财务订单列表
const getlist = async () => {
    try {
        let payCurrencySelect = '';
        let goodsName = '';

        // 处理时间范围
        if (getTime.value && getTime.value.length === 2) {
            searchData.value.startTime = moment(getTime.value[0]).format('YYYY-MM-DD HH:mm:ss');
            searchData.value.endTime = moment(getTime.value[1]).format('YYYY-MM-DD HH:mm:ss');
        } else {
            searchData.value.startTime = '';
            searchData.value.endTime = '';
        }

        // 处理产品名称（级联选择取最后一级）
        if (searchData.value.goodsName) {
            goodsName = searchData.value.goodsName[searchData.value.goodsName.length - 1];
        }

        // 处理付款币种（转ID）
        if (searchData.value.paymentCurrency) {
            payCurrencySelect = CurrencyForId(searchData.value.paymentCurrency);
        }

        // if (searchData.value.jwcode && !isNumber(searchData.value.jwcode)) {
        //     ElMessage.error('精网号只能是数字')
        //     return
        // }

        // 地区财务固定参数：角色ID=1，按标签页筛选状态
        const cashRoleId = '1';
        const receivedMarket = normalizeSubmitterMarket(adminData.value.markets);
        if (activeTab.value === 'wait') searchData.value.status = 0;
        else if (activeTab.value === 'pass') searchData.value.status = 13;
        else if (activeTab.value === 'done') searchData.value.status = 46;
        else if (activeTab.value === 'reject') searchData.value.status = 2;

        // 地区处理
        const markets = ref(null)
        if (searchData.value.markets) {
            markets.value = searchData.value.markets[searchData.value.markets.length - 1]
            console.log('地区转换', markets.value)
        }
        if (searchData.value.jwcode) {
            const isPositiveInteger = /^[1-9]\d*$/.test(searchData.value.jwcode);
            if (!isPositiveInteger) {
                ElMessage.error(t('elmessage.checkJwcodeFormat'))
                return;
            }
            // 添加长度验证，超过8位提示错误
            if (searchData.value.jwcode.length > 8) {
                ElMessage.error(t('elmessage.limitJwcodeLength'))
                return;
            }
        }
        const result = await request({
            url: '/cashCollection/selectCollection',
            data: {
                ...pageInfo.value,
                cashCollection: {
                    ...searchData.value,
                    submitterId: adminData.value.id,
                    receivedMarket: MarketNameForId(receivedMarket),
                    cashRoleId: cashRoleId,
                    paymentCurrency: payCurrencySelect,
                    submitterMarket: normalizeSubmitterMarket(receivedMarket),
                    goodsName: goodsName,
                    // market: MarketNameForId(searchData.value.market)
                    market: markets.value
                }
            }
        });

        if (result.code === 200) {
            tableData.value = result.data.list;
            total.value = result.data.total;
        } else {
            ElMessage.error(t('elmessage.orderDataLoadFailed'));
        }
    } catch (error) {
        console.error('地区财务订单列表请求异常：', error);
        ElMessage.error(t('elmessage.inNetworkError'));
    }
};

//重置退款
const resetRefund = () => {
    refundFormData.value.refundModel = ''
    refundFormData.value.refundReason = ''
}
//提交退款
const submitRefund = async () => {
    try {
        if (refundFormData.value.goodsName != t('cash.coinRecharge')) {

            return ElMessage.error(t('elmessage.onlineDataSupport'));
        }
        if (!refundFormData.value.refundModel) {
            return ElMessage.error(t('elmessage.selectRefundModel'));
        }
        if (!refundFormData.value.refundReason) {
            return ElMessage.error(t('elmessage.refundReasonPlaceholder'));
        }
        // 验证精网号格式和长度
        if (refundFormData.value.jwcode) {
            const isPositiveInteger = /^[1-9]\d*$/.test(refundFormData.value.jwcode);
            if (!isPositiveInteger) {
                return ElMessage.error(t('elmessage.checkJwcodeFormat'));
            }
            if (refundFormData.value.jwcode.length > 8) {
                return ElMessage.error(t('elmessage.limitJwcodeLength'));
            }
        }
        if (refundFormData.value.refundModel == 0) {
            refundFormData.value.partRefundGold = refundFormData.value.permanentGold,
                refundFormData.value.partRefundFree = refundFormData.value.freeGold
        }
        const result = await request({
            url: '/Money/addOnline',
            data: {
                jwcode: refundFormData.value.jwcode,
                name: refundFormData.value.name,
                market: refundFormData.value.marketName,
                submitterId: adminData.value.id,
                submitterMarket: adminData.value.markets,
                remark: refundFormData.value.remark,
                refundReason: refundFormData.value.refundReason,
                refundModel: refundFormData.value.refundModel,
                originalOrderId: refundFormData.value.id,
                orderCode: refundFormData.value.orderCode,
                permanentGold: (refundFormData.value.permanentGold) * 100 || 0,
                freeGold: (refundFormData.value.freeGold) * 100 || 0,
                partRefundGold: (refundFormData.value.partRefundGold) * 100 || 0,
                partRefundFree: (refundFormData.value.partRefundFree) * 100 || 0,
                handlingCharge: refundFormData.value.handlingCharge == null ? null : refundFormData.value.handlingCharge * 100,
            }
        })
        if (result.code == 200) {
            ElMessage.success(t('elmessage.addRefundSuccess'))
            getlist()
            closeRefundForm()
        } else {
            ElMessage.error(result.msg)
            getlist()
        }
        console.log('返回参数：', result);
    } catch (error) {
        console.log(error);
    }
}

// 2.2 搜索与重置
const search = () => {
    getlist();
};

const reset = () => {
    searchData.value = {};
    // 重置页码
    pageInfo.value.pageNum = 1;
    getTime.value = []
    getlist();
};

// 2.3 标签页切换
const navigateTo = async (tab) => {
    activeTab.value = tab;
    await getlist();
};

// 2.4 审核功能
// 打开审核弹窗
const openAuditForm = (row) => {
    auditFormData.value = { ...row, market: row.marketName };
    ifGold(auditFormData.value)
    console.log('isGold', isGold.value);

    auditFormisible.value = true;
};

// 关闭审核弹窗
const closeAuditForm = () => {
    ifReject.value = false;
    auditFormisible.value = false;
    auditFormData.value = {};
};

// 审核通过
const handelAudit = async () => {
    try {
        const result = await request({
            url: '/cashAudit/collectionAudit',
            data: {
                orderCode: auditFormData.value.orderCode,
                action: 1,
                auditId: adminData.value.id
            }
        });

        if (result.code === 200) {
            ElMessage.success(t('elmessage.approveSuccess'));
            getlist();
            closeAuditForm();
        } else {
            ElMessage.error(result.msg || t('elmessage.approveFailed'));
        }
    } catch (error) {
        console.error('审核通过请求异常：', error);
        ElMessage.error(t('elmessage.inNetworkError'));
    }
};

// 审核驳回
const handelAuditReject = async () => {
    if (!auditFormData.value.rejectReason) {
        ElMessage.warning(t('elmessage.rejectReasonPlaceholder'));
        return;
    }

    try {
        const result = await request({
            url: '/cashAudit/collectionAudit',
            data: {
                orderCode: auditFormData.value.orderCode,
                rejectReason: auditFormData.value.rejectReason,
                action: 2,
                auditId: adminData.value.id
            }
        });

        if (result.code === 200) {
            ElMessage.success(t('elmessage.rejectSuccess'));
            getlist();
            closeAuditForm();
        } else {
            ElMessage.error(result.msg || t('elmessage.rejectFailed'));
        }
    } catch (error) {
        console.error('审核驳回请求异常：', error);
        ElMessage.error(t('elmessage.inNetworkError'));
    }
};

//判断产品类型
const isGold = ref(false)
const ifGold = (data) => {
    console.log('data', data);
    if (data.goodsName === t('cash.coinRecharge')) {
        isGold.value = true
    } else {
        isGold.value = false
    }
}

// 审核按钮倒计时（防止误操作）
watch(auditFormisible, (val) => {
    if (val) {
        countdown.value = 3;
        isBtnDisabled.value = true;
        btnText.value = `${t('common.pass')}(${countdown.value})`;

        const timer = setInterval(() => {
            countdown.value--;
            btnText.value = `${t('common.pass')}(${countdown.value})`;

            if (countdown.value <= 0) {
                isBtnDisabled.value = false;
                clearInterval(timer);
                btnText.value = t('common.pass');
            }
        }, 1000);
    }
});

// 2.5 编辑手续费功能
// 打开编辑弹窗
const openEditForm = (row) => {
    console.log('row.aaa', row.handlingCharge);

    editFormData.value = { ...row };
    // 区分金币产品与普通产品
    if (row.goodsName === t('cash.coinRecharge')) isEditGold.value = true;
    else isEditGold.value = false;
    // 在线支付订单允许修改付款信息
    if (row.status === 3) ifOnline.value = true;
    else ifOnline.value = false;

    editFormisible.value = true;
};

// 关闭编辑弹窗
const closeEditForm = () => {
    editFormisible.value = false;
    editFormData.value = {};
    editFormRef.value.resetFields();
};

// 提交编辑（补充手续费）
const submitEditForm = async () => {
    try {
        await editFormRef.value.validate();

        // 处理时间格式
        if (editFormData.value.receivedTime) {
            editFormData.value.receivedTime = moment(editFormData.value.receivedTime).format('YYYY-MM-DD HH:mm:ss');
        }
        console.log('editFormData.value.handlingCharge', editFormData.value.handlingCharge);

        const result = await request({
            url: '/cashCollection/complete',
            data: {
                orderCode: editFormData.value.orderCode,
                handlingCharge: editFormData.value.handlingCharge == null ? null : editFormData.value.handlingCharge * 100, // 转为分单位
                paymentCurrency: CurrencyForId(editFormData.value.paymentCurrency),
                paymentAmount: editFormData.value.paymentAmount * 100, // 转为分单位
                receivedCurrency: CurrencyForId(editFormData.value.receivedCurrency),
                receivedAmount: editFormData.value.receivedAmount * 100 || null, // 转为分单位
                receivedTime: editFormData.value.receivedTime,
                receivedRemark: editFormData.value.receivedRemark || ''
            }
        });

        if (result.code === 200) {
            ElMessage.success(t('elmessage.editSuccess'));
            getlist();
            closeEditForm();
        } else {
            ElMessage.error(result.msg || t('elmessage.editFailed'));
        }
    } catch (error) {
        console.error('编辑提交请求异常：', error);
        ElMessage.error(t('elmessage.formValidationFailed'));
    }
};

// 2.6 辅助功能
// 图片预览
const previewImage = (imageUrl) => {
    if (!imageUrl) return;

    const imageElement = document.createElement('img');
    imageElement.src = imageUrl;
    imageElement.style.maxWidth = '80vw';
    imageElement.style.maxHeight = '80vh';
    imageElement.style.objectFit = 'contain';

    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.appendChild(imageElement);

    // 点击关闭预览
    viewer.addEventListener('click', () => {
        document.body.removeChild(viewer);
    });

    document.body.appendChild(viewer);
};

// 驳回理由悬浮提示
const handleMouseEnter = (e, content) => {
    if (!content) return;

    showTooltip.value = true;
    tooltipContent.value = content;
    handleMouseMove(e);
};

const handleMouseLeave = () => {
    showTooltip.value = false;
    tooltipContent.value = '';
};

const handleMouseMove = (e) => {
    // 提示框显示在鼠标左侧，避免遮挡
    tooltipLeft.value = e.clientX - 210;
    tooltipTop.value = e.clientY - 10;
};

// 2.7 基础数据加载（初始化）
// 获取管理员信息
const getAdminData = async () => {
    try {
        const result = await API({ url: '/admin/userinfo', data: {} });
        adminData.value = result;

        // 超级管理员判断（仅用于角色切换权限）
        // if (adminData.value.roleId === 2) {
        //     superAdmin.value = true;
        //     // 管理员所属地区提示
        //     if (adminData.value.markets === '总部' || adminData.value.markets === '研发部') {
        //         ElMessageBox.alert(
        //             '管理员账号仅显示所属地区的财务数据，请确认地区设置',
        //             '温馨提示',
        //             { type: 'warning' }
        //         );
        //     }
        // }
    } catch (error) {
        console.error('管理员信息获取失败：', error);
        ElMessage.error(t('elmessage.adminInfoLoadFailed'));
    }
};

// 获取活动列表
const getActivitys = async () => {
    try {
        const result = await API({ url: '/cashCollection/getActivityList', data: {} });
        if (result.code === 200) {
            activityList.value = result.data;
        } else {
            ElMessage.error(t('elmessage.activityLoadFailed'));
        }
    } catch (error) {
        console.error('活动列表获取失败：', error);
        ElMessage.error(t('elmessage.activityLoadFailed'));
    }
};

// 2.8 节流函数（防止重复提交）
const throttledhandelAuditReject = _.throttle(handelAuditReject, 3000, { trailing: false });
const throttledsubmitEditForm = _.throttle(submitEditForm, 3000, { trailing: false });
const throttledsubmitRefund = _.throttle(submitRefund, 5000, {
    trailing: false
})
// 2.9 页面初始化
onMounted(async () => {
    await getAdminData();
    await getActivitys();
    // 初始化加载地区财务订单数据
    await getlist();

    // if (!hasMenuPermission(menuTree.value, 67)) {
    //     ElMessageBox.alert(
    //         '您暂无该页面操作权限，请联系管理员',
    //         '权限提示',
    //         { type: 'error' }
    //     ).then(() => {
    //         window.history.back();
    //     });
    // }
    //背景预加载
    const bgImg = new Image();
    bgImg.src = '/src/assets/receive-recall.png';
    getMarket()
});

// 2.10 未使用函数占位（避免报错）
const handleCurrencyChange = () => { };
const beforeUpload = () => true;
const handelImgErr = () => { };
const handleImageChange = () => { };
const customUpload = () => { };
const handleDatePickerChange = () => { };
const disabledDate = () => false;
const handleSortChange = () => { };
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 handlePagination = (type, val) => {
    if (type === 'size') pageInfo.value.pageSize = val;
    else pageInfo.value.pageNum = val;
    getlist();
};
</script>

<style scoped lang="scss">
.content {
    height: 100%;
    width: 80vw;

    .card1 {
        width: 100%;
        background: #F3FAFE;

        .rowItem {
            display: flex;
            width: 15vw;
            align-items: center;
            justify-content: center;
            margin-right: 0.5vw;
        }

        el-button {
            margin-left: 10px;
        }

        .row1 {
            height: 4vh;
            width: 80vw;
            display: flex;
            min-height: 40px;
        }

        .row2 {
            height: 4vh;
            width: 80vw;
            display: flex;
            align-items: center;

            min-height: 40px;

            .left {
                height: 4vh;
                width: 58vw;
                display: flex;
                min-height: 40px;
            }
        }
    }


    .div-card2 {
        width: 100%;
        margin-top: 2vh;

        .card2 {
            background: #E7F4FD;
        }

        .btns {
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding-bottom: 10px;

            .tabs {
                width: 100%;
                min-width: 300px;
                display: flex;
                align-items: center;
                justify-content: space-between;

                .btnItem {
                    margin-left: 10px;
                    border-radius: 5px;
                }

                .info-tooltip {
                    display: flex;
                    align-items: center;
                }

                .service-icon {
                    color: #666;
                    cursor: pointer;
                    font-size: 18px;
                    transition: all 0.3s ease;
                    padding: 4px;
                    border-radius: 50%;
                }
            }
        }


        .table {
            margin: 10px;
            border-radius: 20px;

            .ellipsis-container {
                position: relative;
                width: 100%;

                .ellipsis-text {
                    display: inline-block;
                    width: 100%;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    cursor: pointer;
                }

                .custom-tooltip {
                    position: fixed;
                    z-index: 9999;
                    padding: 8px 12px;
                    width: 200px;
                    background-color: #E4F0FC;
                    color: #333333;
                    border: 1px solid #e5e7eb;
                    border-radius: 4px;
                    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
                    min-height: 30px;
                    max-height: 300px;
                    overflow-y: auto;
                    font-size: 14px;
                    line-height: 1.5;
                }
            }
        }

        .pagination {
            margin-top: 10px;
            padding: 10px 10px;
        }
    }

    :deep(.adddialog) {
        min-width: 500px;
        background-color: #F3FAFE !important;
        margin-top: 8vh;
        border-radius: 8px;

        .addForm {
            padding: 0 60px 1vh 60px;

            .el-date-editor {
                display: flex;
                flex: 1;

            }

            .pic {
                display: flex;
                align-items: center;

                .uploader {
                    height: 80px;
                    width: 80px;

                    .el-upload {
                        height: 100%;
                        width: 100%;
                    }
                }

                .picText {
                    color: #999999;
                    font-family: "PingFang SC";
                    font-size: 10px;
                    font-style: normal;
                    font-weight: 400;
                    line-height: 20px;
                    margin-left: 10px;
                }
            }
        }

        .dialog-footer {
            display: flex;
            justify-content: center;
            padding-bottom: 1.5vh;
        }
    }

    :deep(.editdialog) {
        min-width: 990px;
        background-color: #F3FAFE !important;
        margin-top: 8vh;
        border-radius: 8px;

        .editForm {
            padding: 0 60px 1vh 60px;

            .el-date-editor {
                display: flex;
                flex: 1;
            }

            .pic {
                display: flex;
                align-items: center;

                .uploader {
                    height: 80px;
                    width: 80px;

                    .el-upload {
                        height: 100%;
                        width: 100%;
                    }
                }

                .picText {
                    color: #999999;
                    font-family: "PingFang SC";
                    font-size: 10px;
                    font-style: normal;
                    font-weight: 400;
                    line-height: 20px;
                    margin-left: 10px;
                }
            }
        }

        .content {
            display: flex;
            height: 100%;
            width: 100%;

            .left {
                min-width: 500px;
            }

            .right {
                flex: 1;

                .editFormRighrt {
                    padding: 0 60px 0 40px;

                    .el-date-editor {
                        display: flex;
                        flex: 1;
                    }
                }

                .editBtns {
                    display: flex;
                    justify-content: center;
                    margin-top: 60px;

                    .txt {
                        color: #f3fafe;
                        text-align: center;
                        font-family: "PingFang SC";
                        font-size: 14px;
                        font-style: normal;
                        font-weight: 700;
                        line-height: 22px;
                    }

                    .editBtn1 {
                        min-width: 80px;
                        padding: 5px 12px;
                        justify-content: center;
                        align-items: center;
                        gap: 4px;
                        border-radius: 4px;
                        background: #7E91FF;
                        border: none;
                        box-shadow: 0 0 4px 0 #00000040;
                    }

                    .editBtn2 {
                        display: flex;
                        width: 80px;
                        min-width: 80px;
                        padding: 5px 12px;
                        justify-content: center;
                        align-items: center;
                        gap: 4px;
                        border-radius: 4px;
                        background: #2741DE;
                        border: none;
                        box-shadow: 0 0 4px 0 #00000040;
                        margin-left: 60px;
                    }
                }
            }
        }
    }

    :deep(.adddialog .el-form-item__label) {
        min-width: 100px;
        width: auto;
        font-weight: 800;
        padding-bottom: 15px;
    }

    .refundDialog {
        .left {
            width: 50%;
            height: 70vh;
            min-height: 700px;
            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;
            }
        }
    }
}

// 表格样式统一
: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;
}

:deep(.el-table__row:hover > .el-table__cell) {
    background-color: #E5EBFE !important;
}

// 驳回理由弹窗样式
.reject-reason-box {
    --el-message-box-height: 500px;
}

.reject-reason-box .el-message-box__content {
    max-height: 350px;
    overflow-y: auto;
    white-space: pre-wrap;
}

.recallDialog {
    //撤回弹窗提示
    height: 392px;
    width: 700px;
    background-image: url('/src/assets/receive-recall.png');
    position: fixed; // 固定定位，相对于浏览器窗口
    top: 50%; // 距离顶部50%
    left: 50%; // 距离左侧50%
    transform: translate(-50%, -50%); // 向左、向上平移自身宽高的50%，实现居中
    z-index: 1000; // 确保在其他元素上层显示

    .close {
        position: absolute;
        left: 625px;
        top: 20px;
        height: 38px;
        width: 38px;
        opacity: 0;

        .Btn {
            height: 100%;
            width: 100%;
            border-radius: 10px;
        }
    }

    .text {
        position: absolute;
        left: 185px;
        top: 190px;
        height: 67px;
        width: 500px;

        .txt {
            height: 100%;
            width: 100%;
            color: #001a42;
            font-family: "PingFang SC";
            font-size: 48px;
            font-style: normal;
            font-weight: 900;
            line-height: normal;
        }
    }

    .cancle {
        position: absolute;
        left: 185px;
        top: 304px;
        height: 55px;
        width: 150px;
        opacity: 0;

        .Btn {
            height: 100%;
            width: 100%;
            border-radius: 20px;
        }
    }

    .confirm {
        position: absolute;
        left: 375px;
        top: 304px;
        height: 55px;
        width: 150px;
        opacity: 0;

        .Btn {
            height: 100%;
            width: 100%;
            border-radius: 20px;
        }
    }
}
</style>
