<template>
  <my-layout>
    <layout-item class="bg-white">
      <div class="py-5px flex" @keyup.enter="search()">
        <expand-filter-box v-model:can-expand="canExpand" :enable-expand="true" class="flex-grow" :expand="expand">
          <input-filter v-model="queryForm.name" label="姓名" placeholder="请输入姓名" :width="240" class="mr-3" />
          <input-filter v-model="queryForm.mobile" label="登录账号" placeholder="请输入登录账号" :width="240" class="mr-3" />
          <radio-filter v-model="queryForm.status" label="账号状态" :list="statusOptions" :width="160" class="mr-3" />
          <radio-filter v-model="queryForm.role" label="角色" :list="roles" :width="160" class="mr-3" />
       
        </expand-filter-box>
        <div class="flex-shrink-0 flex items-center h-40px pr-15px">
          <el-button v-if="canExpand" text plain @click="expand = !expand">
            <span class="mr-5px">{{ expand ? "收起筛选" : "更多筛选" }}</span>
            <el-icon v-if="expand">
              <ArrowUpBold />
            </el-icon>
            <el-icon v-else>
              <ArrowDownBold />
            </el-icon>
          </el-button>
          <el-button type="primary" class="mr-2" @click="search">查询</el-button>
          <el-button class="mr-2" @click="clear">清空筛选</el-button>
          <el-button type="primary" class="ml-auto" @click="editAccount()">新增</el-button>
        </div>

      </div>
      <div class="flex items-center mt-2 mb-2 px-15px border-t border-gray-200 pt-10px">
        <span class="mr-3">已选账号：<span class="text-red-500">{{ selections.length }}</span></span>
        <el-button type="primary" class="mr-2" @click="setState(false)">禁用</el-button>
        <el-button type="primary" @click="setState(true)">启用</el-button>
      </div>
    </layout-item>
    <layout-main :scroll="false">
      <el-table v-loading="loading" border ref="tableRef" height="100%" :data="list"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="40" />
        <el-common-column prop="anotherName" label="账号名称" :width="200" />
        <el-common-column prop="mobile" label="登录账号" :min-width="200" />
        <el-common-column prop="roleNames" label="角色权限" :min-width="200" />
        <el-common-column prop="status" label="账号状态" :min-width="200">
          <template #default="{ row: { accountState } }">
            <span :class="accountState === 'enable' ? '' : 'text-red-500'">
              {{ accountState === 'enable' ? '已启用' : '已禁用' }}
            </span>
          </template>
        </el-common-column>
        <el-common-column prop="loginTime" label="最近登录时间" :min-width="200" />
        <el-common-column prop="loginIp" label="最近登录IP" :min-width="200" />
        <el-table-column label="操作" fixed="right" :width="220">
          <template #default="{ row }">
            <el-text type="primary" class="cursor-pointer" @click="editAccount(row)">修改</el-text>
            <el-text type="primary" class="cursor-pointer ml-5px" @click="reset(row)">重置密码</el-text>
            <el-text type="primary" class="cursor-pointer ml-5px" @click="viewLog(row)">登录日志</el-text>
          </template>
        </el-table-column>
      </el-table>
    </layout-main>
    <layout-item>
      <pagination :totalRow="total" :pageSize="pageSize" :currentPage="page" @handle-size-change="changeSize"
        @handle-current-change="changePage" />
    </layout-item>
  </my-layout>
  <log-modal :user="user" :width="width" :visible="visible" @close="close" />
  <account-modal :data="user" :width="modalWidth" :visible="accountVisible" @close="closeModal" @change="getList" />
</template>
<script setup>
import { ref, onMounted } from "vue";
import dayjs from "dayjs";
import { ElMessage, ElMessageBox } from "element-plus";
import { getLoginLog, resetPassword, getAccountList, setAccountState } from '@/api/account';
import { getRolesList } from '@/api/corp';

import useElPagination from "@/hooks/useElPagination";
import useModal from "@/hooks/useModal";

