<template>
  <div class="content">
    <div class="div-card1">
      <el-card class="card1" style="margin-bottom: 0.5vh; min-height: 110px;">
        <div class="row">
          <div class="rowItem">
            <el-text style="width: 4vw;">精网号</el-text>
            <el-input v-model="searchData.jwcode" placeholder="请输入精网号" style="width:10vw;"
                      clearable></el-input>
          </div>
          <div class="rowItem">
            <el-text style="width: 4vw;">客户姓名</el-text>
            <el-input v-model="searchData.name" placeholder="请输入客户姓名" style="width:10vw;"
                      clearable></el-input>
          </div>
          <div class="rowItem">
            <el-text style="width: 4vw;">所属地区</el-text>
            <el-select v-model="searchData.market" placeholder="请选择所属地区" style="width:10vw;" clearable>
              <el-option v-for="item in marketList" :key="item" :label="item" :value="item"/>
            </el-select>
          </div>
          <div v-if="kefu" class="rowItem">
            <el-text style="width: 4vw;">订单状态</el-text>
            <el-select v-model="searchData.status" placeholder="请选择订单状态" style="width: 10vw;" clearable>
              <el-option v-for="item in statusList" :key="item.name" :label="item.name"
                         :value="item.value"/>
            </el-select>
          </div>
          <div v-if="!kefu" class="rowItem">
            <el-text style="width: 4vw;">付款币种</el-text>
            <el-select v-model="searchData.paymentCurrency" placeholder="请选择付款币种" 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;">支付方式</el-text>
            <el-select v-model="searchData.payType" placeholder="请选择支付方式" style="width: 10vw;" clearable>
              <el-option v-for="item in paytypeList" :key="item" :label="item" :value="item"/>
            </el-select>
          </div>
        </div>
        <div class="row" style="margin-top: 10px;">
          <div class="rowItem">
            <el-text style="width: 4vw;">活动名称</el-text>
            <el-select v-model="searchData.activity" placeholdert="请选择活动方式" 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;">产品名称</el-text>
            <el-cascader v-model="searchData.goodsName" :options="productList" style="width: 10vw;"
                         clearable/>
          </div>
          <div class="rowItem" style="width: 30vw">
            <el-text style="width: 4vw; margin-left: 0.5vw;">付款时间</el-text>
            <el-date-picker v-model="getTime" type="datetimerange" range-separator="至"
                            start-placeholder="起始时间" end-placeholder="结束时间" style="width: 22vw; "
                            @change="handleDatePickerChange" :default-time="defaultTime"
                            :disabled-date="disabledDate"/>
          </div>
          <div v-if="!superAdmin" class="buttons">
            <el-button type="primary" @click="search">查询</el-button>
            <el-button type="success" @click="reset">重置</el-button>
            <!-- <el-button type="primary">导出excel</el-button>
            <el-button type="primary" style="background-color: #5870FF;">导出列表</el-button> -->
          </div>
        </div>
        <div v-if="superAdmin" class="row" style="margin-top: 10px;">
          <div class="buttons">
            <el-button type="primary" @click="search">查询</el-button>
            <el-button type="success" @click="reset">重置</el-button>
            <!-- <el-button type="primary">导出excel</el-button>
            <el-button type="primary" style="background-color: #5870FF;">导出列表</el-button> -->
            <el-button v-if="superAdmin" type="primary" @click="checkKefu">切换客服</el-button>
            <el-button v-if="superAdmin" type="success" @click="checkCaiwu">切换地区财务</el-button>
            <el-button v-if="superAdmin" type="success" @click="checkHqCaiwu">切换总部财务</el-button>
          </div>
        </div>
      </el-card>
    </div>


    <div class="div-card2">
      <el-card class="card2">
        <div class="btns">
          <div class="tabs" v-if="caiwu || HQcaiwu">
            <el-button-group>
              <el-button class="btnItem" v-if="caiwu"
                         :style="{ backgroundColor: activeTab === 'wait' ? '#2741DE' : '#E5EBFE', color: activeTab === 'wait' ? 'white' : '#666' }"
                         @click="navigateTo('wait')">
                待审核
              </el-button>
              <el-button class="btnItem"
                         :style="{ backgroundColor: activeTab === 'pass' ? '#2741DE' : '#E5EBFE', color: activeTab === 'pass' ? 'white' : '#666' }"
                         @click="navigateTo('pass')">
                已通过
              </el-button>
              <el-button class="btnItem"
                         :style="{ backgroundColor: activeTab === 'done' ? '#2741DE' : '#E5EBFE', color: activeTab === 'done' ? 'white' : '#666' }"
                         @click="navigateTo('done')">
                已完成
              </el-button>
              <el-button class="btnItem" v-if="caiwu"
                         :style="{ backgroundColor: activeTab === 'reject' ? '#2741DE' : '#E5EBFE', color: activeTab === 'reject' ? 'white' : '#666' }"
                         @click="navigateTo('reject')">
                已驳回
              </el-button>
            </el-button-group>
          </div>
          <div class="btnAdd">
            <el-button @click="openAddForm" type="success" v-if="kefu">添加收款</el-button>
          </div>
        </div>

        <div class="table">
          <el-table :data="tableData" style="width: 80vw;height:54vh;" @sort-change="handleSortChange"
                    :row-style="{ height: '60px' }" :header-cell-style="{ textAlign: 'center' }"
                    :cell-style="{ textAlign: 'center' }">
            <el-table-column type="index" label="序号" 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="姓名" width="110px"/>
            <el-table-column prop="marketName" label="所属地区" width="80px"/>
            <el-table-column prop="activity" label="活动名称" width="120px" show-overflow-tooltip/>
            <el-table-column prop="goodsName" label="产品名称" width="120px"/>
            <el-table-column prop="goodNum" label="产品数量" width="130px">
              <template #default="scope">
                <span v-if="scope.row.goodsName == '金币充值'">{{ scope.row.permanentGold }}</span>
                <span v-else>{{ scope.row.goodNum }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="paymentCurrency" label="付款币种" width="100px">
            </el-table-column>
            <el-table-column prop="paymentAmount" label="付款金额" width="120px">
            </el-table-column>
            <el-table-column prop="receivedCurrency" label="到账币种"
                             v-if="!kefu && activeTab == 'pass' || activeTab == 'done'" width="150px"></el-table-column>
            <el-table-column prop="receivedAmount" label="到账金额"
                             v-if="!kefu && activeTab == 'pass' || activeTab == 'done'" width="150px">
              <template #default="scope">
                <div v-if="!scope.row.receivedAmount">
                  <text style="color: #FA5A1E;">待补充</text>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="handlingCharge" label="手续费"
                             v-if="!kefu && activeTab == 'pass' || activeTab == 'done'" width="150px">
              <template #default="scope">
                <div v-if="!scope.row.handlingCharge == null">
                  <text style="color: #FA5A1E;">待补充</text>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="payType" label="支付方式" width="130px">
            </el-table-column>
            <el-table-column prop="payTime" label="付款时间" width="180px"/>
            <el-table-column prop="voucher" label="转账凭证" width="110px">
              <template #default="scope">
                <div v-if="scope.row.voucher"
                     style="display: flex; justify-content: center; align-items: center; cursor: pointer;"
                     @click="previewImage(scope.row.voucher)">
                  <img :src="scope.row.voucher" alt="支付凭证" style="width: auto; height: 40px;">
                </div>
                <div v-else
                     style="display: flex; justify-content: center; align-items: center; height: 40px;">
                  ——
                </div>
              </template>
            </el-table-column>
            <!-- <el-table-column prop="bankCode" label="银行流水订单号" v-if="caiwu && activeTab == 'pass'"
                width="150px" show-overflow-tooltip></el-table-column> -->
            <el-table-column prop="submitterName" label="提交人" width="150px"
                             show-overflow-tooltip></el-table-column>
            <el-table-column prop="auditName" label="审核人"
                             v-if="!kefu && activeTab == 'pass' || activeTab == 'reject' || activeTab == 'done'"
                             width="150px" show-overflow-tooltip></el-table-column>
            <el-table-column prop="receivedTime" label="到账时间"
                             v-if="!kefu && activeTab == 'pass' || activeTab == 'done'" width="180px">
            </el-table-column>
            <el-table-column prop="remark" label="备注" v-if="activeTab != 'reject'" width="150px"
                             show-overflow-tooltip></el-table-column>
            <el-table-column prop="status" label="订单状态" v-if="activeTab == 'done' && !kefu" width="150px"
                             show-overflow-tooltip>
              <template #default="scope">
                <span v-if="scope.row.status == 6">退款</span>
                <span v-else>正常</span>
              </template>
            </el-table-column>
            <el-table-column prop="auditTime" label="驳回时间" v-if="activeTab == 'reject' && !kefu"
                             width="180px" show-overflow-tooltip></el-table-column>
            <el-table-column prop="rejectReason" label="驳回理由" v-if="activeTab == 'reject' && !kefu"
                             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 v-if="kefu" fixed="right" prop="status" label="订单状态" width="100px">
              <template #default="scope">
                <span v-if="scope.row.status == 0">待审核</span>
                <span v-else-if="scope.row.status == 1 || scope.row.status == 4">已通过</span>
                <span v-else-if="scope.row.status == 2">已驳回</span>
                <span v-else-if="scope.row.status == 5">已撤回</span>
                <span v-else-if="scope.row.status == 6">退款</span>
                <span v-else></span>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="120px"
                             v-if="activeTab != 'reject' && activeTab != 'done'">
              <template #default=scope>
                <el-link v-if="kefu && scope.row.status == 4" style="color: #FA5A1E;"
                         @click="openConfirm('refund', scope.row)">退款
                </el-link>
                <el-link v-else-if="kefu && scope.row.status == 1" style="color: #2741DE;">待填写手续费</el-link>
                <el-link v-else-if="kefu && scope.row.status == 5" style="color: #2741DE;"
                         @click="openAddForm(scope.row)">编辑
                </el-link>
                <el-link v-else-if="kefu && scope.row.status == 0" style="color: #FA5A1E;"
                         @click="openConfirm('recall', scope.row)">撤回
                </el-link>
                <el-link v-else-if="kefu && scope.row.status == 2" style="color: #FA5A1E;"
                         @click="openRejectReason(scope.row.rejectReason)">查看驳回理由
                </el-link>
                <el-link v-else-if="activeTab == 'wait' && !kefu" style="color: #2741DE;"
                         @click="openAuditForm(scope.row)">审核
                </el-link>
                <el-link
                    v-else-if="activeTab == 'pass' && !kefu && !(scope.row.status == 6 || scope.row.status == 4)"
                    style="color: #2741DE;" @click="openEditForm(scope.row)">编辑
                </el-link>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination">
          <el-pagination background :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="recallDialog">
      <div class="close">
        <button @click="closeRecall" class="Btn">关闭</button>
      </div>
      <div class="text">
        <text class="txt">{{ textContent }}</text>
      </div>
      <div class="cancle">
        <button @click="closeRecall" class="Btn">取消</button>
      </div>
      <div class="confirm">
        <button @click="handleRecall" class="Btn">确定</button>
      </div>
    </div>
    <!-- 退款确认 -->
    <div class="recallDialog" v-show="refundConfirmDialog">
      <div class="close">
        <button @click="closeConfirmRefund" class="Btn">关闭</button>
      </div>
      <div class="text">
        <text class="txt">{{ textContent }}</text>
      </div>
      <div class="cancle">
        <button @click="closeConfirmRefund" class="Btn">取消</button>
      </div>
      <div class="confirm">
        <button @click="openRefundDialog" class="Btn">确定</button>
      </div>
    </div>
    <!-- 客服新增弹窗 -->
    <el-dialog class="adddialog" v-model="addFormisible" width="20vw" :before-close="closeAddForm">
      <el-form class="addForm" ref="addFormRef" :rules="addFormRule" :model="addFormData" label-width="4vw"
               label-position="left">
        <el-form-item label="精网号" required prop="jwcode">
          <el-input v-model="addFormData.jwcode" placeholder="请输入精网号" @blur="jwcodeSeachMarket"/>
        </el-form-item>
        <el-form-item label="客户姓名" required prop="name">
          <el-input disabled="true" v-model="addFormData.name" placeholder="请输入客户姓名"/>
        </el-form-item>
        <el-form-item label="所属地区" required prop="market">
          <el-input disabled="true" v-model="addFormData.market" :value="addFormData.marketName"
                    placeholder="请输入所属地区"/>
        </el-form-item>
        <el-form-item label="活动名称" required prop="activity">
          <el-input v-model="addFormData.activity" placeholder="请输入活动名称"/>
        </el-form-item>
        <el-form-item label="产品名称" required @change="ifGold" prop="goodsName">
          <ProductSelect ref="productSelectRef" v-model="addFormData.goodsName"></ProductSelect>
        </el-form-item>
        <el-form-item v-show="!isGold" label="产品数量" required prop="goodNum">
          <div style="padding-right: 50px; display: flex;">
            <el-input style="padding-right: 10px;" v-model="addFormData.goodNum" placeholder="请输入产品数量"/>
            <span style="color: #999999;">{{ productUnit }}</span>
          </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;">永久金币：</span>
            <el-input style="padding-right: 10px; padding-left: 10px; height: 30px; width: 110px;"
                      v-model="addFormData.permanentGold"/>
          </div>
          <div style="padding-right: 5px; display: flex;">
                        <span
                            style="color: #999999; display: flex; white-space: nowrap;align-items: center;">免费金币：</span>
            <el-input style="padding-right: 10px; padding-left: 10px; height: 30px; width: 110px;"
                      v-model="addFormData.freeGold"/>
          </div>
        </div>
        <el-form-item label="付款币种" required prop="paymentCurrency">
          <CurrencySelect v-model="addFormData.paymentCurrency" :items="customOptions" placeholder="请选择付款币种"
                          @change="handleCurrencyChange"/>
        </el-form-item>
        <el-form-item label="付款金额" required prop="paymentAmount">
          <el-input v-model="addFormData.paymentAmount" placeholder="请输入付款金额"/>
        </el-form-item>
        <el-form-item label="支付方式" required prop="payType">
          <CurrencySelect v-model="addFormData.payType" :items="paytypeOptions" placeholder="请选择支付方式"
                          @change="ifGroup">
          </CurrencySelect>
        </el-form-item>
        <el-form-item label="到账地区" required prop="receivedMarket">
          <CurrencySelect v-model="addFormData.receivedMarket" :items="MoneyAddressOptions"
                          :disabled="isGroup" placeholder="请选择到账地区">
          </CurrencySelect>
        </el-form-item>
        <el-form-item label="付款时间" required prop="payTime">
          <el-date-picker type="datetime" placement="right" v-model="addFormData.payTime"
                          placeholder="请选择付款时间"/>
        </el-form-item>
        <el-form-item label="转账凭证" required prop="voucher">
          <div class="pic">
            <el-upload 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="addFormData.voucher" :src="addFormData.voucher" class="avatar"
                   style="height: 100%; width: 100%;  object-fit: cover;"/>
              <el-icon v-else class="avatar-uploader-icon">
                <Plus/>
              </el-icon>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="备注" required prop="remark">
          <el-input v-model="addFormData.remark" type="textarea" :rows="4" placeholder="请输入备注" maxlength="100"
                    show-word-limit/>
        </el-form-item>
      </el-form>
      <template #footer>
                <span class="dialog-footer">
                    <el-button style="background-color: #7E91FF;" @click="closeAddForm">取消</el-button>
                    <el-button v-if="addOrEdit == 1" style="background-color: #2741DE; margin-left: 2.5vw;"
                               type="primary" @click="throttledhandleAddForm">确定</el-button>
                    <el-button v-else-if="addOrEdit == 2" style="background-color: #2741DE; margin-left: 2.5vw;"
                               type="primary" @click="throttledhandleEditForm">编辑</el-button>
                </span>
      </template>
    </el-dialog>
    <!-- 审核弹窗 -->
    <el-dialog class="adddialog" v-model="auditFormisible" width="20vw" :before-close="closeAuditForm">
      <el-form class="addForm" label-width="4vw" label-position="left">
        <el-form-item label="精网号">
          <el-input disabled="true" v-model="auditFormData.jwcode" placeholder="请输入驳回理由"/>
        </el-form-item>
        <el-form-item label="客户姓名">
          <el-input disabled="true" v-model="auditFormData.name" placeholder="请输入客户姓名"/>
        </el-form-item>
        <el-form-item label="所属地区">
          <el-input disabled="true" v-model="auditFormData.market"/>
        </el-form-item>
        <el-form-item label="活动名称">
          <el-input disabled="true" v-model="auditFormData.activity" placeholder="请输入活动名称"/>
        </el-form-item>
        <el-form-item label="产品名称">
          <el-select disabled="true" v-model="auditFormData.goodsName"/>
        </el-form-item>
        <el-form-item label="付款币种">
          <el-select disabled="true" v-model="auditFormData.paymentCurrency" placeholder="请选择付款币种"
                     @change="handleCurrencyChange"/>
        </el-form-item>
        <el-form-item label="付款金额">
          <el-input disabled="true" v-model="auditFormData.paymentAmount" placeholder="请输入付款金额"/>
        </el-form-item>
        <el-form-item label="支付方式">
          <el-select disabled="true" v-model="auditFormData.payType" :items="paytypeOptions"
                     placeholder="请选择支付方式"/>
        </el-form-item>
        <el-form-item label="到账地区">
          <el-select disabled="true" v-model="auditFormData.receivedMarket" placeholder="到账地区"/>
        </el-form-item>
        <el-form-item label="付款时间">
          <el-date-picker disabled="true" type="datetime" v-model="auditFormData.payTime"
                          placeholder="请选择付款时间"/>
        </el-form-item>
        <el-form-item label="转账凭证">
          <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">
              仅支持.jpg .png格式文件≤ 1 MB
            </el-text>
          </div>
        </el-form-item>
        <el-form-item label="备注">
          <el-input disabled="true" v-model="auditFormData.remark" type="textarea" :rows="3"
                    placeholder="请输入备注" maxlength="100" show-word-limit/>
        </el-form-item>
        <el-form-item label="驳回理由" v-if="ifReject" required>
          <el-input v-model="auditFormData.rejectReason" type="textarea" :rows="3" placeholder="请输入驳回理由"
                    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">驳回</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">取消</el-button>
                    <el-button style="background-color: #2741DE; margin-left: 2.5vw;" type="primary"
                               @click="throttledhandelAuditReject">确定</el-button>
                </span>
      </template>
    </el-dialog>
    <!-- 编辑填手续费弹窗 -->
    <el-dialog class="editdialog" v-model="editFormisible" width="20vw" :before-close="closeEditForm">
      <div class="content">
        <div class="left">
          <el-form class="editForm" label-width="4.5vw" label-position="left">
            <el-form-item label="精网号">
              <el-input disabled="true" v-model="editFormData.jwcode" placeholder="请输入驳回理由"/>
            </el-form-item>
            <el-form-item label="客户姓名">
              <el-input disabled="true" v-model="editFormData.name" placeholder="请输入客户姓名"/>
            </el-form-item>
            <el-form-item label="所属地区">
              <el-input disabled="true" v-model="editFormData.marketName" placeholder="请输入所属地区"/>
            </el-form-item>
            <el-form-item label="活动名称">
              <el-input disabled="true" v-model="editFormData.activity" placeholder="请输入活动名称"/>
            </el-form-item>
            <el-form-item label="产品名称">
              <el-select disabled="true" v-model="editFormData.goodsName" placeholder="请选择产品名称"
                         clearable></el-select>
            </el-form-item>
            <el-form-item v-show="!isEditGold" label="产品数量">
              <div style="padding-right: 50px; display: flex;">
                <el-input disabled="true" style="padding-right: 10px;" v-model="editFormData.goodNum"
                          placeholder="请输入产品数量"/>
                <span style="color: #999999;">个</span>
              </div>
            </el-form-item>
            <div v-show="isEditGold" style="margin-bottom: 15px;  display: flex;">
              <div style=" display: flex; ">
                                <span
                                    style="color: #999999; display: flex; white-space: nowrap;align-items: center;">永久金币：</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;">免费金币：</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="付款币种">
              <CurrencySelect :disabled="!ifOnline" v-model="editFormData.paymentCurrency"
                              :items="customOptions" placeholder="请选择付款币种"/>
            </el-form-item>
            <el-form-item label="付款金额">
              <el-input :disabled="!ifOnline" v-model="editFormData.paymentAmount"
                        placeholder="请输入付款金额"/>
            </el-form-item>
            <el-form-item label="支付方式">
              <el-select disabled="true" v-model="editFormData.payType" placeholder="请选择支付方式"
                         clearable></el-select>
            </el-form-item>
            <el-form-item label="到账地区">
              <el-select disabled="true" v-model="editFormData.receivedMarket" placeholder="请选择到账地区"
                         clearable></el-select>
            </el-form-item>
            <el-form-item label="付款时间">
              <el-date-picker disabled="true" type="datetime" v-model="editFormData.payTime"
                              placeholder="请选择付款时间"/>
            </el-form-item>
            <el-form-item label="转账凭证">
              <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">
                  仅支持.jpg .png格式文件≤ 1 MB
                </el-text>
              </div>
            </el-form-item>
            <el-form-item label="备注">
              <el-input disabled="true" v-model="editFormData.remark" type="textarea" :rows="4"
                        placeholder="请输入驳回理由" 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="4.5vw" label-position="left">
            <el-form-item label="到账货币">
              <CurrencySelect v-model="editFormData.receivedCurrency" :items="customOptions"
                              placeholder="请选择到账货币"/>
            </el-form-item>
            <el-form-item label="到账金额" prop="receivedAmount">
              <el-input v-model="editFormData.receivedAmount" placeholder="请输入到账金额"/>
            </el-form-item>
            <el-form-item label="手续费" prop="handlingCharge">
              <el-input v-model="editFormData.handlingCharge" placeholder="请输入手续费"/>
            </el-form-item>
            <!-- <el-form-item label="银行流水订单号">
                <el-input v-model="editFormData.jwcode" placeholder="请输入银行流水订单号" />
            </el-form-item> -->
            <el-form-item label="到账时间">
              <el-date-picker type="datetime" v-model="editFormData.receivedTime" placeholder="请输入到账时间"/>
            </el-form-item>
          </el-form>
          <span class="editBtns">
                        <button class="editBtn1" @click="closeEditForm">
                            <text class="txt">
                                取消
                            </text>
                        </button>
                        <button class="editBtn2" @click="throttledsubmitEditForm">
                            <text class="txt">
                                提交
                            </text>
                        </button>
                    </span>
        </div>
      </div>
    </el-dialog>
    <!-- 新增退款 -->
    <el-dialog v-model="refundDialog" title="退款" 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;">精网号</el-text>
            <el-input v-model="refundFormData.jwcode" style="width:10vw;" disabled/>
          </div>
          <div class="add-item">
            <el-text style="width:4vw;">客户姓名</el-text>
            <el-input v-model="refundFormData.name" style="width:10vw;" disabled/>
          </div>
          <div class="add-item">
            <el-text style="width:4vw;">所属地区</el-text>
            <el-input v-model="refundFormData.marketName" style="width:10vw;" disabled/>
          </div>
          <div class="add-item">
            <el-text style="width:4vw;">活动名称</el-text>
            <el-input v-model="refundFormData.activity" style="width:10vw;" disabled/>
          </div>
          <div class="add-item">
            <el-text style="width:4vw;">产品名称</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;">产品数量</el-text>
            <el-input style="padding-right: 10px; width:10.5vw;" v-model="refundFormData.goodNum"
                      placeholder="请输入产品数量" disabled/>
            <span style="color: #999999;">{{ productUnit }}</span>
          </div>
          <div v-show="isRefundGold" style="margin-bottom: 15px; ">
            <div style=" display: flex; ">
                        <span
                            style="color: #999999; display: flex; white-space: nowrap;align-items: center;">永久金币：</span>
              <el-input style="padding-right: 10px;  height: 30px; width: 110px; margin-bottom: 10px"
                        v-model="refundFormData.permanentGold" disabled/>
            </div>
            <div style="padding-right: 5px; display: flex;">
                        <span
                            style="color: #999999; display: flex; white-space: nowrap;align-items: center;">免费金币：</span>
              <el-input style="padding-right: 10px;  height: 30px; width: 110px;"
                        v-model="refundFormData.freeGold" disabled/>
            </div>
          </div>
          <div class="add-item">
            <el-text style="width:4vw;">付款币种</el-text>
            <el-input v-model="refundFormData.paymentCurrency" style="width:10vw;" disabled/>
          </div>
          <div class="add-item">
            <el-text style="width:4vw;">付款金额</el-text>
            <el-input v-model="refundFormData.paymentAmount" style="width:10vw;" disabled/>
          </div>
          <div class="add-item">
            <el-text style="width:4vw;">支付方式</el-text>
            <el-input v-model="refundFormData.payType" style="width:10vw;" disabled/>
          </div>
          <div class="add-item">
            <el-text style="width:4vw;">付款时间</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">转账凭证</el-text>
            <el-form-item :rules="{ required: true, message: '请上传图片', 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;">备注</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;">退款模式</el-text>
            <el-radio-group v-model="refundFormData.refundModel">
              <el-radio value="0">全部退款</el-radio>
              <el-radio value="1">部分退款</el-radio>
            </el-radio-group>
          </div>
          <div class="add-item">
            <el-text style="width:4vw;">退款理由</el-text>
            <el-input v-model="refundFormData.refundReason" style="width:10vw;" :rows="5" maxlength="150"
                      show-word-limit type="textarea"/>
          </div>
          <div>ps:请在退款理由表明用户的退款需求。</div>
          <div style="display:flex;justify-content: center;margin-top: 5vh;">
            <el-button type="default" @click="">重置</el-button>
            <el-button type="primary" @click="throttledsubmitRefund">提交</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
import {ref, watch, computed, onMounted} from 'vue';
import {storeToRefs} from 'pinia';
import {ElMessage, ElMessageBox} from 'element-plus'
import API from '@/util/http.js'
import {color} from 'echarts';
import {template} from 'lodash';
import CurrencySelect from '@/components/MoneyManage/CurrencySelect.vue'
import ProductSelect from '@/components/MoneyManage/ProductSelect.vue'
import {Search} from '@element-plus/icons-vue';
import request from '@/util/http.js'
import moment from 'moment'
import {useAdminStore} from '@/store/index.js'
import {hasMenuPermission} from '@/utils/menuTreePermission.js'
import {isNode} from 'mathjs';

const adminStore = useAdminStore();
const {menuTree} = storeToRefs(adminStore);
console.log('menutree', menuTree.value);
import _ from 'lodash'
import {addFormRule, editFormRule} from './utils/recriveFormRules.js'
import { productList,MarketNameForId,CurrencyForId,marketList,statusList} from './utils/staticData.js'
//=====================   查询相关        =================================
const tableData = 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 search = () => {
  getlist()
  ElMessage.success('查询成功')
}
const reset = () => {
  searchData.value = {}
  getTime.value = []
  getlist()
}
//获得表格数据接口
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]
    }
    if (searchData.value.paymentCurrency) {
      payCurrencySelect = CurrencyForId(searchData.value.paymentCurrency)
    }
    //角色id 0：客服 1：地方财务 2:总部财务
    let cashRoleId = ''
    let receivedMarket = adminData.value.markets
    if (kefu.value) {
      cashRoleId = '0'
      receivedMarket = ''
    } else if (caiwu.value) {
      cashRoleId = '1'
      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
      }
    } else if (HQcaiwu.value) {
      cashRoleId = '2'
      console.log('ctiveTab.value', activeTab.value);

      if (activeTab.value == 'pass') {
        searchData.value.status = 13
      } else if (activeTab.value == 'done') {
        searchData.value.status = 46
      }
    }
    const result = await request({
      url: '/cashCollection/selectCollection',
      data: {
        ...pageInfo.value,
        cashCollection: {
          ...searchData.value,
          ...getTime.value,
          submitterId: adminData.value.id,
          receivedMarket: MarketNameForId(receivedMarket),
          cashRoleId: cashRoleId,
          paymentCurrency: payCurrencySelect,
          submitterMarket: receivedMarket,
          goodsName: goodsName,
          market: MarketNameForId(searchData.value.market)
        }
      }
    })
    if (result.code == 200) {
      console.log('返回参数：', result);
      tableData.value = result.data.list
      total.value = result.data.total
    } else {
      ElMessage.error('数据异常')
      console.log(result.msg);
    }
  } catch (error) {
    console.log(error);
  }
}
//====================   标签切换  =========================
const activeTab = ref('wait')

