<script setup lang="ts">
import type { FormInstance } from 'element-plus';

import { computed, markRaw, nextTick, onMounted, ref } from 'vue';

import {
  Delete,
  Lock,
  MoreFilled,
  Plus,
  Upload,
} from '@element-plus/icons-vue';
import {
  ElAvatar,
  ElButton,
  ElDropdown,
  ElDropdownItem,
  ElDropdownMenu,
  ElMessage,
  ElMessageBox,
  ElTable,
  ElTableColumn,
} from 'element-plus';

import { api } from '#/api/request';
import defaultAvatar from '#/assets/defaultUserAvatar.png';
import HeaderSearch from '#/components/headerSearch/HeaderSearch.vue';
import ListPageShell from '#/components/page/ListPageShell.vue';
import PageData from '#/components/page/PageData.vue';
import { $t } from '#/locales';
import { useDictStore } from '#/store';

import SysAccountImportModal from './SysAccountImportModal.vue';
import SysAccountModal from './SysAccountModal.vue';

onMounted(() => {
  initDict();
});

const pageDataRef = ref();
const tableRef = ref();
const importDialog = ref();
const saveDialog = ref();
const selectedRows = ref<any[]>([]);
const batchActionLoading = ref(false);
const dictStore = useDictStore();
const selectedCount = computed(() => selectedRows.value.length);
const headerButtons = [
  {
    key: 'create',
    text: $t('button.add'),
    icon: markRaw(Plus),
    type: 'primary',
    data: { action: 'create' },
    permission: '/api/v1/sysAccount/save',
  },
  {
    key: 'import',
    text: $t('button.import'),
    icon: markRaw(Upload),
    data: { action: 'import' },
    permission: '/api/v1/sysAccount/save',
  },
];

function initDict() {
  dictStore.fetchDictionary('dataStatus');
}
const handleSearch = (params: string) => {
  pageDataRef.value.setQuery({ loginName: params, isQueryOr: true });
};
function clearSelection() {
  selectedRows.value = [];
  tableRef.value?.clearSelection?.();
}
async function reloadPage() {
  await pageDataRef.value?.reload?.();
  await nextTick();
  clearSelection();
}
function reset(formEl?: FormInstance) {
  formEl?.resetFields();
  clearSelection();
  pageDataRef.value.setQuery({});
}
function showDialog(row: any) {
  saveDialog.value.openDialog({ ...row });
}
function openImportDialog() {
  importDialog.value.openDialog();
}
function handleHeaderButtonClick(payload: any) {
  if (payload?.key === 'import') {
    openImportDialog();
    return;
  }
  showDialog({});
}
function remove(row: any) {
  ElMessageBox.confirm($t('message.deleteAlert'), $t('message.noticeTitle'), {
    confirmButtonText: $t('message.ok'),
    cancelButtonText: $t('message.cancel'),
    type: 'warning',
    beforeClose: (action, instance, done) => {
      if (action === 'confirm') {
        instance.confirmButtonLoading = true;
        api
          .post('/api/v1/sysAccount/remove', { id: row.id })
          .then((res) => {
            instance.confirmButtonLoading = false;
            if (res.errorCode === 0) {
              ElMessage.success(res.message);
              void reloadPage();
              done();
            }
          })
          .catch(() => {
            instance.confirmButtonLoading = false;
          });
      } else {
        done();
      }
    },
  }).catch(() => {});
}
function resetPassword(row: any) {
  ElMessageBox.confirm(
    $t('sysAccount.resetPasswordConfirm'),
    $t('message.noticeTitle'),
    {
      confirmButtonText: $t('message.ok'),
      cancelButtonText: $t('message.cancel'),
      type: 'warning',
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true;
          api
            .post('/api/v1/sysAccount/resetPassword', { id: row.id })
            .then((res) => {
              instance.confirmButtonLoading = false;
              if (res.errorCode === 0) {
                ElMessage.success($t('sysAccount.resetPasswordSuccess'));
                clearSelection();
                done();
              }
            })
            .catch(() => {
              instance.confirmButtonLoading = false;
            });
        } else {
          done();
        }
      },
    },
  ).catch(() => {});
}
function handleSelectionChange(rows: any[]) {
  selectedRows.value = rows;
}
function getSelectedIds() {
  return selectedRows.value
    .map((row) => row?.id)
    .filter((id) => id !== null && id !== undefined);
}
function getFirstBatchErrorReason(result: any) {
  return result?.errorItems?.[0]?.reason;
}
function notifyBatchActionResult(action: 'delete' | 'reset', result: any) {
  const successCount = result?.successCount || 0;
  const errorCount = result?.errorCount || 0;
  const firstReason = getFirstBatchErrorReason(result);
  if (errorCount === 0) {
    ElMessage.success(
      action === 'delete'
        ? $t('sysAccount.batchDeleteSuccess', { count: successCount })
        : $t('sysAccount.batchResetPasswordSuccess', { count: successCount }),
    );
    return;
  }
  if (successCount === 0) {
    ElMessage.error(
      firstReason ||
        (action === 'delete'
          ? $t('sysAccount.batchDeleteAllFailed')
          : $t('sysAccount.batchResetPasswordAllFailed')),
    );
    return;
  }
  ElMessage.warning(
    action === 'delete'
      ? $t('sysAccount.batchDeletePartialSuccess', {
          successCount,
          errorCount,
        })
      : $t('sysAccount.batchResetPasswordPartialSuccess', {
          successCount,
          errorCount,
        }),
  );
}
async function submitBatchAction(
  url: string,
  action: 'delete' | 'reset',
  confirmMessage: string,
) {
  const ids = getSelectedIds();
  if (ids.length === 0) {
    ElMessage.warning($t('sysAccount.batchActionSelectRequired'));
    return;
  }
  try {
    await ElMessageBox.confirm(confirmMessage, $t('message.noticeTitle'), {
      confirmButtonText: $t('message.ok'),
      cancelButtonText: $t('message.cancel'),
      type: 'warning',
    });
  } catch {
    return;
  }

  batchActionLoading.value = true;
  try {
    const res = await api.post(url, { ids });
    if (res.errorCode !== 0) {
      ElMessage.error(res.message || $t('sysAccount.batchActionFailed'));
      return;
    }
    notifyBatchActionResult(action, res.data || {});
    if (action === 'delete' && (res.data?.successCount || 0) > 0) {
      await reloadPage();
      return;
    }
    clearSelection();
  } catch (error: any) {
    ElMessage.error(error?.message || $t('sysAccount.batchActionFailed'));
  } finally {
    batchActionLoading.value = false;
  }
}
function batchDelete() {
  void submitBatchAction(
    '/api/v1/sysAccount/removeBatchWithResult',
    'delete',
    $t('sysAccount.batchDeleteConfirm', { count: selectedCount.value }),
  );
}
function batchResetPassword() {
  void submitBatchAction(
    '/api/v1/sysAccount/resetPasswordBatch',
    'reset',
    $t('sysAccount.batchResetPasswordConfirm', { count: selectedCount.value }),
  );
}
function isAdmin(data: any) {
  return data?.accountType === 1 || data?.accountType === 99;
}
</script>

