<template>
  <div class="page-container">
    <a-row :gutter="20">
      <a-col :span="24">
        <a-card class="box-card" :bordered="false">
            <div class="toolbar">
              <a-button type="primary" @click="handleAddUser" v-hasPermi="['system:user:add']">新增用户</a-button>
              <a-input
                v-model="searchUser"
                placeholder="搜索用户..."
                style="width: 200px; margin-left: 10px"
                allow-clear
              >
                <template #prefix>
                  <icon-search />
                </template>
              </a-input>
            </div>
            
            <a-table :data="filteredUsers" style="margin-top: 15px" :pagination="{ pageSize: 10 }">
              <template #columns>
                <a-table-column title="用户名" data-index="Username" :width="150" />
                <a-table-column title="姓名" data-index="Name" :width="150" />
                <a-table-column title="手机号" data-index="PhoneNumber" :width="150" />
                <a-table-column title="邮箱" data-index="Email" />
                <a-table-column title="状态" data-index="Status" :width="100">
                  <template #cell="{ record }">
                    <a-tag :color="record.Status === '0' ? 'green' : 'red'">
                      {{ record.Status === '0' ? '正常' : '禁用' }}
                    </a-tag>
                  </template>
                </a-table-column>
                <a-table-column title="操作" :width="180">
                  <template #cell="{ record }">
                    <a-space>
                      <a-button size="small" @click="handleEditUser(record)" v-hasPermi="['system:user:edit']" :disabled="record.Username === 'admin' && userStore.user.Username !== 'admin'">编辑</a-button>
                      <a-button size="small" status="danger" @click="handleDeleteUser(record)" v-hasPermi="['system:user:remove']" v-if="record.Username !== 'admin'">删除</a-button>
                    </a-space>
                  </template>
                </a-table-column>
              </template>
            </a-table>
        </a-card>
      </a-col>
    </a-row>

    <!-- Dialog: User -->
    <a-modal v-model:visible="userDialog.visible" :title="userDialog.isEdit ? '编辑用户' : '新增用户'" @ok="submitUser" @cancel="userDialog.visible = false">
      <a-form :model="userForm" layout="vertical">
        <a-form-item field="Name" label="姓名">
          <a-input 
            v-model="userForm.Name" 
            :name="userDialog.fieldNames.name"
            placeholder="必填"
            allow-clear
          />
        </a-form-item>
        <a-form-item field="PhoneNumber" label="手机号">
          <a-input 
            v-model="userForm.PhoneNumber" 
            :name="userDialog.fieldNames.phoneNumber"
            placeholder="必填"
            allow-clear
          />
        </a-form-item>
        <a-form-item field="Email" label="邮箱">
          <a-input 
            v-model="userForm.Email" 
            :name="userDialog.fieldNames.email"
            allow-clear
          />
        </a-form-item>
        
        <a-form-item field="Username" label="用户名" v-if="userDialog.isEdit">
          <a-input 
            v-model="userForm.Username" 
            disabled 
            :name="userDialog.fieldNames.username"
          />
        </a-form-item>
        
        <a-form-item field="RoleIds" label="角色">
           <a-select v-model="userForm.RoleIds" multiple placeholder="选择角色" allow-clear>
             <a-option v-for="role in roles" :key="role.ID" :label="role.Name" :value="role.ID" />
           </a-select>
        </a-form-item>
         <a-form-item field="Status" label="状态">
          <a-radio-group v-model="userForm.Status">
            <a-radio value="0">正常</a-radio>
            <a-radio value="1">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick } from 'vue';
import { IconSearch } from '@arco-design/web-vue/es/icon';
import { Message, Modal } from '@arco-design/web-vue';
import * as sysApi from '../../api/system';
import { useUserStore } from '../../stores/user';

const userStore = useUserStore();

const searchUser = ref('');

// --- Data Models ---
const users = ref<any[]>([]);
const roles = ref<any[]>([]);

// --- Lifecycle ---
onMounted(() => {
  loadRoles();
  loadUsers();
});

const loadRoles = async () => {
  // getRoles now might return object with rows, or array. Handle both.
  const res: any = await sysApi.getRoles();
  if (res.rows) {
      roles.value = res.rows;
  } else if (Array.isArray(res)) {
      roles.value = res;
  } else {
      roles.value = [];
  }
};

const loadUsers = async () => {
  users.value = await sysApi.getUsers() as any;
};

// --- Computed ---
const filteredUsers = computed(() => {
  if (!searchUser.value) return users.value;
  return users.value.filter((u: any) => u.Username.includes(searchUser.value) || u.Name.includes(searchUser.value));
});

// --- User Logic ---
const userDialog = reactive({ 
  visible: false, 
  isEdit: false,
  fieldNames: { // Dynamic field names
    username: 'u_' + Math.random().toString(36).slice(2),
    password: 'p_' + Math.random().toString(36).slice(2),
    name: 'n_' + Math.random().toString(36).slice(2),
    email: 'e_' + Math.random().toString(36).slice(2),
    phoneNumber: 'ph_' + Math.random().toString(36).slice(2),
  }
});
const userForm = reactive<any>({ Username: '', Name: '', Password: '', RoleIds: [], Status: '0', Email: '', PhoneNumber: '' });

const refreshFieldNames = () => {
  userDialog.fieldNames = {
    username: 'u_' + Math.random().toString(36).slice(2),
    password: 'p_' + Math.random().toString(36).slice(2),
    name: 'n_' + Math.random().toString(36).slice(2),
    email: 'e_' + Math.random().toString(36).slice(2),
    phoneNumber: 'ph_' + Math.random().toString(36).slice(2),
  };
};

const handleAddUser = () => {
  userDialog.isEdit = false;
  refreshFieldNames();
  Object.assign(userForm, { Username: '', Name: '', Password: '', RoleIds: [], Status: '0', Email: '', PhoneNumber: '' });
  userDialog.visible = true;
};
const handleEditUser = (row: any) => {
  if (row.Username === 'admin' && userStore.user.Username !== 'admin') {
    Message.warning('系统管理员不可修改');
    return;
  }
  userDialog.isEdit = true;
  refreshFieldNames();
  Object.assign(userForm, row);
  userForm.Password = '';  
  userDialog.visible = true;
};
const handleDeleteUser = (row: any) => {
  if (row.Username === 'admin') {
    Message.warning('系统管理员不可删除');
    return;
  }
  Modal.confirm({
    title: '提示',
    content: '确定删除该用户吗?',
    onOk: async () => {
      await sysApi.deleteUser(row.ID);
      Message.success('删除成功');
      loadUsers();
    }
  });
};
const submitUser = async () => {
  if (userDialog.isEdit) {
    await sysApi.updateUser(userForm.ID, userForm);
    Message.success('更新成功');
  } else {
    // Validate required fields
    if (!userForm.Name || !userForm.PhoneNumber) {
        Message.warning('姓名和手机号必填');
        nextTick(() => userDialog.visible = true);
        return;
    }
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(userForm.PhoneNumber)) {
        Message.warning('请输入正确的手机号码格式');
        nextTick(() => userDialog.visible = true);
        return;
    }

    const res: any = await sysApi.createUser(userForm);
    Modal.info({
        title: '账号信息',
        content: `用户创建成功！用户名: ${res.user.Username}, 密码: ${res.generated_password}`,
        okText: '复制并关闭'
    });
  }
  userDialog.visible = false;
  loadUsers();
};

</script>

<style scoped>
.page-container {
  padding: 20px;
}
.box-card {
  height: 100%;
  min-height: 600px;
}
.toolbar {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}
</style>
