<template>
  <el-container class="withdraw-view panel-block">
    <el-header class="sa-header">
      <!-- 简化搜索组件 -->
      <div class="search-container">
        <sa-search-simple
          :searchFields="searchFields"
          :defaultValues="defaultSearchValues"
          @search="(val) => getData(1, val)"
          @reset="getData(1)"
        >
        </sa-search-simple>
      </div>
      <div class="sa-title sa-flex sa-row-between">
        <div class="label sa-flex">提款管理</div>
        <div>
          <el-button class="sa-button-refresh" icon="RefreshRight" @click="getData()"></el-button>
        </div>
      </div>
    </el-header>
    <el-main class="sa-p-0">
      <div class="sa-table-wrap panel-block panel-block--bottom" v-loading="loading">
        <el-table
          height="100%"
          class="sa-table"
          :data="table.data"
          @selection-change="changeSelection"
          @sort-change="fieldFilter"
          @row-dblclick="editRow"
          row-key="id"
          stripe
        >
          <template #empty>
            <sa-empty />
          </template>
          <el-table-column type="selection" width="48" align="center"></el-table-column>
          <el-table-column prop="id" label="ID" min-width="100" sortable="custom">
          </el-table-column>
          <el-table-column label="用户" min-width="120">
            <template #default="scope">
              <span class="sa-table-line-1">
                {{ scope.row.username || '-' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="提款金额" min-width="120">
            <template #default="scope"> ৳{{ scope.row.amount || 0 }} </template>
          </el-table-column>
          <el-table-column label="手续费" min-width="100">
            <template #default="scope"> ৳{{ scope.row.fee || 0 }} </template>
          </el-table-column>
          <el-table-column label="实际到账" min-width="120">
            <template #default="scope"> ৳{{ scope.row.actual_amount || 0 }} </template>
          </el-table-column>
          <el-table-column label="提款方式" min-width="120">
            <template #default="scope">
              <el-tag :type="scope.row.withdraw_method === 'bank' ? 'primary' : 'success'">
                {{ scope.row.withdraw_method_text || '-' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="状态" min-width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ scope.row.status_text || '-' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="申请时间" min-width="160">
            <template #default="scope">
              {{ scope.row.create_time || '-' }}
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" min-width="150">
            <template #default="scope">
              <el-button class="is-link" type="primary" @click="editRow(scope.row)">查看</el-button>
              <el-button
                v-if="scope.row.status === 'pending'"
                class="is-link"
                type="success"
                @click="approveWithdraw(scope.row)"
              >
                通过
              </el-button>
              <el-button
                v-if="scope.row.status === 'pending'"
                class="is-link"
                type="danger"
                @click="rejectWithdraw(scope.row)"
              >
                拒绝
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-main>
    <sa-view-bar>
      <template #left>
        <sa-batch-handle
          :batchHandleTools="batchHandleTools"
          :selectedLeng="table.selected.length"
          @batchHandle="batchHandle"
        ></sa-batch-handle>
      </template>
      <template #right>
        <sa-pagination :pageData="pageData" @updateFn="getData" />
      </template>
    </sa-view-bar>
  </el-container>
</template>
<script setup>
  import { onMounted, reactive, ref } from 'vue';
  import { api } from '../finance.service';
  import { ElMessageBox, ElMessage } from 'element-plus';
  import { useModal } from '@/sheep/hooks';
  import { usePagination } from '@/sheep/hooks';
  import withdrawEdit from './edit.vue';
  const { pageData } = usePagination();

  // 搜索字段配置
  const searchFields = reactive({
    username: {
      type: 'input',
      label: '用户名',
      placeholder: '请输入用户名',
      width: 200,
    },
    status: {
      type: 'select',
      label: '状态',
      placeholder: '请选择状态',
      width: 150,
      options: [
        { label: '待审核', value: 'pending' },
        { label: '已通过', value: 'approved' },
        { label: '已拒绝', value: 'rejected' },
        { label: '已完成', value: 'completed' },
      ],
    },
  });
  // 默认搜索值
  const defaultSearchValues = reactive({
    username: '',
    status: '',
  });
  // 列表
  const table = reactive({
    data: [],
    order: '',
    sort: '',
    selected: [],
  });
  const loading = ref(true);

  // 获取状态类型
  function getStatusType(status) {
    const statusMap = {
      pending: 'warning',
      approved: 'primary',
      rejected: 'danger',
      completed: 'success',
    };
    return statusMap[status] || 'info';
  }

  // 获取
  async function getData(page, searchParams = {}) {
    if (page) pageData.page = page;
    loading.value = true;
    const { error, data } = await api.withdraw.list({
      page: pageData.page,
      list_rows: pageData.list_rows,
      order: table.order,
      ...searchParams,
      sort: table.sort,
    });
    console.log('API 响应:', error, data);
    if (error === 0) {
      table.data = data.data;
      pageData.page = data.current_page;
      pageData.list_rows = data.per_page;
      pageData.total = data.total;
    }
    loading.value = false;
  }
  // table 字段排序
  function fieldFilter({ prop, order }) {
    table.order = order == 'ascending' ? 'asc' : 'desc';
    table.sort = prop;
    getData();
  }
  //table批量选择
  function changeSelection(row) {
    table.selected = row;
  }
  // 分页/批量操作
  const batchHandleTools = [
    {
      type: 'approve',
      label: '批量通过',
      auth: 'shop.admin.finance.withdraw.approve',
      class: 'success',
    },
    {
      type: 'reject',
      label: '批量拒绝',
      auth: 'shop.admin.finance.withdraw.reject',
      class: 'danger',
    },
  ];

  function editRow(row) {
    useModal(
      withdrawEdit,
      {
        title: '查看提款',
        type: 'view',
        id: row.id,
      },
      {
        confirm: () => {
          getData();
        },
      },
    );
  }

  // 通过提款
  async function approveWithdraw(row) {
    ElMessageBox.confirm('确认通过该笔提款申请?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      const { error } = await api.withdraw.approve(row.id);
      if (error === 0) {
        ElMessage.success('通过成功');
        getData();
      }
    });
  }

  // 拒绝提款
  async function rejectWithdraw(row) {
    ElMessageBox.prompt('请输入拒绝原因', '拒绝提款', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /.+/,
      inputErrorMessage: '拒绝原因不能为空',
    }).then(async ({ value }) => {
      const { error } = await api.withdraw.reject(row.id, { reason: value });
      if (error === 0) {
        ElMessage.success('拒绝成功');
        getData();
      }
    });
  }

  async function batchHandle(type) {
    let ids = [];
    table.selected.forEach((row) => {
      ids.push(row.id);
    });
    switch (type) {
      case 'approve':
        ElMessageBox.confirm('确认通过选中的提款申请?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(async () => {
          const { error } = await api.withdraw.batchApprove(ids.join(','));
          if (error === 0) {
            ElMessage.success('批量通过成功');
            getData();
          }
        });
        break;
      case 'reject':
        ElMessageBox.prompt('请输入拒绝原因', '批量拒绝', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /.+/,
          inputErrorMessage: '拒绝原因不能为空',
        }).then(async ({ value }) => {
          const { error } = await api.withdraw.batchReject(ids.join(','), { reason: value });
          if (error === 0) {
            ElMessage.success('批量拒绝成功');
            getData();
          }
        });
        break;
    }
  }

  onMounted(() => {
    getData();
  });
</script>
<style lang="scss" scoped>
  .withdraw-view {
    .el-header {
      height: auto;
    }
    .el-main {
      .sa-table-wrap {
        height: 100%;
      }
    }
  }
</style>