<template>
  <div class="flex h-full flex-col gap-6 p-6">
    <SysAccountImportModal ref="importDialog" @reload="reset" />
    <SysAccountModal ref="saveDialog" @reload="reset" />
    <ListPageShell>
      <template #filters>
        <HeaderSearch
          :buttons="headerButtons"
          @search="handleSearch"
          @button-click="handleHeaderButtonClick"
        >
          <template #middle>
            <div v-if="selectedCount > 0" class="sys-account-batch-inline">
              <span class="sys-account-batch-inline__count">
                {{
                  $t('sysAccount.batchSelectedCount', { count: selectedCount })
                }}
              </span>
              <div class="sys-account-batch-inline__actions">
                <div v-access:code="'/api/v1/sysAccount/save'">
                  <ElButton
                    class="sys-account-batch-inline__button"
                    :icon="Lock"
                    :loading="batchActionLoading"
                    @click="batchResetPassword"
                  >
                    {{ $t('sysAccount.batchResetPassword') }}
                  </ElButton>
                </div>
                <div v-access:code="'/api/v1/sysAccount/remove'">
                  <ElButton
                    class="sys-account-batch-inline__button is-danger"
                    :icon="Delete"
                    :loading="batchActionLoading"
                    @click="batchDelete"
                  >
                    {{ $t('sysAccount.batchDelete') }}
                  </ElButton>
                </div>
              </div>
            </div>
          </template>
        </HeaderSearch>
      </template>
      <PageData
        ref="pageDataRef"
        page-url="/api/v1/sysAccount/page"
        :page-size="10"
      >
        <template #default="{ pageList }">
          <ElTable
            ref="tableRef"
            :data="pageList"
            border
            @selection-change="handleSelectionChange"
          >
            <ElTableColumn type="selection" width="48" />
            <ElTableColumn
              prop="avatar"
              align="center"
              :label="$t('sysAccount.avatar')"
            >
              <template #default="{ row }">
                <ElAvatar :src="row.avatar || defaultAvatar" />
              </template>
            </ElTableColumn>
            <ElTableColumn
              prop="loginName"
              align="center"
              :label="$t('sysAccount.loginName')"
            >
              <template #default="{ row }">
                {{ row.loginName }}
              </template>
            </ElTableColumn>
            <ElTableColumn
              prop="nickname"
              align="center"
              :label="$t('sysAccount.nickname')"
            >
              <template #default="{ row }">
                {{ row.nickname }}
              </template>
            </ElTableColumn>
            <ElTableColumn
              prop="mobile"
              align="center"
              width="120"
              :label="$t('sysAccount.mobile')"
            >
              <template #default="{ row }">
                {{ row.mobile }}
              </template>
            </ElTableColumn>
            <ElTableColumn
              prop="email"
              align="center"
              width="200"
              :label="$t('sysAccount.email')"
            >
              <template #default="{ row }">
                {{ row.email }}
              </template>
            </ElTableColumn>
            <ElTableColumn
              prop="status"
              align="center"
              :label="$t('sysAccount.status')"
            >
              <template #default="{ row }">
                {{ dictStore.getDictLabel('dataStatus', row.status) }}
              </template>
            </ElTableColumn>
            <ElTableColumn
              prop="created"
              width="160"
              :label="$t('sysAccount.created')"
            >
              <template #default="{ row }">
                {{ row.created }}
              </template>
            </ElTableColumn>
            <ElTableColumn prop="remark" :label="$t('sysAccount.remark')">
              <template #default="{ row }">
                {{ row.remark }}
              </template>
            </ElTableColumn>
            <ElTableColumn
              :label="$t('common.handle')"
              width="90"
              align="right"
            >
              <template #default="{ row }">
                <div class="flex items-center gap-3" v-if="!isAdmin(row)">
                  <ElButton link type="primary" @click="showDialog(row)">
                    {{ $t('button.edit') }}
                  </ElButton>

                  <ElDropdown>
                    <ElButton link :icon="MoreFilled" />

                    <template #dropdown>
                      <ElDropdownMenu>
                        <div v-access:code="'/api/v1/sysAccount/save'">
                          <ElDropdownItem @click="resetPassword(row)">
                            <ElButton type="primary" :icon="Lock" link>
                              {{ $t('sysAccount.resetPassword') }}
                            </ElButton>
                          </ElDropdownItem>
                        </div>
                        <div v-access:code="'/api/v1/sysAccount/remove'">
                          <ElDropdownItem @click="remove(row)">
                            <ElButton type="danger" :icon="Delete" link>
                              {{ $t('button.delete') }}
                            </ElButton>
                          </ElDropdownItem>
                        </div>
                      </ElDropdownMenu>
                    </template>
                  </ElDropdown>
                </div>
              </template>
            </ElTableColumn>
          </ElTable>
        </template>
      </PageData>
    </ListPageShell>
  </div>
