<template>
  <el-container class="user-list-view panel-block">
    <el-header class="sa-header">
      <!-- 搜索组件 -->
      <div class="search-container">
        <sa-search-simple :searchFields="searchFields" :defaultValues="defaultSearchValues"
          v-model="currentSearchParams" @search="handleSearch" @reset="handleReset">
          <template #custom="{ data }">
            <el-form-item :label="t('modules.user.registrationTime')">
              <el-date-picker v-model="data.dateRange" type="daterange" :range-separator="t('common.to')"
                :start-placeholder="t('common.startDate')" :end-placeholder="t('common.endDate')" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" style="width: 240px" />
            </el-form-item>
          </template>
        </sa-search-simple>
      </div>

      <div class="sa-title sa-flex sa-row-between">
        <div class="label sa-flex">
          <span class="left">{{ t('modules.user.userList') }}</span>
        </div>
        <div>
          <el-button class="sa-button-refresh" icon="RefreshRight" @click="getData()"></el-button>
          <el-button icon="Download" type="primary" :loading="exportLoading" :disabled="exportLoading"
            @click="exportUsers">
            {{ exportLoading ? t('common.exporting') : t('common.exportData') }}
          </el-button>
        </div>
      </div>
    </el-header>
    <el-main class="sa-p-0">
      <div class="sa-table-wrap" v-loading="loading">
        <el-table height="100%" class="sa-table" :data="table.data" @selection-change="changeSelection"
          @sort-change="fieldFilter" 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="t('modules.user.userId')" min-width="120" sortable="custom">
            <template #default="scope">
              <span class="user-id">{{ scope.row.userNo }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.user.userName')" min-width="120">
            <template #default="scope">
              <div class="user-info">
                {{ scope.row.name || '-' }}
              </div>
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.user.userPhone')" min-width="124">
            <template #default="scope">
              {{ scope.row.phoneNo || '-' }}
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.user.userLevel')" min-width="100" align="center">
            <template #default="scope">
              <el-tag type="primary" size="small">V{{ scope.row.vipLevel }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.user.inviteFriends')" min-width="120" align="center">
            <template #default="scope">
              {{ scope.row.inviteNum || 0 }}
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.user.teamMembers')" min-width="130" align="center">
            <template #default="scope">
              {{ scope.row.teamNum || 0 }}
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.user.successOrders')" min-width="124" align="center">
            <template #default="scope">
              {{ scope.row.successGroupNum || 0 }}
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.user.accountBalance')" min-width="130" align="center">
            <template #default="scope">
              <span class="amount">৳{{ scope.row.walletBalance || '0' }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.user.commissionBalance')" min-width="160" align="center">
            <template #default="scope">
              <span class="amount">৳{{ scope.row.earningsBalance || '0' }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.user.loginPermission')" min-width="140" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.hasLogin === 1 ? 'success' : 'danger'" size="small">
                {{ scope.row.hasLogin === 1 ? t('common.allow') : t('common.forbid') }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.user.orderPermission')" min-width="140" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.hasOrder === 1 ? 'success' : 'danger'" size="small">
                {{ scope.row.hasOrder === 1 ? t('common.allow') : t('common.forbid') }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.user.withdrawPermission')" min-width="170" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.hasWithdraw === 1 ? 'success' : 'danger'" size="small">
                {{ scope.row.hasWithdraw === 1 ? t('common.allow') : t('common.forbid') }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column :label="t('common.memo')" min-width="120">
            <template #default="scope">
              {{ scope.row.memo || '--' }}
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.user.registrationTime')" min-width="160">
            <template #default="scope">
              {{ scope.row.createTime || '-' }}
            </template>
          </el-table-column>
          <el-table-column fixed="right" :label="t('common.actions')" min-width="250">
            <template #default="scope">
              <el-button class="is-link" type="primary" @click="viewDetail(scope.row)">
                {{ t('common.detail') }}
              </el-button>
              <el-button class="is-link" type="primary" @click="editRow(scope.row)">
                {{ t('common.edit') }}
              </el-button>
              <el-button class="is-link" type="warning" @click="changePassword(scope.row)">
                {{ t('modules.user.changePassword') }}
              </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, computed } from 'vue';
import { api } from '../user.service';
import { ElMessageBox, ElMessage } from 'element-plus';
import { useModal } from '@/sheep/hooks';
import { usePagination } from '@/sheep/hooks';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();
import userEdit from './edit.vue';
import userDetail from './detail.vue';
import userPassword from './password.vue';
const { pageData } = usePagination();

// 搜索字段配置 - 使用computed确保语言切换时更新
const searchFields = computed(() => ({
  name: {
    type: 'input',
    label: t('modules.user.userAccount'),
    placeholder: t('form.inputUserAccount'),
    width: 200,
  },
  phone: {
    type: 'input',
    label: t('modules.user.userPhone'),
    placeholder: t('form.inputPhone'),
    width: 150,
  },
  hasLogin: {
    type: 'select',
    label: t('modules.user.loginPermission'),
    placeholder: t('form.selectLoginPermission'),
    width: 120,
    options: [
      { label: t('common.all'), value: '' },
      { label: t('common.allow'), value: 1 },
      { label: t('common.forbid'), value: 2 },
    ],
  },
  hasOrder: {
    type: 'select',
    label: t('modules.user.orderPermission'),
    placeholder: t('form.selectOrderPermission'),
    width: 120,
    options: [
      { label: t('common.all'), value: '' },
      { label: t('common.allow'), value: 1 },
      { label: t('common.forbid'), value: 2 },
    ],
  },
  hasWithdraw: {
    type: 'select',
    label: t('modules.user.withdrawPermission'),
    placeholder: t('form.selectWithdrawPermission'),
    width: 120,
    options: [
      { label: t('common.all'), value: '' },
      { label: t('common.allow'), value: 1 },
      { label: t('common.forbid'), value: 2 },
    ],
  },
}));

// 默认搜索值
const defaultSearchValues = reactive({
  name: '',
  phone: '',
  hasLogin: '',
  hasOrder: '',
  hasWithdraw: '',
});

// 列表
const table = reactive({
  data: [],
  order: '',
  sort: '',
  selected: [],
});
const loading = ref(true);

// 获取数据
async function getData(page, searchParams = null) {
  if (page) pageData.page = page;
  loading.value = true;

  // 构建请求参数 - 优先使用传入的参数，否则使用双向绑定的搜索条件
  const finalSearchParams = searchParams !== null ? searchParams : currentSearchParams.value;

  const requestData = {
    page: pageData.page,
    size: pageData.size,
    type: 0,
    ...finalSearchParams,
  };

  // 处理时间范围搜索
  if (finalSearchParams.dateRange && finalSearchParams.dateRange.length === 2) {
    requestData.startTime = finalSearchParams.dateRange[0];
    requestData.endTime = finalSearchParams.dateRange[1];
    delete requestData.dateRange;
  }

  const { code, data } = await api.list.list(requestData, false);

  if (code == '200') {
    table.data = data.list;
    pageData.page = data.pageNum;
    pageData.size = data.pageSize;
    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: 'delete',
  //   get label() {
  //     return t('common.delete');
  //   },
  //   auth: 'shop.admin.user.list.delete',
  //   class: 'danger',
  // },
];
// 查看详情
function viewDetail(row) {
  useModal(
    userDetail,
    {
      title: t('modules.user.userDetail'),
      type: 'view',
      width: '80%',
      class: 'sa-modal-big',
      id: row.id,
    },
    {
      confirm: () => {
        getData();
      },
    },
  );
}

function addRow() {
  useModal(
    userEdit,
    { title: t('modules.user.addUser'), type: 'add' },
    {
      confirm: () => {
        getData();
      },
    },
  );
}

// 当前搜索参数状态
const currentSearchParams = ref({});

// 导出loading状态
const exportLoading = ref(false);

// 搜索处理函数
function handleSearch(searchParams) {
  // 由于使用了 v-model，currentSearchParams 会自动更新
  // 直接调用 getData，会自动使用当前的搜索条件
  getData(1);
}

// 重置搜索参数处理函数
function handleReset() {
  // 由于使用了 v-model，currentSearchParams 会自动清空
  // 直接调用 getData，会自动使用当前的搜索条件
  getData(1, {});
}

// 导出用户数据
async function exportUsers() {
  if (exportLoading.value) return; // 防止重复点击

  exportLoading.value = true;
  try {
    // 构建导出参数，与列表请求参数保持一致，但排除分页相关数据
    const exportParams = {
      type: 0, // 固定参数
      ...currentSearchParams.value, // 当前搜索参数
    };

    // 处理时间范围搜索（与 getData 函数保持一致）
    if (exportParams.dateRange && exportParams.dateRange.length === 2) {
      exportParams.startTime = exportParams.dateRange[0];
      exportParams.endTime = exportParams.dateRange[1];
      delete exportParams.dateRange;
    }

    // 调用导出API，所有下载逻辑都在REPORT函数中处理
    await api.list.report(exportParams, '用户数据');
  } finally {
    exportLoading.value = false;
  }
}

function editRow(row) {
  useModal(
    userEdit,
    {
      title: t('modules.user.editUser'),
      type: 'edit',
      id: row.id,
    },
    {
      confirm: () => {
        getData();
      },
    },
  );
}

function changePassword(row) {
  useModal(
    userPassword,
    {
      title: t('modules.user.changePassword'),
      width: '500px',
      id: row.id,
    },
    {
      confirm: () => {
        // 密码修改成功后不需要刷新列表
      },
    },
  );
}
// 删除api 单独批量可以直接调用
async function deleteApi(id) {
  await api.list.delete(id);
  getData();
}
async function batchHandle(type) {
  let ids = [];
  table.selected.forEach((row) => {
    ids.push(row.id);
  });
  switch (type) {
    case 'delete':
      ElMessageBox.confirm(t('message.deleteConfirm'), t('common.tip'), {
        confirmButtonText: t('common.confirm'),
        cancelButtonText: t('common.cancel'),
        type: 'warning',
      }).then(() => {
        deleteApi(ids.join(','));
      });
      break;
  }
}

onMounted(() => {
  getData();
});
</script>
<style lang="scss">
.sa-modal-big {
  max-height: 80vh !important;
}
</style>