const navigateTo = async (tab) => {
  if (tab === 'wait') {
    activeTab.value = 'wait'
    await getlist()
  } else if (tab === 'pass') {
    activeTab.value = 'pass'
    await getlist()
  } else if (tab === 'done') {
    activeTab.value = 'done'
    await getlist()
  } else if (tab === 'reject') {
    activeTab.value = 'reject'
    await getlist()
  }
}
//角色id 0：客服 1：地方财务 2:总部财务
const cashRoleId = ref('')
const kefu = ref(true)
const caiwu = ref(false)
const HQcaiwu = ref(false)
const superAdmin = ref(false)
const checkKefu = () => {
  kefu.value = true
  caiwu.value = false
  HQcaiwu.value = false
  searchData.value = {}
  getlist()
}
const checkCaiwu = () => {
  kefu.value = false
  caiwu.value = true
  HQcaiwu.value = false
  activeTab.value = 'wait'
  searchData.value = {}
  getlist()
}
const checkHqCaiwu = () => {
  kefu.value = false
  caiwu.value = false
  HQcaiwu.value = true
  activeTab.value = 'pass'
  searchData.value = {}
  getlist()
}
//=================  客服新增弹窗   ==================
const addFormData = ref({
  name: '',
  market: '',
  permanentGold: 0,
  freeGold: 0,
  goodsName: ''
})
const addFormRef = ref(null)
const isGold = ref(false)
const isProduct = ref(false)
const selectItems = [
  "AI机构追踪",
  "AI机构出击",
  "AI机构资金",
  "AI机活跃度",
  "超级机构透视",
  "超级机构伏击",
  "超级机构猎杀",
  "超级机构脉搏",
  "超级机构罗盘",
  "静态信息费",
  "博股会员"
];
const productUnit = ref('个')
const ifGold = () => {
  if (addFormData.value.goodsName === '金币充值') {
    isGold.value = true
    addFormData.value.goodNum = 0
  } else {
    isGold.value = false
    if (selectItems.includes(addFormData.value.goodsName)) {
      productUnit.value = '年'
    } else {
      productUnit.value = '个'
    }
  }
}
const isEditGold = ref(false)
const EditifGold = () => {
  if (editFormData.value.goodsName === '金币充值') {
    isEditGold.value = true
  } else {
    isEditGold.value = false
  }
}

