<script setup lang="ts">
import { ref } from "vue";

import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { getQyUserListApi, getTotalBalanceApi, QyUserDTO, QyUserQuery } from "@/api/qy/qyUser";
import Search from "@iconify-icons/ep/search";
import Refresh from "@iconify-icons/ep/refresh";
import { ElMessage } from "element-plus";
import { useWxStore } from "@/store/modules/wx";

defineOptions({
  name: "UserBalance"
});

const wxStore = useWxStore(); // 微信相关状态管理
const formRef = ref();
const tableRef = ref();

// 搜索表单
const searchFormParams = ref<QyUserQuery & { search?: string }>({
  name: null,
  mobile: null,
  search: null,
  corpid: wxStore.corpid, // 企业ID
  balancePage: 1
});

// 分页参数
const pagination = ref({
  pageSize: 10,
  currentPage: 1,
  total: 0
});

const loading = ref(false);
const dataList = ref<QyUserDTO[]>([]);

const formatCurrency = (value) => {
  return value.toLocaleString('en-US', { 
    minimumFractionDigits: 0, 
    maximumFractionDigits: 2 
  }) || 0 + '元';
};

const balanceData = ref([
  {
    name: '用户总借呗', value: '0元',
  },
  {
    name: '已用总借呗', value: '0元',
  },
  {
    name: '剩余总借呗', value: '0元',
  },
]);

// 获取用户余额列表
const getList = async () => {
  try {
    loading.value = true;
    handleSearchInput(searchFormParams.value.search);
    const { data } = await getQyUserListApi({
      ...searchFormParams.value,
      pageSize: pagination.value.pageSize,
      pageNum: pagination.value.currentPage
    });
    dataList.value = data.rows;
    pagination.value.total = data.total;
  } finally {
    loading.value = false;
  }
};

const handleSearchInput = (value) => {
  // 手机号正则
  const phoneRegex = /^1[3-9]\d{9}$/;

  if (phoneRegex.test(value)) {
    searchFormParams.value.mobile = value;
    searchFormParams.value.name = '';
  } else {
    searchFormParams.value.name = value;
    searchFormParams.value.mobile = '';
  }
};

// 搜索
const onSearch = () => {
  pagination.value.currentPage = 1;
  getList();
};

// 重置
const resetForm = () => {
  formRef.value.resetFields();
  onSearch();
};

// 分页变化
const handlePaginationChange = () => getList();

// 获取总余额
const getTotalBalance = async () => {
  try {
    const { data } = await getTotalBalanceApi(wxStore.corpid);
    balanceData.value[0].value = formatCurrency(data.balanceLimit);
    balanceData.value[1].value = formatCurrency(data.useBalance);
    balanceData.value[2].value = formatCurrency(data.balance);
  } catch (error) {
    console.error('获取总余额失败:', error);
  }
};

// 在getList中调用获取总余额
getList().then(() => getTotalBalance());

</script>

<template>
  <div class="main">
    <el-row :gutter="12" class="data-section">
      <!-- 商店数据 -->
      <el-col :span="4" v-for="item in balanceData" :key="item.name">
        <el-card shadow="never" :body-style="{ padding: ' 20px 0' }" class="todo-card">
          <div class="todo-content">
            <div class="todo-name">{{ item.name }}</div>
            <div class="todo-count">{{ item.value }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!-- <el-form ref="formRef" :inline="true" :model="searchFormParams"
      class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px]">
      <el-form-item label="姓名：" prop="name">
        <el-input @keydown.enter.prevent="onSearch" v-model="searchFormParams.name" placeholder="请输入姓名" clearable
          class="!w-[180px]" />
      </el-form-item>
      <el-form-item label="手机号：" prop="mobile">
        <el-input @keydown.enter.prevent="onSearch" v-model="searchFormParams.mobile" placeholder="请输入手机号" clearable
          class="!w-[180px]" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="useRenderIcon(Search)" @click="onSearch">
          搜索
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm">
          重置
        </el-button>
      </el-form-item>
    </el-form> -->

    <div class="table-container">
      <el-form ref="formRef" :inline="true" :model="searchFormParams" class="search-form bg-bg_color w-[99/100]">
        <el-form-item prop="search">
          <el-input v-model="searchFormParams.search" placeholder="请输入姓名/手机号" clearable class="!w-[300px]"
            @keydown.enter.prevent="onSearch" @change="handleSearchInput" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="useRenderIcon(Search)" @click="onSearch">
            搜索
          </el-button>
        </el-form-item>
      </el-form>

      <el-table ref="tableRef" v-loading="loading" :data="dataList" border>
        <el-table-column label="用户ID" prop="id" width="80" />
        <el-table-column label="姓名" prop="name" width="200" />
        <el-table-column label="借呗" prop="balanceLimit" width="230">
          <template #default="{ row }">{{ formatCurrency(row.balanceLimit) }}</template>
        </el-table-column>
        <el-table-column label="已用借呗" prop="useBalance" width="230">
          <template #default="{ row }">{{ formatCurrency(row.useBalance) }}
          </template>
        </el-table-column>
        <el-table-column label="剩余借呗" prop="balance" width="230">
          <template #default="{ row }">{{ formatCurrency(row.balance) }}
          </template>
        </el-table-column>
        <el-table-column label="手机号" prop="mobile" />
        <!-- <el-table-column label="所属部门" prop="department" /> -->
      </el-table>
      <el-pagination class="table-pagination" v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize" :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper" :total="pagination.total" @size-change="handlePaginationChange"
        @current-change="handlePaginationChange" />
    </div>
  </div>
</template>

<style scoped>
.main {
  padding: 0;
}

.data-section {
  margin-bottom: 0;

  .todo-card {
    height: 100%;
    border: none;

    .todo-content {
      display: flex;
      flex-direction: column;
      align-items: start;
      justify-content: center;
      padding: 10px 0 10px 26px;

      .todo-name {
        font-size: 14px;
        color: var(--el-text-color-regular);
        margin-bottom: 5px;
      }

      .todo-icon {
        margin-bottom: 10px;
        color: var(--el-color-primary);
      }
    }
  }
}

.table-container {
  margin-top: 8px;
  background-color: var(--el-bg-color);
  border-radius: 4px;
  padding: 16px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;

  .el-table {
    flex: 1;
    overflow: hidden;
  }

  .table-pagination {
    margin-top: 10px;
  }
}
</style>