<template>
  <el-container class="user-select">
    <el-container>
      <el-header class="user-search">
        <sa-search-simple :searchFields="searchFields" :defaultValues="defaultSearchValues"
          @search="(val) => getData(1, val)" @reset="getData(1)" />
      </el-header>
      <el-main v-loading="loading">
        <el-table class="sa-table" ref="multipleTableRef" :data="table.list" @select="selectRow" @select-all="selectAll"
          stripe>
          <template #empty>
            <sa-empty />
          </template>
          <el-table-column v-if="modal.params.multiple" type="selection" width="48"></el-table-column>
          <el-table-column prop="id" :label="t('modules.userSelect.userId')" align="center" width="80" />
          <el-table-column :label="t('modules.userSelect.userInfo')" min-width="200">
            <template #default="scope">
              <div class="user-info">
                <el-avatar :src="scope.row.headPic" :size="40">
                  <el-icon>
                    <User />
                  </el-icon>
                </el-avatar>
                <div class="user-details">
                  <div class="user-name">{{ scope.row.name || t('modules.userSelect.noNickname')
                  }}</div>
                  <div class="user-phone">{{ scope.row.phoneNo || t('modules.userSelect.noPhone') }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.userSelect.registerTime')" align="center">
            <template #default="scope">
              {{ scope.row.createTime || '-' }}
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.userSelect.status')" align="center" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                {{ scope.row.status === 1 ? t('modules.userSelect.normal') : t('modules.userSelect.disabled') }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column v-if="!modal.params.multiple" :label="t('modules.userSelect.actions')" width="80">
            <template #default="scope">
              <el-button link type="primary" @click="singleSelect(scope.row)">
                {{ t('modules.userSelect.select') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
      <el-footer class="sa-footer--submit" :class="modal.params.multiple ? 'sa-row-between' : 'sa-row-right'">
        <sa-pagination :pageData="pageData" layout="total, prev, pager, next" @updateFn="getData" />
        <el-button v-if="modal.params.multiple" type="primary" @click="confirm">
          {{ t('modules.userSelect.confirmSelect') }}
        </el-button>
      </el-footer>
    </el-container>
  </el-container>
</template>

<script setup>
import { nextTick, onMounted, reactive, ref, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { User } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { usePagination } from '@/sheep/hooks';
import { api } from '../user.service';

const { t } = useI18n();

const { pageData } = usePagination();

const emit = defineEmits(['modalCallBack']);
const props = defineProps(['modal']);

// 搜索字段配置 - 使用计算属性以支持语言切换
const searchFields = computed(() => ({
  name: {
    type: 'input',
    label: t('modules.userSelect.userAccount'),
    placeholder: t('modules.userSelect.enterUserAccount'),
    width: 150,
  },
  phone: {
    type: 'input',
    label: t('modules.userSelect.userPhone'),
    placeholder: t('modules.userSelect.enterPhoneNumber'),
    width: 150,
  },
}));

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

const loading = ref(true);
const table = reactive({
  list: [],
  ids: props.modal.params.ids || [],
  selectedUsers: new Map(),
});

async function getData(page, searchParams = {}) {
  if (page) pageData.page = page;
  loading.value = true;

  try {
    const params = {
      page: pageData.page,
      size: pageData.size,
    };

    // 添加搜索参数
    if (searchParams.name) {
      params.name = searchParams.name;
    }
    if (searchParams.phone) {
      params.phone = searchParams.phone;
    }

    const { code, data } = await api.list.list(params);
    if (code == 200) {
      table.list = data.list || [];
      pageData.page = data.pageNum;
      pageData.size = data.pageSize;
      pageData.total = data.total;

      nextTick(() => {
        setDefaultSelected();
        initSelectedUsers();
      });
    }
  } catch (error) {
    console.error('获取用户列表失败:', error);
    ElMessage.error(t('modules.userSelect.getUserListFailed'));
    table.list = [];
  } finally {
    loading.value = false;
  }
}

// 设置默认选中
function setDefaultSelected() {
  if (!table.list || !Array.isArray(table.list)) {
    return;
  }

  table.list.forEach((item) => {
    if (table.ids?.includes(item.id)) {
      multipleTableRef.value?.toggleRowSelection(item, true);
    }
  });
}

const multipleTableRef = ref();

function selectRow(_, row) {
  if (table.ids.includes(row.id)) {
    let index = table.ids.findIndex((id) => id == row.id);
    table.ids.splice(index, 1);
    table.selectedUsers.delete(row.id);
  } else {
    table.ids.push(row.id);
    addToSelectedUsers(row);
  }
}

function selectAll(selection) {
  if (selection.length == 0) {
    // 取消全选
    table.list.forEach((l) => {
      if (table.ids.includes(l.id)) {
        let index = table.ids.findIndex((id) => id == l.id);
        table.ids.splice(index, 1);
        table.selectedUsers.delete(l.id);
      }
    });
  } else {
    // 全选
    table.list.forEach((l) => {
      if (!table.ids.includes(l.id)) {
        table.ids.push(l.id);
        addToSelectedUsers(l);
      }
    });
  }
}

// 添加用户到选中数据集合
function addToSelectedUsers(item) {
  const userData = {
    id: item.id,
    nickname: item.nickname || item.name,
    phone: item.phoneNo,
    avatar: item.headPic,
    status: item.status,
    name: item.name,
  };
  table.selectedUsers.set(item.id, userData);
}

// 初始化时添加已选中的用户数据
function initSelectedUsers() {
  table.list.forEach((item) => {
    if (table.ids.includes(item.id)) {
      addToSelectedUsers(item);
    }
  });
}

function singleSelect(user) {
  const userData = {
    id: user.id,
    nickname: user.nickname || user.name,
    phone: user.phoneNo,
    avatar: user.headPic,
    status: user.status,
    name: user.name,
  };

  emit('modalCallBack', {
    event: 'confirm',
    data: [userData],
  });
}

function confirm() {
  const selectedUsersData = Array.from(table.selectedUsers.values());

  emit('modalCallBack', {
    event: 'confirm',
    data: selectedUsersData,
  });
}

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

<style lang="scss" scoped>
.user-select {
  .user-search {
    --el-header-height: auto;
    padding-top: var(--sa-padding);
  }

  .sa-footer--submit {
    height: auto;
    padding: 16px;
    border-top: 1px solid var(--sa-border);
    background: #fff;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    --el-footer-height: auto;
    min-height: 60px;
  }

  .user-info {
    display: flex;
    align-items: center;
    gap: 12px;

    .user-details {
      .user-name {
        font-size: 14px;
        color: #333;
        margin-bottom: 4px;
      }

      .user-phone {
        font-size: 12px;
        color: #666;
      }
    }
  }
}
</style>