//是否为默认归属平台
const isGroup = ref(false)
const ifGroup = () => {
  if (addFormData.value.payType == 'Stripe-链接收款') {
    isGroup.value = true
    addFormData.value.receivedMarket = '香港'
  } else if (addFormData.value.payType == 'PaymentAsia-链接收款') {
    isGroup.value = true
    addFormData.value.receivedMarket = '香港'
  } else if (addFormData.value.payType == 'Ipay88-链接收款') {
    isGroup.value = true
    addFormData.value.receivedMarket = '马来西亚'
  } else {
    isGroup.value = false
  }
}
const addFormisible = ref(false)
const jwcodeSeachMarket = async () => {
  try {
    const result = await request({
      url: '/cashCollection/getNameAndMarket',
      data: addFormData.value.jwcode
    })
    addFormData.value.market = result.data.market
    addFormData.value.marketName = result.data.marketName
    addFormData.value.name = result.data.name
    console.log('返回参数：', result);
  } catch (error) {
    console.log(error);
  }
}
const openRejectReason = (reason) => {
  ElMessageBox.alert(reason, '驳回理由', {
    // if you want to disable its autofocus
    // autofocus: false,
    confirmButtonText: '确认',
    customClass: 'reject-reason-box',
  })
}
const uploadRef = ref()
const addOrEdit = ref(0)  // 1 为新增   2 为编辑
const productSelectRef = ref(null);

