<template>
  <div class="finance-page">
    <!-- 今日收益 -->
    <el-card class="summary-card" shadow="hover">
      <div class="card-img">
        <div class="summary-header">
          <span class="title">今日收益</span>
          <el-tooltip content="今日收益=今日已核销到账金额-技术服务费" placement="top">
            <el-icon class="question-icon">
              <QuestionFilled />
            </el-icon>
          </el-tooltip>
          <el-icon class="right-icon" @click="handleTodayIncomeList">
            <ArrowRight />
          </el-icon>
        </div>
        <div class="summary-body">
          <el-image :src="gold" class="gold" />
          <div class="summary-amount">
            <span class="currency">¥</span>
            <span class="amount">{{ todayIncome }}</span>
            <span class="unit">元</span>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 统计信息 -->
    <div class="stat-cards">
      <el-card v-for="stat in stats" :key="stat.key" class="stat-card" shadow="hover">
        <div class="stat-header">
          <span class="stat-title">{{ stat.title }}</span>
          <el-tooltip :content="stat.tooltip" placement="top" v-if="stat.tooltip">
            <el-icon class="question-icon" style="color: #7f9dff">
              <QuestionFilled />
            </el-icon>
          </el-tooltip>
        </div>
        <div class="stat-amount">
          {{ stat.amount }}
        </div>
        <!----:disabled="stat.key === 'withdraw' && isWithdrawDisabled(stat.amount)"-->
        <el-button type="primary" class="stat-btn" @click="handleAction(stat.key)">
          {{ stat.buttonText }}
        </el-button>
      </el-card>
    </div>

    <!-- 重置按钮 -->
    <!-- <el-card class="reset-card" shadow="hover">
      <div class="reset-content">
        <div class="reset-info">
          <h3 class="reset-title">重置到刚注册状态</h3>
          <p class="reset-desc">
            此操作将删除所有入住申请数据、订单、优惠券、验券、消息等相关数据，恢复到刚注册时的初始状态。此操作不可恢复，请谨慎操作！
          </p>
        </div>
        <el-button type="danger" class="reset-btn" @click="handleResetToInitialStatus" :loading="resetLoading">
          重置到刚注册状态
        </el-button>
      </div>
    </el-card> -->
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted, nextTick } from "vue";
import { QuestionFilled, ArrowRight } from "@element-plus/icons-vue";
import gold from "../../assets/financial/gold.png";
import {
  getAccountBalance,
  getTodayIncome,
  getPaymentCycle,
  checkPayPassword,
  resetToInitialStatus
} from "@/api/modules/homeEntry";
import { localGet } from "@/utils/index";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import en from "@/languages/modules/en";
import { pa } from "element-plus/es/locale";
const router = useRouter();
const userInfo = localGet("geeker-user")?.userInfo || {};
onMounted(() => {
  fetchGetTodayIncome();
  fetchAccountBalance();
  fetchGetPaymentCycle0();
  fetchGetPaymentCycle1();
});

const stats = reactive([
  {
    key: "withdraw",
    title: "可提现金额",
    amount: "",
    buttonText: "提现",
    tooltip: "收益产生后3天可提现,28天自动付收益产生日期+3个自然日可提现,若未提现,则按收益产生日期+28个自然日自动付"
  },
  { key: "settled", title: "已到账期金额", amount: "", buttonText: "查看", tooltip: "已到达可提现时间的金额总额" },
  {
    key: "pending",
    title: "未到账期金额",
    amount: "",
    buttonText: "查看",
    tooltip: "未到达可提现时间的账单,您需要等待账单到达结算周期后发起提现"
  }
]);
const handleTodayIncomeList = async () => {
  router.push({ path: "/financialManagement/todayIncomeList" });
};

console.log(stats[0].amount);
//已到账/未到账金额   paymentType 未到传0    已到传1
const fetchGetPaymentCycle0 = async () => {
  let param = {
    storeId: userInfo.storeId,
    startTime: null,
    endTime: null,
    paymentType: 0, //未到
    incomeType: 0,
    pageNum: 1,
    pageSize: 999999
  };
  const res: any = await getPaymentCycle(param as any);
  if (res.code == 200) {
    nextTick(() => {
      stats[2].amount = res.data.money;
    });
  }
};
const fetchGetPaymentCycle1 = async () => {
  let param = {
    storeId: userInfo.storeId,
    startTime: null,
    endTime: null,
    paymentType: 1,
    incomeType: 1,
    pageNum: 1,
    pageSize: 999999
  };
  const res: any = await getPaymentCycle(param as any);
  if (res.code == 200) {
    nextTick(() => {
      stats[1].amount = res.data.money;
    });
  }
};
//可提现金额
const fetchAccountBalance = async () => {
  let param = {
    storeId: userInfo.storeId
  };
  const res: any = await getAccountBalance(param as any);
  if (res.code == 200) {
    nextTick(() => {
      stats[0].amount = res.data.cashOutMoney; //cashOutMoney  可提现金额减未审核通过的金额
    });
  }
};
//今日收益
const todayIncome = ref("");
const fetchGetTodayIncome = async () => {
  let param = {
    storeId: userInfo.storeId
  };
  const res: any = await getTodayIncome(param as any);
  if (res.code == 200) {
    todayIncome.value = res.data;
  }
};

// 判断提现按钮是否禁用
// const isWithdrawDisabled = (amount: any): boolean => {
//   if (!amount && amount !== 0) return true; // 金额为空或undefined
//   const numAmount = typeof amount === 'string' ? parseFloat(amount) : amount;
//   return numAmount === 0 || isNaN(numAmount);
// };