import MyLayout, { LayoutMain, LayoutItem } from "@/components/layout";
import { InputFilter, expandFilterBox, RadioFilter, CheckBoxFilter, DateRangeFilter, CustomFilter } from "@/components/filter-bar";
import pagination from "@/components/pagination/pagination.vue";
import elCommonColumn from "@/components/el-common-column/el-common-column.vue";
import logModal from "./log-modal.vue";
import accountModal from "./account-modal.vue";

const queryForm = ref({
  name: "",
  status: "",
  mobile: '',
  role: ''
});
const roles = ref([]);
const statusOptions = [
  { label: "已启用", value: true },
  { label: "已禁用", value: false }
];
const { list, more, page, pageSize, changePage, changeSize, loadMore, total } = useElPagination(getList)
const loading = ref(false);
const selections = ref([]);
const canExpand = ref(true);
const expand = ref(false);
const params = {};
const user = ref({})
const tableRef = ref();
const { close, show, visible, width } = useModal(1200);
const { close: closeModal, show: showModal, visible: accountVisible, width: modalWidth } = useModal(800);

function editAccount(row = {}) {
  user.value = row;
  showModal();
}

function search() {
  // 查询逻辑
  params.name = queryForm.value.name.trim();
  params.mobile = queryForm.value.mobile.trim();
  params.accountState = queryForm.value.status;
  params.roleId = queryForm.value.role;
  changePage(1)
}
function clear() {
  queryForm.value = { name: "", status: "", mobile: '', role: '' };
  search();
}
async function getList() {
  loading.value = true;
  tableRef.value && tableRef.value.clearSelection();

  const { data, success, message } = await getAccountList({
    page: page.value,
    pageSize: pageSize.value,
    ...params
  });
  list.value = data && Array.isArray(data.list) ? data.list.map(i => ({
    ...i,
    loginTime: i.lastLogin && i.lastLogin[0] && i.lastLogin[0].createTime && dayjs(i.lastLogin[0].createTime).isValid() ? dayjs(i.lastLogin[0].createTime).format('YYYY-MM-DD HH:mm:ss') : '--',
    loginIp: i.lastLogin && i.lastLogin[0] && i.lastLogin[0].ip ? i.lastLogin[0].ip : '--',
    roleNames: Array.isArray(i.roles) ? i.roles.map(i => i.roleName).join(',') : '',
  })) : [];
  total.value = data.total > 0 ? data.total : 0;
  loading.value = false;
  if (!success) {
    ElMessage.error(message);
  }
}

async function reset(row) {
  await ElMessageBox.confirm("是否重置密码？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  });
  loading.value = true;
  const { success, data, message } = await resetPassword({ userId: row.userid, accountId: row._id });
  loading.value = false
  if (success) {
    ElMessageBox.alert(
      `
      <div class="text-center">密码重置成功</div>
      ${data && data.password ? `<div class="text-center">初始密码：<span class="text-blue-500">${data.password}</span></div>` : ''}
      `,
      '提示',
      {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '知道了',
        center: true
      }
    );
  } else {
    ElMessage.error(message);
  }
}

async function setState(state) {
  if (selections.value.length === 0) {
    ElMessage.info('请选择账号');
    return;
  }
  await ElMessageBox.confirm(`确定${state ? '启用' : '禁用'}选中的账号吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  });
  const res = await setAccountState({ accountIds: selections.value, state });
  if (res.success) {
    ElMessage.success('操作成功');
    getList();
  } else {
    ElMessage.error(res.message);
  }
}

function viewLog(row) {
  user.value = row;
  show();
}

function handleSelectionChange(val) {
  selections.value = val.map((i) => i._id);
}

async function getRoles() {
  const res = await getRolesList({ showOptions: true });
  roles.value = res.data && Array.isArray(res.data.data) ? res.data.data.map(i => ({ value: i._id, label: i.roleName })) : [];
}


onMounted(() => {
  getList()
  getRoles()
})
</script>