const openAddForm = (row) => {
  productSelectRef.value?.resetSelect();
  if (row.jwcode) {
    console.log('编辑回显数据', row);
    addOrEdit.value = 2
    addFormData.value = {...row};
    jwcodeSeachMarket()
    ifGold()
    addFormisible.value = true

  } else {
    addOrEdit.value = 1
    addFormData.value = {
      goodsName: ''
    }
    addFormisible.value = true
  }
}
const closeAddForm = () => {
  addFormisible.value = false
  addFormData.value = {}
  addOrEdit.value = 0
  isGold.value = false
  addFormRef.value?.resetFields();
}
//客服新增
const handleAddForm = async () => {
  try {
    await addFormRef.value.validate();
    if (addFormData.value.payTime) {
      addFormData.value.payTime = moment(addFormData.value.payTime).format('YYYY-MM-DD HH:mm:ss')
    }
    console.log('客服新增的数据', addFormData.value);
    const result = await request({
      url: '/cashCollection/add',
      data: {
        ...addFormData.value,
        submitterId: adminData.value.id,
        permanentGold: (addFormData.value.permanentGold || 0) * 100,
        freeGold: (addFormData.value.freeGold || 0) * 100,
        goodNum: addFormData.value.goodNum || 0,
        paymentCurrency: CurrencyForId(addFormData.value.paymentCurrency) || '',
        receivedMarket: MarketNameForId(addFormData.value.receivedMarket) || '',
        paymentAmount: (addFormData.value.paymentAmount) * 100,
        submitterMarket: adminData.value.markets
      }
    })
    if (result.code == 200) {
      ElMessage.success('添加成功')
      getlist()
      closeAddForm()
    } else {

    }
    console.log('返回参数：', result);
  } catch (error) {
    console.log('出啥错了？', error);
    ElMessage.error('请完善表单信息后提交');
  }
}
//客服提交撤回的编辑记录
const handleEditForm = async () => {
  try {
    if (addFormData.value.payTime) {
      addFormData.value.payTime = moment(addFormData.value.payTime).format('YYYY-MM-DD HH:mm:ss')
    }
    console.log('客服编辑的数据', addFormData.value);
    const result = await request({
      url: '/cashCollection/reSubmit',
      data: {
        ...addFormData.value,
        submitterId: adminData.value.id,
        permanentGold: (addFormData.value.permanentGold || 0) * 100,
        freeGold: (addFormData.value.freeGold || 0) * 100,
        goodNum: addFormData.value.goodNum || 0,
        paymentCurrency: CurrencyForId(addFormData.value.paymentCurrency) || '',
        receivedMarket: MarketNameForId(addFormData.value.receivedMarket) || '',
        paymentAmount: (addFormData.value.paymentAmount) * 100
      }
    })
    if (result.code == 200) {
      ElMessage.success('编辑成功')
      getlist()
      closeAddForm()
    }
    console.log('返回参数：', result);
  } catch (error) {
    console.log(error);
  }
}
//付款币种
const selectedCurrency = ref('');
const customOptions = ref(['美元(USD)', '港币(HKD)', '新币(SGD)', '马币(MYR)', '泰铢(THB)', '加币(CAD)', '越南盾(VDN)', '韩元(KRW)']);

