<template>
  <el-container class="admin-view panel-block">
    <el-header class="sa-header">
      <div class="sa-title sa-flex sa-row-between">
        <div class="label sa-flex">{{ t('modules.auth.userManagement') }}</div>
        <div>
          <el-button class="sa-button-refresh" icon="RefreshRight" @click="getData()"></el-button>
          <el-button icon="Plus" type="primary" @click="addRow">{{
            t('modules.auth.addAdmin')
          }}</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" @sort-change="fieldFilter" row-key="id" stripe>
          <template #empty>
            <sa-empty />
          </template>
          <el-table-column prop="id" label="ID" min-width="100" sortable="custom">
          </el-table-column>
          <el-table-column prop="name" :label="t('modules.auth.username')" min-width="150">
            <template #default="scope">
              <span class="sa-table-line-1">{{ scope.row.name || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="t('form.status')" min-width="120" align="center">
            <template #default="scope">
              <!-- ID为1的用户状态不可修改 -->
              <el-tag v-if="scope.row.id == 1" :type="scope.row.status === '0' ? 'success' : 'danger'">
                <span>{{ scope.row.status === '0' ? t('common.enabled') : t('common.disabled') }}</span>
              </el-tag>
              <!-- 其他用户可以修改状态 -->
              <el-dropdown v-else popper-class="user-dropdown" @command="handleStatusCommand">
                <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">
                  <span>{{ scope.row.status === '0' ? t('common.enabled') : t('common.disabled') }}</span>
                  <el-icon class="sa-m-l-4">
                    <ArrowDown />
                  </el-icon>
                </el-tag>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item :command="{
                      id: scope.row.id,
                      type: 'enable',
                    }">
                      <span class="status-up">{{ t('common.enable') }}</span>
                    </el-dropdown-item>
                    <el-dropdown-item :command="{
                      id: scope.row.id,
                      type: 'disable',
                    }">
                      <span class="status-down">{{ t('common.disable') }}</span>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
          <el-table-column fixed="right" :label="t('common.actions')">
            <template #default="scope">
              <!-- 修改密码按钮：所有用户都可以 -->
              <el-button link type="warning" @click="changePassword(scope.row)">{{ t('modules.auth.changePassword')
              }}</el-button>

              <!-- ID为1的用户不能编辑和删除 -->
              <template v-if="scope.row.id != 1">
                <el-button link type="primary" @click="editRow(scope.row)">{{ t('common.edit') }}</el-button>
                <el-popconfirm width="fit-content" :confirm-button-text="t('common.confirm')"
                  :cancel-button-text="t('common.cancel')" :title="t('message.confirmDelete')"
                  @confirm="deleteApi(scope.row.id)">
                  <template #reference>
                    <el-button link type="danger">{{ t('common.delete') }}</el-button>
                  </template>
                </el-popconfirm>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-main>
    <sa-view-bar>
      <template #right>
        <sa-pagination :pageData="pageData" @updateFn="getData" />
      </template>
    </sa-view-bar>
  </el-container>
</template>
<script>
export default {
  name: 'admin.auth.admin',
};
</script>
<script setup>
import { onMounted, reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { ArrowDown } from '@element-plus/icons-vue';
import { useModal, usePagination } from '@/sheep/hooks';
import { useI18n } from 'vue-i18n';
import admin from '@/app/admin/api';

const { t } = useI18n();
import AdminEdit from './edit.vue';
import PasswordEdit from './password.vue';

const { pageData } = usePagination();

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

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

  try {
    const { code, data } = await admin.auth.user.userList({
      page: pageData.page,
      size: pageData.size,
      order: table.order,
      sort: table.sort,
      ...searchParams,
    });

    if (code == 200) {
      table.data = data.list;
      pageData.page = data.pageNum;
      pageData.size = data.pageSize;
      pageData.total = data.total;
    }
  } catch (error) {
    console.error('获取数据失败:', error);
  } finally {
    loading.value = false;
  }
}

// table 字段排序
function fieldFilter({ prop, order }) {
  table.order = order == 'ascending' ? 'asc' : 'desc';
  table.sort = prop;
  getData();
}

// 新增人员
function addRow() {
  useModal(
    AdminEdit,
    { title: '新增人员', type: 'add' },
    {
      confirm: () => {
        getData();
      },
    },
  );
}

// 编辑人员
function editRow(row) {
  useModal(
    AdminEdit,
    {
      title: '编辑人员',
      type: 'edit',
      id: row.id,
    },
    {
      confirm: () => {
        getData();
      },
    },
  );
}

// 修改密码
function changePassword(row) {
  useModal(
    PasswordEdit,
    {
      title: '修改密码',
      type: 'password',
      id: row.id,
      name: row.name,
    },
    {
      confirm: () => {
        ElMessage.success('密码修改成功');
      },
    },
  );
}

// 状态切换处理
async function handleStatusCommand(command) {
  try {
    await admin.auth.user.status(command.id);
    ElMessage.success('状态切换成功');
    getData();
  } catch (error) {
    console.error('状态切换失败:', error);
    ElMessage.error('状态切换失败');
  }
}

// 删除人员
async function deleteApi(id) {
  await admin.auth.user.delete({ id });
  getData();
}

onMounted(async () => {
  await getData();
});
</script>
<style lang="scss" scoped>
.login-time {
  font-size: 12px;
  color: var(--sa-font);
}
</style>

<style lang="scss">
.user-dropdown {
  .status-up {
    color: var(--el-color-success);
  }

  .status-down {
    color: var(--el-color-danger);
  }
}
</style>