</template>

<style scoped>
.sys-account-batch-inline {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
}

.sys-account-batch-inline__count {
  display: flex;
  align-items: center;
  min-height: 28px;
  font-size: 12px;
  font-weight: 600;
  color: hsl(var(--text-muted));
  white-space: nowrap;
}

.sys-account-batch-inline__actions {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.sys-account-batch-inline__actions :deep(.el-button) {
  height: 32px;
  min-height: 32px;
  padding-inline: 14px;
  border-radius: 10px;
  box-shadow: none;
}

:deep(.sys-account-batch-inline__button) {
  color: hsl(var(--primary));
}

:deep(.sys-account-batch-inline__button:not(.is-disabled):hover),
:deep(.sys-account-batch-inline__button:not(.is-disabled):focus-visible) {
  color: hsl(var(--primary));
  background: hsl(var(--primary) / 8%);
  border-color: hsl(var(--primary) / 16%);
}

:deep(.sys-account-batch-inline__button.is-danger) {
  color: hsl(var(--destructive));
}

:deep(.sys-account-batch-inline__button.is-danger:not(.is-disabled):hover),
:deep(
  .sys-account-batch-inline__button.is-danger:not(.is-disabled):focus-visible
) {
  color: hsl(var(--destructive));
  background: hsl(var(--destructive) / 8%);
  border-color: hsl(var(--destructive) / 16%);
}

@media (max-width: 640px) {
  .sys-account-batch-inline {
    width: 100%;
  }

  .sys-account-batch-inline__actions {
    gap: 6px;
  }
}
</style>