//支付方式
const paytypeOptions = ref(["Stripe-链接收款", "PaymentAsia-链接收款", "Ipay88-链接收款", "银行转账", "刷卡", "现金", "支票", "Grabpay", "Nets", "E-Transfer", "Paypal"])
const MoneyAddressOptions = ref(['马来西亚', '香港', '新加坡', '泰国', '越南HCM', '加拿大'])
const handleCurrencyChange = (option) => {
  console.log('选中的币种:', option);
};

//图片上传
const handleImgSuccess = (response, uploadFile) => {
  try {
    console.log('11', response)
    addFormData.value.voucher = response.data.url
    console.log('22', response.data.url)
  } catch (error) {
    console.log('报错信息', error)
    ElMessage.error(response.msg || '图片上传失败')
  }
}

const handelImgErr = (err) => {
  console.log(err);
  addFormData.value.imageUrl = null
  ElMessage.error("图片上传失败")
}
const beforeUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('图片必须是jpg或png类型!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}
const handleImageChange = (file) => {
  uploadRef.value.submit()
}

const customUpload = async (options) => {
  try {
    const formData = new FormData()
    formData.append('file', options.file)

    const response = await API({
      url: 'https://api.homilychart.com/hljw/api/aws/upload',
      method: 'POST',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    if (response.code === 200 && response.data) {
      handleImgSuccess(response, options.file)
      ElMessage.success('上传成功')
    } else {
      options.onError(response)
      ElMessage.error(response.msg || '上传失败')
    }
  } catch (error) {
    console.error('上传错误:', error)
    ElMessage.error(`上传失败: ${error.msg || error.message || '网络异常'}`)
  }
}

// 预览图片函数

const previewImage = (imageUrl) => {
  // 使用 element-plus 的 el-image 组件实现图片预览功能
  const imageElement = document.createElement('img');
  imageElement.src = imageUrl;
  imageElement.style.maxWidth = '80vw';
  imageElement.style.maxHeight = '80vh';
  const viewer = document.createElement('div');
  viewer.style.position = 'fixed';
  viewer.style.top = '0';
  viewer.style.left = '0';
  viewer.style.width = '100vw';
  viewer.style.height = '100vh';
  viewer.style.backgroundColor = 'rgba(0, 0, 0, 0.7)';
  viewer.style.display = 'flex';
  viewer.style.justifyContent = 'center';
  viewer.style.alignItems = 'center';
  viewer.style.zIndex = '9999';
  viewer.style.overflow = 'auto';
  viewer.appendChild(imageElement);
  document.body.appendChild(viewer);
  viewer.addEventListener('click', () => {
    document.body.removeChild(viewer);
  });
};


//========= 客服新增 退款/撤回 相关 ===============
const refundFormData = ref({})
const refundDialog = ref(false)
const openRefundDialog = () => {
  refundDialog.value = true
  closeConfirmRefund()
}
const closeRefundForm = () => {
  refundDialog.value = false
  refundFormData.value = {}
}

const submitRefund = async () => {
  try {
    const result = await request({
      url: '/Money/add',
      data: {
        jwcode: refundFormData.value.jwcode, // 精网号（必填）
        name: refundFormData.value.name,  // 姓名（必填）
        market: refundFormData.value.marketName,  // 所属地区（必填）
        activity: refundFormData.value.activity, // 活动名称（可选）
        bankCode: refundFormData.value.bankCode,  // 银行流水订单号（必填）
        goodsName: refundFormData.value.goodsName, // 商品名称（必填）
        goodNum: refundFormData.value.goodNum,  // 商品数量（必填，默认0）
        paymentCurrency: refundFormData.value.paymentCurrency,  // 付款币种（必填）
        paymentAmount: (refundFormData.value.paymentAmount) * 100,  // 付款金额（必填）
        receivedCurrency: refundFormData.value.receivedCurrency,  // 到账币种（必填）
        receivedAmount: (refundFormData.value.receivedAmount) * 100,  // 到账金额（必填）
        handlingCharge: (refundFormData.value.handlingCharge) * 100,  // 手续费（可选）
        receivedMarket: refundFormData.value.receivedMarket, // 到账地区（可选）
        payType: refundFormData.value.payType,  // 支付方式（必填）
        payTime: refundFormData.value.payTime,  // 付款时间，格式：yyyy-MM-dd HH:mm:ss（可选）
        receivedTime: refundFormData.value.receivedTime,  // 到账时间，格式：yyyy-MM-dd HH:mm:ss（可选）
        areaServise: adminData.value.adminName,  // 提交人（可选）
        submitterId: adminData.value.id,
        voucher: refundFormData.value.voucher,  // 转账凭证URL（可选）
        remark: refundFormData.value.remark,  // 备注信息（可选）
        refundReason: refundFormData.value.refundReason,  // 退款备注-客服填写（可选）
        refundModel: refundFormData.value.refundModel,  // 退款方式：0-全额，1-部分（可选）
        id: refundFormData.value.id,                      //订单id
        orderCode: refundFormData.value.orderCode,
        permanentGold: (refundFormData.value.permanentGold) * 100 || 0,
        freeGold: (refundFormData.value.freeGold) * 100 || 0
      }
    })
    if (result.code == 200) {
      ElMessage.success('新增退款成功')
      getlist()
      closeRefundForm()
    } else {
      ElMessage.error(result.msg)
      getlist()
    }
    console.log('返回参数：', result);
  } catch (error) {
    console.log(error);
  }
}

//撤回弹窗
const textContent = ref('')
const recallDialog = ref(false)
const refundConfirmDialog = ref(false)
const RecallNum = ref('')
const isRefundGold = ref(false)
const ifRefundGold = () =>{
  if (refundFormData.value.goodsName === '金币充值') {
    isRefundGold.value = true
    refundFormData.value.goodNum = 0
  } else {
    isRefundGold.value = false
    if (selectItems.includes(refundFormData.value.goodsName)) {
      productUnit.value = '年'
    } else {
      productUnit.value = '个'
    }
  }
}
const openConfirm = (val, row) => {
  console.log('打开弹窗', val, row);
  if (val == 'refund') {
    textContent.value = '将要对该订单退款!'
    refundFormData.value = {...row}
    ifRefundGold()
    console.log('ifRefundGold',)
    refundConfirmDialog.value = true

  }
  if (val == 'recall') {
    textContent.value = '将要撤回该信息!'
    recallDialog.value = true
    RecallNum.value = row.orderCode
  }
}
const closeRecall = () => {
  recallDialog.value = false
  textContent.value = ''
  RecallNum.value = ''
}
const handleRecall = async () => {
  try {
    const result = await request({
      url: '/cashCollection/cancel',
      data: {
        orderCode: RecallNum.value,
      }
    })
    if (result.code == 200) {
      ElMessage.success('撤回成功')
      getlist()
      closeRecall()
    }
    console.log('返回参数：', result);
  } catch (error) {
    console.log(error);
  }
}
const closeConfirmRefund = () => {
  refundConfirmDialog.value = false
  textContent.value = ''
}
//==================  财务编辑相关     =========================
const editFormData = ref({})

const ifOnline = ref(false)
const editFormisible = ref(false)
const editFormRef = ref(null)
const openEditForm = (row) => {
  console.log('编辑时该行数据：', row);
  editFormData.value = row
  EditifGold()
  if (row.status == 3) {
    ifOnline.value = true
  } else {
    ifOnline.value = false
  }
  editFormisible.value = true
}
const closeEditForm = () => {
  editFormisible.value = false
  editFormData.value = {}
  getlist()
}
//提交编辑
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')
    }
    const result = await request({
      url: '/cashCollection/complete',
      data: {
        orderCode: editFormData.value.orderCode,
        handlingCharge: editFormData.value.handlingCharge * 100,
        paymentCurrency: CurrencyForId(editFormData.value.paymentCurrency),
        paymentAmount: (editFormData.value.paymentAmount) * 100,
        receivedCurrency: CurrencyForId(editFormData.value.receivedCurrency),
        receivedAmount: editFormData.value.receivedAmount * 100,
        receivedTime: editFormData.value.receivedTime,
        receivedRemark: editFormData.value.receivedRemark,
      }
    })
    if (result.code == 200) {
      ElMessage.success('提交成功')
      getlist()
      closeEditForm()
    }
    console.log('返回参数：', result);
  } catch (error) {
    console.log(error);
    ElMessage.error('请检查表单数据格式');
  }
}
//==================  审核相关     =========================
const auditFormData = ref({})
//财务通过审核请求
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('审核成功')
      getlist()
      closeAuditForm()
    } else {
      ElMessage.error(result.msg)
      getlist()
    }
    console.log('返回参数：', result);
  } catch (error) {
    console.log(error);
  }
}

