<template>
  <el-container class="withdraw-detail">
    <el-main v-loading="loading" :element-loading-text="t('common.loading')">
      <!-- 基本信息 -->
      <div class="basic-info sa-m-b-26">
        <div class="sa-flex sa-row-between sa-m-b-20">
          <h3>{{ t('modules.withdraw.basicInfo') }}</h3>
          <!-- 操作按钮 -->
          <div v-if="[1, 5, 6].includes(withdrawDetail.status)">
            <el-button type="success" plain @click="handleApprove" class="mr-10px">{{ t('modules.withdraw.approve')
            }}</el-button>
            <el-button type="danger" plain @click="handleReject">{{ t('modules.withdraw.reject') }}</el-button>
          </div>
        </div>
        <!-- 第一行 - 提现订单基本信息 -->
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="info-item" :style="{ '--label-width': formLabelWidth }">
              <span class="label">{{ t('modules.withdraw.orderNo') }}：</span>
              <span class="value">{{ withdrawDetail.orderNo || '--' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item" :style="{ '--label-width': formLabelWidth }">
              <span class="label">{{ t('modules.withdraw.userName') }}：</span>
              <span class="value">{{ withdrawDetail.userName || '--' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item" :style="{ '--label-width': formLabelWidth }">
              <span class="label">{{ t('modules.withdraw.phoneNo') }}：</span>
              <span class="value">{{ withdrawDetail.userPhone || '--' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item" :style="{ '--label-width': formLabelWidth }">
              <span class="label">{{ t('modules.withdraw.currency') }}：</span>
              <span class="value">{{ getCurrencyText(withdrawDetail.currency) }}</span>
            </div>
          </el-col>
        </el-row>
        <!-- 第二行 - 用户信息+余额信息 -->
        <el-row :gutter="20" class="sa-m-t-12">
          <el-col :span="6">
            <div class="info-item" :style="{ '--label-width': formLabelWidth }">
              <span class="label">{{ t('modules.withdraw.status') }}：</span>
              <el-tag :type="getStatusType(withdrawDetail.status)">
                {{ getStatusText(withdrawDetail.status) }}
              </el-tag>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item" :style="{ '--label-width': formLabelWidth }">
              <span class="label">{{ t('modules.withdraw.accountType') }}：</span>
              <el-tag :type="withdrawDetail.accountType === 1 ? 'primary' : 'success'">
                {{ getAccountTypeTextLocal(withdrawDetail.accountType) }}
              </el-tag>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item" :style="{ '--label-width': formLabelWidth }">
              <span class="label">{{ t('modules.finance.accountBalance') }}：</span>
              <span class="value">৳{{ withdrawDetail.walletBalance || 0 }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item" :style="{ '--label-width': formLabelWidth }">
              <span class="label">{{ t('modules.finance.commissionBalance') }}：</span>
              <span class="value">৳{{ withdrawDetail.earningsBalance || 0 }}</span>
            </div>
          </el-col>
        </el-row>
        <!-- 第三行 - 银行账户信息 -->
        <el-row :gutter="20" class="sa-m-t-12">
          <el-col :span="6">
            <div class="info-item" :style="{ '--label-width': formLabelWidth }">
              <span class="label">{{ t('modules.withdraw.amount') }}：</span>
              <span class="value">৳{{ withdrawDetail.amount || 0 }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item" :style="{ '--label-width': formLabelWidth }">
              <span class="label">{{ t('modules.withdraw.fee') }}：</span>
              <span class="value">৳{{ withdrawDetail.fee || 0 }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item" :style="{ '--label-width': formLabelWidth }">
              <span class="label">{{ t('modules.withdraw.channel') }}：</span>
              <span class="value">{{ withdrawDetail.channel || '--' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item" :style="{ '--label-width': formLabelWidth }">
              <span class="label">{{ t('modules.withdraw.method') }}：</span>
              <span class="value">{{ withdrawDetail.bank || '--' }}</span>
            </div>
          </el-col>
        </el-row>
        <!-- 第四行 - 提现渠道信息 -->
        <el-row :gutter="20" class="sa-m-t-12">
          <el-col :span="6">
            <div class="info-item" :style="{ '--label-width': formLabelWidth }">
              <span class="label">{{ t('modules.withdraw.receivingBank') }}：</span>
              <span class="value">{{ withdrawDetail.bank || '--' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item" :style="{ '--label-width': formLabelWidth }">
              <span class="label">{{ t('modules.withdraw.accountName') }}：</span>
              <span class="value">{{ withdrawDetail.bankAccountName || '--' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item" :style="{ '--label-width': formLabelWidth }">
              <span class="label">{{ t('modules.withdraw.receivingAccount') }}：</span>
              <span class="value">{{ withdrawDetail.bankAccount || '--' }}</span>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 操作日志 -->
      <div class="operation-logs sa-m-b-26 mt-40px">
        <h3 class="sa-m-b-20">{{ t('modules.withdraw.operationLog') }}</h3>
        <div class="sa-table-wrap">
          <el-table class="sa-table" :data="operationLogs.data" v-loading="operationLogs.loading" stripe border>
            <template #empty>
              <sa-empty />
            </template>
            <el-table-column prop="createTime" :label="t('modules.withdraw.operationTime')" min-width="160"
              align="center">
              <template #default="scope">
                {{ scope.row.createTime || '--' }}
              </template>
            </el-table-column>
            <el-table-column prop="createUser" :label="t('modules.withdraw.operator')" min-width="120" align="center">
              <template #default="scope">
                {{ scope.row.createUser || '--' }}
              </template>
            </el-table-column>
            <el-table-column prop="type" :label="t('modules.withdraw.operationType')" min-width="200">
              <template #default="scope">
                {{ getLogTypeText(scope.row.type) }}
              </template>
            </el-table-column>
            <el-table-column prop="memo" :label="t('modules.withdraw.remark')" min-width="300">
              <template #default="scope">
                {{ scope.row.memo || '--' }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-main>
  </el-container>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useModal, usePagination } from '@/sheep/hooks';
import { useFormConfig } from '@/hooks/useFormConfig';
import { api, financeUtils } from '../finance.service';
import WithdrawAudit from './audit.vue';

const { t } = useI18n();

// 使用表单配置hooks来处理不同语言的宽度
const { formLabelWidth } = useFormConfig({ enWidth: '150px' });

const props = defineProps({
  modal: {
    type: Object,
    default: () => ({}),
  },
});

const withdrawDetail = ref({});
const loading = ref(false);

// 操作日志分页
const { pageData: logPageData } = usePagination();
const operationLogs = reactive({
  data: [],
  loading: false,
  total: 0,
  pageData: logPageData,
});

// 使用公共配置的函数
const getStatusType = (status) => financeUtils.getStatusType(status, 'withdraw');
const getStatusText = financeUtils.getWithdrawStatusText;
const getAccountTypeText = financeUtils.getAccountTypeText;
const getCurrencyText = financeUtils.getCurrencyText;
const getLogTypeText = financeUtils.getLogTypeText;

// 本地账户类型文本函数（解决国际化问题）
const getAccountTypeTextLocal = (accountType) => {
  const typeMap = {
    1: () => t('modules.finance.walletBalance'),
    2: () => t('modules.finance.accountEarnings'),
  };
  const typeFn = typeMap[accountType] || typeMap[parseInt(accountType)];
  return typeFn ? typeFn() : t('common.unknown');
};

// 获取提款详情
async function getWithdrawDetail() {
  if (!props.modal?.params?.id) return;

  loading.value = true;
  try {
    const { code, data } = await api.withdraw.withdrawDetail(props.modal.params.id);
    if (code == '200') {
      withdrawDetail.value = data;
      // 获取详情后更新操作日志
      getOperationLogs();
    }
  } catch (error) {
    console.error('获取提款详情失败:', error);
  } finally {
    loading.value = false;
  }
}

// 获取操作日志 - 从详情数据中获取
function getOperationLogs() {
  operationLogs.loading = true;
  try {
    // 使用详情数据中的 bizLogs
    operationLogs.data = withdrawDetail.value.bizLogs || [];
    operationLogs.total = operationLogs.data.length;
  } catch (error) {
    console.error('获取操作日志失败:', error);
  } finally {
    operationLogs.loading = false;
  }
}

// 审核通过
function handleApprove() {
  useModal(
    WithdrawAudit,
    {
      width: '500px',
      title: '提款审核通过',
      id: withdrawDetail.value.id,
      type: 'approve',
    },
    {
      confirm: () => {
        getWithdrawDetail();
      },
    },
  );
}

// 审核拒绝
function handleReject() {
  useModal(
    WithdrawAudit,
    {
      width: '500px',
      title: '提款审核拒绝',
      id: withdrawDetail.value.id,
      type: 'reject',
    },
    {
      confirm: () => {
        getWithdrawDetail();
      },
    },
  );
}

onMounted(() => {
  getWithdrawDetail();
});
</script>

<style lang="scss" scoped>
.withdraw-detail {
  .operation-buttons {
    .el-button {
      margin-left: 8px;
    }
  }

  .basic-info {
    h3 {
      font-size: 16px;
      font-weight: 600;
      color: var(--sa-title);
    }

    .info-item {
      display: flex;
      align-items: center;
      margin-bottom: 8px;

      .label {
        flex-shrink: 0;
        color: var(--sa-subfont);
        font-size: 14px;
        min-width: var(--label-width, 80px);
      }

      .value {
        color: var(--sa-subtitle);
        font-size: 14px;
        font-weight: 500;
      }
    }
  }

  .operation-logs {
    h3 {
      font-size: 16px;
      font-weight: 600;
      color: var(--sa-title);
    }

    .sa-table {
      border-radius: 8px;
      overflow: hidden;
      border: 1px solid #dcdfe6;

      :deep(.el-table) {
        border: none;
        border-radius: 0;
      }

      :deep(.el-table__header-wrapper) {
        background: var(--sa-table-header-bg, #f5f7fa);

        .el-table__header {
          background: var(--sa-table-header-bg, #f5f7fa);

          th {
            background: var(--sa-table-header-bg, #f5f7fa) !important;
            font-weight: 600;
            color: var(--sa-title, #303133);
            border-bottom: 1px solid #dcdfe6;
            border-right: 1px solid #dcdfe6;

            &:first-child {
              border-left: none;
            }

            &:last-child {
              border-right: none;
            }
          }
        }
      }

      :deep(.el-table__body-wrapper) {
        .el-table__body {
          tr {
            &:hover {
              background: #f5f7fa !important;
            }

            td {
              border-bottom: 1px solid #dcdfe6;
              border-right: 1px solid #dcdfe6;
              border-left: none;

              &:first-child {
                border-left: none;
              }

              &:last-child {
                border-right: none;
              }
            }

            &:last-child td {
              border-bottom: none;
            }
          }
        }
      }
    }
  }
}
</style>