const handleAction = async (key: string) => {
  if (key == "withdraw") {
    // 获取可提现金额
    const withdrawAmount = stats[0].amount;

    // 转换为数字类型
    const numAmount = typeof withdrawAmount === "string" ? parseFloat(withdrawAmount) : Number(withdrawAmount);

    // 校验金额是否小于0.1
    if (isNaN(numAmount) || numAmount < 0.1) {
      // 格式化金额显示
      const formattedAmount = isNaN(numAmount) ? "0.00" : numAmount.toFixed(2);
      ElMessage.warning(`可提现金额不足，最低提现金额为0.1元，当前可提现金额为¥${formattedAmount}元`);
      return;
    }

    // 金额校验通过，继续原有逻辑
    if (userInfo.alipayAccount != null && userInfo.payPassword != null) {
      router.push({ path: "/financialManagement/cashApply" });
    } else {
      router.push({ path: "/financialManagement/realName" });
    }
  }
  if (key == "settled") {
    router.push({ path: "/financialManagement/reconciled" });
  }
  if (key == "pending") {
    router.push({ path: "/financialManagement/unposted" });
  }
};

// 重置到刚注册状态
// const resetLoading = ref(false);
// const handleResetToInitialStatus = async () => {
//   try {
//     // 二次确认
//     await ElMessageBox.confirm(
//       "此操作将删除所有入住申请数据、订单、优惠券、验券、消息等相关数据，恢复到刚注册时的初始状态。此操作不可恢复，是否继续？",
//       "确认重置",
//       {
//         confirmButtonText: "确定",
//         cancelButtonText: "取消",
//         type: "warning",
//         dangerouslyUseHTMLString: false
//       }
//     );

//     resetLoading.value = true;
//     const res: any = await resetToInitialStatus();

//     if (res.code === 200 && res.success) {
//       ElMessage.success(res.msg || "重置成功，已退回到刚注册状态");
//       // 刷新页面数据或跳转到注册成功页面
//       setTimeout(() => {
//         // 可以跳转到注册成功页面或刷新当前页面
//         // router.push({ path: '/register-success' });
//         window.location.reload();
//       }, 1500);
//     } else {
//       ElMessage.error(res.msg || "重置失败，请稍后重试");
//     }
//   } catch (error: any) {
//     // 用户取消操作
//     if (error === "cancel") {
//       return;
//     }
//     console.error("重置失败:", error);
//     ElMessage.error(error?.response?.data?.msg || error?.message || "重置失败，请稍后重试");
//   } finally {
//     resetLoading.value = false;
//   }
// };
</script>

<style scoped lang="scss">
.finance-page {
  display: flex;
  flex-direction: column;
  gap: 20px;
  min-height: calc(100vh - 100px);
}
.summary-card {
  position: relative;
  width: 100%;
  overflow: hidden;
  border: none;
  border-radius: 16px;
  .card-img {
    width: 100%;
    height: 214px;
    background: url("../../assets/financial/financeBg.png") no-repeat;
    background-position: right;
    background-size: contain;
  }
  .summary-header {
    display: flex;
    gap: 8px;
    align-items: center;
    margin-bottom: 12px;
    font-size: 16px;
    color: #333333;
    .question-icon {
      color: #7293f8;
      cursor: pointer;
    }
    .right-icon {
      margin-left: 30px;
      font-weight: bold;
      color: #7293f8;
      cursor: pointer;
    }
  }
  .summary-body {
    display: flex;
    gap: 24px;
    align-items: center;
    justify-content: center;
    width: 757px;
    height: 140px;
    padding: 12px 0;
    margin: auto;
    font-weight: 600;
    background: #6c8ff8;
    border-radius: 74px;
    box-shadow: 0 5px 0 0 #355ac8;
  }
  .summary-amount {
    display: flex;
    gap: 8px;
    align-items: baseline;
    font-weight: 600;
    .currency {
      padding: 8px 16px;
      font-size: 80px;
      color: #ffffff;
      border-radius: 999px 0 0 999px;
    }
    .amount {
      font-size: 80px;
      color: #ffffff;
    }
    .unit {
      font-size: 16px;
      color: #ffffff;
    }
  }
}
.stat-cards {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  .stat-card {
    padding: 16px;
    text-align: center;
    border: none;
    border-radius: 12px;
    .stat-header {
      display: inline-flex;
      gap: 6px;
      align-items: center;
      margin-bottom: 16px;
      font-size: 16px;
      color: #222222;
    }
    .stat-amount {
      margin-bottom: 20px;
      font-size: 32px;
      font-weight: 600;
      color: #222222;
    }
    .stat-btn {
      width: 120px;
      background: #7f9dff;
      border: none;
      border-radius: 6px;
      &:disabled {
        color: #ffffff;
        cursor: not-allowed;
        background: #c0c4cc;
        border-color: #c0c4cc;
      }
    }
  }
}

@media (width <= 1024px) {
  .stat-cards {
    grid-template-columns: repeat(1, 1fr);
  }
}
.reset-card {
  width: 100%;
  border: none;
  border-radius: 12px;
  .reset-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px;
    .reset-info {
      flex: 1;
      .reset-title {
        margin: 0 0 8px;
        font-size: 18px;
        font-weight: 600;
        color: #222222;
      }
      .reset-desc {
        margin: 0;
        font-size: 14px;
        line-height: 1.6;
        color: #666666;
      }
    }
    .reset-btn {
      padding: 12px 32px;
      margin-left: 24px;
      font-size: 16px;
    }
  }
}

@media (width <= 768px) {
  .reset-card {
    .reset-content {
      flex-direction: column;
      gap: 16px;
      align-items: flex-start;
      .reset-btn {
        width: 100%;
        margin-left: 0;
      }
    }
  }
}
</style>