//财务驳回审核请求
const handelAuditReject = async () => {
  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('审核成功')
      getlist()
      closeAuditForm()
    }
    console.log('返回参数：', result);
  } catch (error) {
    console.log(error);
  }
}
const auditFormisible = ref(false)
//判断弹窗中是否展示驳回
const ifReject = ref(false)

const openAuditForm = (row) => {
  console.log('这是审核的数据', row);

  auditFormData.value = {
    ...row,
    market: row.marketName
  }
  auditFormisible.value = true
}
const countdown = ref(0);          // 倒计时秒数
const isBtnDisabled = ref(false);  // 按钮是否禁用
const btnText = ref('通过(3)');    // 按钮显示的文字

const closeAuditForm = () => {
  ifReject.value = false
  auditFormisible.value = false
  auditFormData.value = {}
}
//倒计时控制通过按钮
watch(auditFormisible, (val) => {
  if (val) {
    countdown.value = 3
    isBtnDisabled.value = true
    btnText.value = `通过(${countdown.value})`

    const timer = setInterval(() => {
      countdown.value--
      btnText.value = `通过(${countdown.value})`
      console.log(btnText.value);

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

})
//========================分页相关==================
const pageInfo = ref({
  pageSize: 10,
  pageNum: 1
})
const total = ref(0)

const handlePagination = (type, val) => {
  if (type === 'size') {
    pageInfo.value.pageSize = val
  } else {
    pageInfo.value.pageNum = val
  }
  getlist()
}

// ============   已驳回相关      ===========================
// 提示框状态管理
const showTooltip = ref(false);
const tooltipContent = ref('');
const tooltipLeft = ref(0);
const tooltipTop = ref(0);
const tooltipWidth = 200;
// 鼠标进入时显示提示框
const handleMouseEnter = (e, content) => {
  if (content) {
    showTooltip.value = true;
    tooltipContent.value = content;
    handleMouseMove(e);
  }
};

// 鼠标离开时隐藏提示框
const handleMouseLeave = () => {
  showTooltip.value = false;
  tooltipContent.value = '';
};

// 鼠标移动时更新提示框位置（显示在鼠标左侧）
const handleMouseMove = (e) => {
  // 左侧显示：鼠标X坐标 - 提示框宽度 - 偏移量
  tooltipLeft.value = e.clientX - tooltipWidth - 10;
  // Y坐标与鼠标保持一致（垂直居中对齐）
  tooltipTop.value = e.clientY - 10;
};


const adminData = ref({})
// 获取管理员信息
const getAdminData = async function () {
  try {
    const result = await API({
      url: '/admin/userinfo',
      data: {}
    })
    adminData.value = result
    console.log('请求成功', result)
  } catch (error) {
    console.log('请求失败', error)
  }
}

const paytypeList = ["Stripe-链接收款", "PaymentAsia-链接收款", "Ipay88-链接收款", "银行转账", "刷卡", "现金", "支票", "Grabpay", "Nets", "E-Transfer", "Paypal"]
const activityList = ref([])


// 获取活动信息
const getActivitys = async function () {
  try {
    const result = await API({
      url: '/cashCollection/getActivityList',
      data: {}
    })
    if (result.code == 200) {
      activityList.value = result.data
      console.log('请求成功', result)
    } else {
      ElMessage.error('活动列表获取失败')
      console.log('活动列表获取失败', result.msg);

    }
  } catch (error) {
    console.log('请求失败', error)
  }
}



//节流
const throttledhandleAddForm = _.throttle(handleAddForm, 5000, {
  trailing: false
})
const throttledhandleEditForm = _.throttle(handleEditForm, 5000, {
  trailing: false
})
const throttledhandelAuditReject = _.throttle(handelAuditReject, 5000, {
  trailing: false
})
const throttledsubmitEditForm = _.throttle(submitEditForm, 5000, {
  trailing: false
})
const throttledsubmitRefund = _.throttle(submitRefund, 5000, {
  trailing: false
})
onMounted(async function () {
  await getAdminData()
  await getActivitys()
  if (hasMenuPermission(menuTree.value, 77) && hasMenuPermission(menuTree.value, 78) && hasMenuPermission(menuTree.value, 79)) {
    superAdmin.value = true
    getlist()
  } else if (hasMenuPermission(menuTree.value, 77)) {
    checkKefu()
  } else if (hasMenuPermission(menuTree.value, 78)) {
    checkCaiwu()
  } else if (hasMenuPermission(menuTree.value, 79)) {
    checkHqCaiwu()
  }
})
</script>
<style scoped lang="scss">
.content {
  //整体内容
  height: 100%;
  width: 80vw;

  .card1 {
    // 筛选框
    width: 100%;

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

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

      .buttons {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-left: 10px;
      }
    }
  }


  .div-card2 {
    // 下方数据展示card
    width: 100%;

    margin-top: 2vh;

    .btns {
      //切换标签
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding-bottom: 10px;

      .tabs {
        min-width: 300px;

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

      .btnAdd {
        padding-left: 10px;
      }
    }


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

  .recallDialog {
    //撤回弹窗提示
    height: 392px;
    width: 700px;
    background-image: url('/src/assets/收款明细撤回背景.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;
      }
    }
  }

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

      .moneyType {
        position: relative;
        width: 100%;


      }
    }

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

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

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

      }
    }


  }

  .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(.adddialog .el-form-item__label) {
    //设置新增弹窗表头
    min-width: 80px;
    width: auto;
    font-weight: 800;
    padding-bottom: 15px;
  }
}

// 搜索的卡片样式
.card1 {
  background: #F3FAFE;
}

// 表单的卡片样式
.card2 {
  background: #E7F4FD;
}


// 表头背景等
: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;
  /* 处理换行符，避免内容挤在一起 */
}
</style>