<!-- 各地负责人 -->
<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" :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.markets" :options="market"
                    :placeholder="t('common.marketPlaceholder')" clearable @change="handleMarketChange" />
            </div>
            <div class="item1">
                <el-text size="large" style="width:4vw;">{{ t('common.orderStatus') }}</el-text>
                <el-select v-model="searchForm.statuses" style="width:9vw;"
                    :placeholder="t('common.orderStatusPlaceholder')" clearable>
                    <el-option v-for="item in statusList" :label="item" :value="item" :key="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;"
                    :placeholder="t('common.payCurrencyPlaceholder')" 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;"
                    :placeholder="t('common.payModelPlaceholder')" clearable>
                    <el-option v-for="item in channelOptions" :key="item" :label="item" :value="item" />
                </el-select>
            </div>
            <div class="item2" style="width: 29.3vw;">
                <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;" @change="handleDatePickerChange" clearable :disabled-date="disabledDate"
                    :default-time="defaultTime" />
            </div>
            <div>
                <el-button type="primary" @click="getRefund">{{ t('common.search') }}</el-button>
                <el-button type="warning" @click="exportExcel()">{{ t('common.exportExcel') }}</el-button>
                <el-button type="primary" @click="openExportList">{{ t('common.viewExportList') }}</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 :data="tableData" style="height:73vh;width:82vw">
            <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="name" label="Homily ID" width="120" fixed="left" />
            <el-table-column prop="jwcode" :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="goodsName" :label="t('common_list.productName')" width="130" show-overflow-tooltip />
            <el-table-column prop="goodsNum" :label="t('common_list.productNum')" width="120" />
            <el-table-column prop="refundModel" :label="t('common_list.refundModel')" width="120">
                <template #default="scope">
                    {{ scope.row.refundModel === 1 ? t('common_list.refundModelPart') : t('common_list.refundModelAll')
                    }}
                </template>
            </el-table-column>
            <el-table-column prop="submitter" :label="t('common_list.submitter')" width="120" />
            <el-table-column prop="refundReason" :label="t('common_list.refundReason')" width="120"
                show-overflow-tooltip />
            <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">
                    {{
                        [20].includes(scope.row.status) ? t('cash.statusList.pending') :
                            [30, 40].includes(scope.row.status) ? t('cash.statusList.passed') :
                                [22, 32].includes(scope.row.status) ? t('cash.statusList.rejected') :
                                    scope.row.status === 41 ? t('cash.refundSuccess') : 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 === 20" type="primary" text @click="showAudit(scope.row)">
                            {{ t('common.audit') }}
                        </el-button>
                        <el-button v-else type="primary" text @click="showStep(scope.row)">
                            {{ t('common.viewProgress') }}
                        </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="showAudit2" :title="t('common.audit')" class="audit2" width="35vw" overflow draggable
        style="background-color: #F3FAFE !important;">
        <div class="top">
            <el-button @click="" class="smallTitle" size="small">{{ t('common_add.refundApplyInfo') }}</el-button>
            <div class="top-item">
                <el-text style="width:4vw;" size="small">{{ t('common_add.refundModel') }}</el-text>
                <el-select v-model="auditRow.refundModel" size="small" style="width:10vw;" disabled>
                    <el-option :label="t('common_add.refundModelAll')" :value="0"></el-option>
                    <el-option :label="t('common_add.refundModelPart')" :value="1"></el-option>
                </el-select>
            </div>
            <div class="top-item">
                <el-text style="width:4vw;" size="small">{{ t('common_add.permanentGold') }}</el-text>
                <el-input v-model="auditRow.permanentGold" size="small" style="width:10vw;" disabled /><span>&nbsp;{{
                    t('common.个') }}</span>
            </div>
            <div class="top-item">
                <el-text style="width:4vw;" size="small">{{ t('common_add.freeGold') }}</el-text>
                <el-input v-model="auditRow.freeGold" size="small" style="width:10vw;" disabled /><span>&nbsp;{{
                    t('common.个') }}</span>
            </div>
            <div class="top-item">
                <el-text style="width:4vw;" size="small">{{ t('common_add.refundReason') }}</el-text>
                <el-input v-model="auditRow.refundReason" size="small" style="width:10vw;" :rows="3" maxlength="100"
                    show-word-limit type="textarea" disabled />
            </div>
        </div>
        <el-button @click="" class="smallTitle" size="small">{{ t('common_add.originalOrderInfo') }}</el-button>
        <div class="center">
            <div class="center-left">
                <div class="center-item">
                    <el-text style="width:4vw;" size="small">{{ t('common_add.jwcode') }}</el-text>
                    <el-input v-model="auditRow.jwcode" size="small" style="width:10vw;" disabled />
                </div>
                <div class="center-item">
                    <el-text style="width:4vw;" size="small">{{ t('common_add.market') }}</el-text>
                    <el-input v-model="auditRow.marketName" size="small" style="width:10vw;" disabled />
                </div>
                <div class="center-item">
                    <el-text style="width:4vw;" size="small">{{ t('common_add.productName') }}</el-text>
                    <el-input v-model="auditRow.goodsName" size="small" style="width:10vw;" disabled />
                </div>
                <div class="center-item">
                    <el-text style="width:4vw;" size="small">{{ t('common_add.payCurrency') }}</el-text>
                    <el-input v-model="auditRow.paymentCurrency" size="small" style="width:10vw;" disabled />
                </div>
                <div class="center-item">
                    <el-text style="width:4vw;" size="small">{{ t('common_add.payAmount') }}</el-text>
                    <el-input v-model="auditRow.paymentAmount" size="small" style="width:10vw;" disabled />
                </div>
                <div class="center-item">
                    <el-text style="width:4vw;" size="small">{{ t('common_add.payTime') }}</el-text>
                    <el-input v-model="auditRow.payTime" size="small" style="width:10vw;" disabled />
                </div>
                <div class="center-item">
                    <el-text style="width:4vw;">{{ t('common_add.transferVoucher') }}</el-text>
                    <img v-if="auditRow.payVoucher" :src="auditRow.payVoucher"
                        style="width: 80px; height: 80px; object-fit: cover;">
                    <div v-else>
                        {{ t('common_add.noTransferVoucher') }}
                    </div>
                </div>
            </div>
            <div class="center-right">
                <div class="right-item">
                    <el-text style="width:4vw;" size="small">{{ t('common_add.customerName') }}</el-text>
                    <el-input v-model="auditRow.name" size="small" style="width:10vw;" disabled />
                </div>
                <div class="right-item">
                    <el-text style="width:4vw;" size="small">{{ t('common_add.activity') }}</el-text>
                    <el-input v-model="auditRow.activity" size="small" style="width:10vw;" disabled />
                </div>
                <div class="right-item">
                    <el-text style="width:4vw;" size="small">{{ t('common_add.payMethod') }}</el-text>
                    <el-input v-model="auditRow.payType" size="small" style="width:10vw;" disabled />
                </div>
                <div class="right-item">
                    <el-text style="width:4vw;" size="small">{{ t('common_add.receiveCurrency') }}</el-text>
                    <el-input v-model="auditRow.receivedCurrency" size="small" style="width:10vw;" disabled />
                </div>
                <div class="right-item">
                    <el-text style="width:4vw;" size="small">{{ t('common_add.receiveAmount') }}</el-text>
                    <el-input v-model="auditRow.receivedAmount" size="small" style="width:10vw;" disabled />
                </div>
                <div class="right-item">
                    <el-text style="width:4vw;" size="small">{{ t('common_add.receiveTime') }}</el-text>
                    <el-input v-model="auditRow.receivedTime" size="small" style="width:10vw;" disabled />
                </div>
                <div class="right-item">
                    <el-text style="width:4vw;" size="small">{{ t('common_add.fee') }}</el-text>
                    <el-input v-model="auditRow.handlingCharge" size="small" style="width:10vw;" disabled />
                </div>
                <div class="right-item">
                    <el-text style="width:4vw;" size="small">{{ t('common_add.submitter') }}</el-text>
                    <el-input v-model="auditRow.submitter" size="small" style="width:10vw;" disabled />
                </div>
                <div class="right-item">
                    <el-text style="width:4vw;" size="small">{{ t('common_add.remark') }}</el-text>
                    <el-input v-model="auditRow.remark" size="small" style="width:10vw;" :row="3" maxlength="100"
                        type="textarea" show-word-limit disabled />
                </div>
            </div>
        </div>
        <div class="bottom">
            <el-button class="smallTitle" size="small" v-show="showReject">{{ t('common.rejectInfo') }}</el-button>
            <div class="bottom-item" v-show="showReject">
                <el-text style="width:4vw;" size="small">{{ t('common_add.rejectRemark') }}</el-text>
                <el-input v-model="addForm.remark" :placeholder="t('common_add.rejectRemarkPlaceholder')" size="small"
                    style="width:10vw;" :row="3" maxlength="100" type="textarea" show-word-limit clearable />
            </div>
            <div style="text-align: center;" v-show="!showReject">
                <el-button type="default" @click="showReject = true">{{ t('common.reject') }}</el-button>
                <el-button type="primary" @click="handlePass">{{ t('common.pass') }}</el-button>
            </div>
            <div style="text-align: center;" v-show="showReject">
                <el-button type="default" @click="hideReject">{{ t('common.cancel') }}</el-button>
                <el-button type="primary" @click="handleReject">{{ t('common.confirm') }}</el-button>
            </div>
        </div>
    </el-dialog>

    <el-dialog v-model="showSteps" overflow draggable width="1206px" height="506px" :style="{
        backgroundImage: `url(${RefundChargeBackground})`,
        backgroundSize: 'cover',
        backgroundPosition: 'center'
    }">
        <div class="steps">
            <div class="steps-content">
                <el-steps :active="currentStep" align-center>
                    <el-step>
                        <template #title>
                            <div>
                                {{ t('common_list.submitter') }}<br>{{ submitter || t('common.unknownSubmitter') }}
                            </div>
                        </template>
                        <template #icon>
                            <img src="@/assets/images/refund-approved.png" :alt="t('common.completed')">
                        </template>
                    </el-step>

                    <el-step>
                        <template #title>
                            <div>
                                {{ t('cash.progress.areaFinance') }}<br>{{ areaFinance || t('common.noAuditorRecorded')
                                }}
                            </div>
                        </template>
                        <template #icon>
                            <img v-if="currentStep === 2" src="@/assets/images/refund-rejected.png"
                                :alt="t('common.rejected')">
                            <img v-else-if="currentStep === 1" src="@/assets/images/refund-approving.png"
                                :alt="t('common.pendingAudit')">
                            <img v-else-if="currentStep > 2" src="@/assets/images/refund-approved.png"
                                :alt="t('common.passed')">
                        </template>
                    </el-step>

                    <el-step>
                        <template #title>
                            <div>
                                {{ t('cash.progress.areaCharge') }}<br>{{ areaCharge || t('common.noAuditorRecorded') }}
                            </div>
                        </template>
                        <template #icon>
                            <img v-if="currentStep === 4" src="@/assets/images/refund-rejected.png"
                                :alt="t('common.rejected')">
                            <img v-else-if="currentStep === 3" src="@/assets/images/refund-approving.png"
                                :alt="t('common.pendingAudit')">
                            <img v-else-if="currentStep > 3 && currentStep != 4"
                                src="@/assets/images/refund-approved.png" :alt="t('common.audited')">
                            <img v-else-if="currentStep < 3" src="@/assets/images/refund-waiting.png"
                                :alt="t('common_list.activityStatus.notStarted')">
                        </template>
                    </el-step>

                    <el-step>
                        <template #title>
                            <div>
                                {{ t('cash.progress.headFinance') }}<br>{{ headFinance || t('common.noAuditorRecorded')
                                }}
                            </div>
                        </template>
                        <template #icon>
                            <img v-if="currentStep === 6" src="@/assets/images/refund-rejected.png"
                                :alt="t('common.rejected')">
                            <img v-else-if="currentStep === 5" src="@/assets/images/refund-approving.png"
                                :alt="t('common.pendingAudit')">
                            <img v-else-if="currentStep > 5 && currentStep != 6"
                                src="@/assets/images/refund-approved.png" :alt="t('common.audited')">
                            <img v-else-if="currentStep < 5" src="@/assets/images/refund-waiting.png"
                                :alt="t('common_list.activityStatus.notStarted')">
                        </template>
                    </el-step>

                    <el-step>
                        <template #title>
                            <div>
                                {{ t('cash.progress.executor') }}<br>{{ executor || t('common.noExecutorRecorded') }}
                            </div>
                        </template>
                        <template #icon>
                            <img v-if="currentStep === 7" src="@/assets/images/refund-approving.png"
                                :alt="t('common_list.pending')">
                            <img v-else-if="currentStep === 8" src="@/assets/images/refund-approved.png"
                                :alt="t('common.completed')">
                            <img v-else-if="currentStep < 7" src="@/assets/images/refund-waiting.png"
                                :alt="t('common_list.activityStatus.notStarted')">
                        </template>
                    </el-step>
                </el-steps>
            </div>
            <div class="reject-reason" v-if="isReject">{{ t('common_list.rejectReason') }}：{{ rejectReason }}</div>
            <div class="steps-btn">
                <el-button type="primary" @click="showSteps = false">{{ t('common.confirm') }}</el-button>
            </div>
        </div>
    </el-dialog>

    <el-dialog v-model="exportListVisible" :title="t('common_export.exportList')" width="80%">
        <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>
</template>
<script setup>
import { ref, onMounted, computed } 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 moment from 'moment'
import { productList, CurrencyForId } from '@/views/moneyManage/receiveDetail/utils/staticData.js'
import RefundChargeBackground from '@/assets/images/refund-progress.png'
import { isNumber } from 'lodash'
import { useI18n } from 'vue-i18n'
const { t } = useI18n()

const currentStep = ref(0)// 进度图
const searchForm = ref({
    jwcode: '',
    markets: []
})
const isHeadquarters = computed(() => {
    const m = adminData.value.markets
    return m === t('common.markets.headquarters') || m === '总部' || m === 'Headquarters'
})
const isReject = ref(false)// 进度图有没有驳回状态
const rejectReason = ref('')// 驳回理由，进度图
const addForm = ref({
    remark: ''
})
const showReject = ref(false)
const auditRow = ref({})// 审核回显
const dateRange = ref([])
const pagination = ref({
    pageNum: 1,
    pageSize: 50,
    total: 0
})
const market = ref([])
const showAudit2 = ref(false)
const tableData = ref([])
const showSteps = ref(false)
const submitter = ref('')// 提交人
const areaFinance = ref('')// 地区财务
const areaCharge = ref('')// 地区负责人
const headFinance = ref('')// 总部财务
const executor = ref('')// 指定执行人
const uploadRef = ref(null)
const exportListVisible = ref(false)
const exportList = ref([])
// 导出列表加载状态
const exportListLoading = ref(false)

const statusStepMap = {
    10: [1, false],
    12: [2, true],
    20: [3, false],
    22: [4, true],
    30: [5, false],
    32: [6, true],
    40: [7, false],
    41: [8, 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')
])
const channelOptions = computed(() => [
    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 statusList = computed(() => [
    t('cash.statusList.pending'),
    t('cash.statusList.passed'),
    t('cash.statusList.rejected'),
    t('cash.refundSuccess')
])
// 查全部
const getRefund = async function () {
    if (!hasMenuPermission(menuTree.value, permissionMapping.view_area_manager_refund)) {
        ElMessage.error(t('elmessage.noPermission'))
        return
    }
    try {
        const payCurrencySelect = ref('')
        const statuses = ref([20, 22, 30, 32, 40, 41]) // 看不到进度没到这里的
        if (searchForm.value.statuses === t('cash.statusList.passed')) {
            statuses.value = [30, 40]
        } else if (searchForm.value.statuses === t('cash.statusList.rejected')) {
            statuses.value = [22, 32]
        } else if (searchForm.value.statuses === t('cash.statusList.pending')) {
            statuses.value = [20]
        } else if (searchForm.value.statuses === t('cash.refundSuccess')) {
            statuses.value = [41]
        } else {
            statuses.value = [20, 22, 30, 32, 40, 41]
        }

        const goodsName = searchForm.value.goodsName && searchForm.value.goodsName.length > 0
            ? searchForm.value.goodsName[searchForm.value.goodsName.length - 1] : ''

        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;
        }

        if (searchForm.value.paymentCurrency) {
            payCurrencySelect.value = CurrencyForId(searchForm.value.paymentCurrency)
        }

        const params = {
            pageNum: pagination.value.pageNum,
            pageSize: pagination.value.pageSize,
            cashRecordDTO: {
                jwcode: searchForm.value.jwcode,//精网号
                name: searchForm.value.name,//姓名
                markets: searchForm.value.markets && searchForm.value.markets.length > 0 ? [searchForm.value.markets[searchForm.value.markets.length - 1]] : [],
                goodsName: goodsName,//商品名
                statuses: statuses.value,//10：地区财务待审核；12：地区财务驳回；
                // 20：地区负责人待审核；22：地区负责人驳回；
                // 30：总部财务待审核；32：总部财务驳回；
                // 40：执行人待处理；41：执行人已处理，退款完成；
                paymentCurrency: payCurrencySelect.value,//付款币种
                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') : "",
                adminId: adminData.value.id
            }
        }

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

        tableData.value = result.data.list || []
        pagination.value.total = result.data.total || 0
    } catch (error) {
        ElMessage.error(error.message || t('elmessage.searchFailed'))
    }
}
// 审核通过
const handlePass = async function () {
    if (!hasMenuPermission(menuTree.value, permissionMapping.audit_area_manager_refund)) {
        ElMessage.error(t('elmessage.noPermission'))
        return
    }
    try {
        const params = {
            id: auditRow.value.id,
            status: 30,
            rejectReason: addForm.value.remark,
            areaCharge: adminData.value.adminName,
            auditId: auditRow.value.auditId,
            relatedId: auditRow.value.relatedId
        }
        const result = await API({
            url: '/Money/review',
            data: params
        })
        if (result.code === 200) {
            ElMessage.success(t('elmessage.approveSuccess'))
            showAudit2.value = false
            getRefund()
        }
    } catch (error) {
        ElMessage.error(error.message || t('elmessage.approveFailed'))
    }
}
// 审核驳回
const handleReject = async function () {
    if (!hasMenuPermission(menuTree.value, permissionMapping.audit_area_manager_refund)) {
        ElMessage.error(t('elmessage.noPermission'))
        return
    }
    try {
        const params = {
            id: auditRow.value.id,
            status: 22,
            rejectReason: addForm.value.remark,
            areaCharge: adminData.value.adminName,
            auditId: auditRow.value.auditId,
            orderCode: auditRow.value.orderCode,
            relatedId: auditRow.value.relatedId
        }
        const result = await API({
            url: '/Money/review',
            data: params
        })
        if (result.code === 200) {
            ElMessage.success(t('elmessage.rejectSuccess'))
            getRefund()
            addForm.value.remark = ''
            showAudit2.value = false
            showReject.value = false
        }
    } catch (error) {
        ElMessage.error(error.message || t('elmessage.approveFailed'))
    }
}
const showStep = function (row) {
    if (!hasMenuPermission(menuTree.value, permissionMapping.track_area_manager_refund_progress)) {
        ElMessage.error(t('elmessage.noPermission'))
        return
    }

    rejectReason.value = row.rejectReason || ''
    isReject.value = false
    submitter.value = row.submitter || ''
    areaFinance.value = row.areaFinance || ''
    areaCharge.value = row.areaCharge || ''
    headFinance.value = row.headFinance || ''
    executor.value = row.executorName || ''
    currentStep.value = 1

    const status = row.status
    if (statusStepMap[status]) {
        const [step, reject] = statusStepMap[status]
        currentStep.value = step
        isReject.value = reject
    }

    console.log('步骤条状态', currentStep.value)
    showSteps.value = true
}
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 exportExcel = async function () {
    const payCurrencySelect = ref('')
    const statuses = ref([20, 22, 30, 32, 40, 41]) // 看不到进度没到这里的
    if (searchForm.value.statuses === '审核通过') {
        statuses.value = [30, 40]
    } else if (searchForm.value.statuses === '已驳回') {
        statuses.value = [22, 32]
    } else if (searchForm.value.statuses === '待审核') {
        statuses.value = [20]
    } else if (searchForm.value.statuses === '退款成功') {
        statuses.value = [41]
    } else {
        statuses.value = [20, 22, 30, 32, 40, 41]
    }

    const goodsName = searchForm.value.goodsName && searchForm.value.goodsName.length > 0
        ? searchForm.value.goodsName[searchForm.value.goodsName.length - 1] : ''

    if (searchForm.value.jwcode) {
        const isPositiveInteger = /^[1-9]\d*$/.test(searchForm.value.jwcode);
        if (!isPositiveInteger) {
            ElMessage.error('请输入正确的精网号')
            return
        }
    }
    // 增加精网号长度限制，防止后端400错误
    if (searchForm.value.jwcode.length > 8) {
        ElMessage.error('精网号长度不能超过8位')
        return;
    }

    if (searchForm.value.paymentCurrency) {
        payCurrencySelect.value = CurrencyForId(searchForm.value.paymentCurrency)
    }

    const params = {
        pageNum: pagination.value.pageNum,
        pageSize: pagination.value.pageSize,
        cashRecordDTO: {
            jwcode: searchForm.value.jwcode,//精网号
            name: searchForm.value.name,//姓名
            markets: searchForm.value.markets && searchForm.value.markets.length > 0 ? [searchForm.value.markets[searchForm.value.markets.length - 1]] : [],
            goodsName: goodsName,//商品名
            statuses: statuses.value,//10：地区财务待审核；12：地区财务驳回；
            // 20：地区负责人待审核；22：地区负责人驳回；
            // 30：总部财务待审核；32：总部财务驳回；
            // 40：执行人待处理；41：执行人已处理，退款完成；
            paymentCurrency: payCurrencySelect.value,//付款币种
            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') : "",
            adminId: adminData.value.id
        }
    }
    const res = await API({ url: '/export/exportFinance', data: params })
    if (res.code === 200) {
        ElMessage.success(t('elmessage.exportSuccess'))
    }
}
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 === 12
            })
            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');
    }
}
const hideReject = function () {
    showReject.value = false
    addForm.value.remark = ''
}
const reset = function () {
    searchForm.value = {
        jwcode: '',
        markets: [],
        statuses: []
    }
    // 重置页码
    pagination.value.pageNum = 1
    dateRange.value = []
    getRefund()
}
const showAudit = function (row) {
    auditRow.value = row
    showAudit2.value = true
}
const defaultTime = [
    new Date(2000, 1, 1, 0, 0, 0),
    new Date(2000, 2, 1, 23, 59, 59),
]
const disabledDate = (time) => {
    const limitDate = new Date(2025, 0, 1);
    return time.getTime() < limitDate.getTime();
}
const handlePageSizeChange = function (val) {
    pagination.value.pageSize = val
    getRefund()
}
const handleCurrentChange = function (val) {
    pagination.value.pageNum = val
    getRefund()
}
onMounted(() => {
    getRefund()
    getMarket()
})
</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;
    }
}

.audit1 {
    height: 47vh;

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

.audit2 {
    display: flex;
    justify-content: center;
    height: auto;
    min-height: 40vh;


    .top {
        width: 30vw;
        height: 22vh;

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

    .smallTitle {
        background-color: white;
        color: rgb(64, 158, 255);
        border-color: rgb(64, 158, 255);
        margin-bottom: 0.5vh;
    }

    .center {
        display: flex;
        width: 30vw;
        height: 35vh;

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

        .center-left {
            width: 60%;
            height: 35vh;

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

            :deep(.el-upload--picture-card) {
                width: 4vw !important;
                height: 4vw !important;
                padding: 0 !important;
            }

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

        .center-right {
            height: 35vh;

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

    .bottom {
        width: 30vw;
        height: 12vh;

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

.steps {
    .steps-content {
        padding-top: 15vw;
    }

    .steps-status {
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .reject-reason {
        margin-top: 2vh;
        width: 40%;
        margin-left: 30%;
        background-color: white;
        padding: 1vh;
        border-radius: 10px;
    }

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