<template>
  <div class="page-container">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span style="font-weight: bold;">账号管理</span>
          <div class="header-actions" style="display: flex; gap: 10px;">
            <el-input v-model="queryParams.userName" placeholder="搜索用户名" style="width: 150px" clearable @keyup.enter="getList" />
            <el-input v-model="queryParams.phonenumber" placeholder="搜索手机号" style="width: 150px" clearable @keyup.enter="getList" />
            <el-button type="primary" icon="Search" @click="getList">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            <el-button type="warning" icon="Plus" @click="handleAdd" v-hasPermi="['system:user:add']" style="background-color: #e6a23c; border-color: #e6a23c; color: #fff;">新增账号</el-button>
          </div>
        </div>
      </template>

      <el-table :data="tableData" style="width: 100%" v-loading="loading" :header-cell-style="{ color: '#909399', fontWeight: 'normal', backgroundColor: '#fff', borderBottom: '1px solid #ebeef5' }">
        <el-table-column prop="avatar" label="头像" width="80" align="center">
          <template #default="scope">
            <el-avatar :size="40" :src="scope.row.avatarUrl || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" />
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="用户名" width="120" />
        <el-table-column prop="nickName" label="姓名" width="120" />
        <el-table-column prop="phonenumber" label="手机号" width="150" />
        <el-table-column prop="roles" label="角色" min-width="150">
          <template #default="scope">
            <template v-if="scope.row.roles && scope.row.roles.length > 0">
              <el-tag v-for="role in scope.row.roles" :key="role.roleId" style="margin-right: 5px; margin-bottom: 5px;" size="small">
                {{ roleOptions.find(item => item.id === role.roleId)?.name || role.roleName }}
              </el-tag>
            </template>
            <template v-else-if="scope.row.roleIds && scope.row.roleIds.length > 0">
              <el-tag v-for="roleId in scope.row.roleIds" :key="roleId" style="margin-right: 5px; margin-bottom: 5px;" size="small">
                {{ roleOptions.find(item => item.id == roleId)?.name || '未知角色' }}
              </el-tag>
            </template>
            <span v-else style="color: #909399;">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="storeIds" label="管理门店" min-width="200">
          <template #default="scope">
            <span v-if="scope.row.storeIds && scope.row.storeIds.length > 0">
              {{ scope.row.storeIds.map(id => storeOptions.find(item => item.id === id)?.name || '未知门店(' + id + ')').join('，') }}
            </span>
            <span v-else style="color: #909399;">全部门店</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)" style="--el-switch-on-color: #f3d19e; --el-switch-off-color: #dcdfe6" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <div style="display: flex; gap: 15px;" v-if="scope.row.userId !== 1">
              <el-button link style="color: #e6a23c; padding: 0;" @click="handleEdit(scope.row)" v-hasPermi="['system:user:edit']">编辑</el-button>
              <el-button link style="color: #67c23a; padding: 0;" @click="handleResetPwd(scope.row)" v-hasPermi="['system:user:resetPwd']">重置密码</el-button>
              <el-button link style="color: #f56c6c; padding: 0;" @click="handleDelete(scope.row)" v-hasPermi="['system:user:remove']">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-if="total > 0"
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 账号表单 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑账号' : '新增账号'" width="550px" append-to-body>
      <el-form ref="userFormRef" :model="form" :rules="rules" label-width="90px">
        <el-row>
          <el-col :span="24">
            <div style="display: flex; justify-content: center; align-items: center; margin-bottom: 20px;">
              <image-upload v-model="form.avatar" :limit="1" :is-show-tip="false" class="circular-upload" />
              <span style="color: #999; font-size: 13px; margin-left: 10px;">点击上传头像</span>
            </div>
          </el-col>
          <el-col :span="24" v-if="!isEdit">
            <el-form-item label="用户名" prop="userName">
              <el-input v-model="form.userName" placeholder="用于登录" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="姓名" prop="nickName">
              <el-input v-model="form.nickName" placeholder="人员姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="手机号" prop="phonenumber">
              <el-input v-model="form.phonenumber" placeholder="联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="!isEdit">
            <el-form-item label="登录密码" prop="password">
              <el-input v-model="form.password" type="password" show-password placeholder="密码" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="分配角色" prop="roleIds">
              <el-select v-model="form.roleIds" multiple placeholder="请选择角色" style="width: 100%">
                <el-option
                  v-for="item in roleOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="管理门店">
              <permi-select v-model="form.storeIds" :options="storeOptions" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio value="0">启用</el-radio>
                <el-radio value="1">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveAccount" :loading="buttonLoading">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="Account">
import { ref, reactive, computed, onMounted, nextTick, getCurrentInstance, ComponentInternalInstance } from 'vue';
import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus';
import userApi from '@/api/system/user';
import { listOnUser } from '@/api/system/store';
import { listAllRole } from '@/api/system/role';
import { useUserStore } from '@/store/modules/user';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

// State
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  userName: '',
  phonenumber: ''
});
const total = ref(0);
const tableData = ref([]);
const loading = ref(false);
const buttonLoading = ref(false);

const dialogVisible = ref(false);
const isEdit = ref(false);

const userFormRef = ref<FormInstance>();
const form = ref<any>({
  userId: undefined,
  userName: '',
  nickName: '',
  phonenumber: '',
  password: '',
  roleIds: [],
  storeIds: [],
  postIds: [],
  status: '0',
  avatar: ''
});

const rules = reactive<FormRules>({
  userName: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
  nickName: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
  password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
  roleIds: [{ type: 'array', required: true, message: '请至少选择一个角色', trigger: 'change' }]
});

const storeOptions = ref<any[]>([]);
const roleOptions = ref<any[]>([]);
const initPassword = ref('123456');

// Fetch data
const getList = async () => {
  loading.value = true;
  try {
    const res = await userApi.listUser(queryParams);
    tableData.value = res.rows as any;
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};

const resetQuery = () => {
  queryParams.userName = '';
  queryParams.phonenumber = '';
  queryParams.pageNum = 1;
  getList();
};

const getStoreData = async () => {
  const res = await listOnUser();
  storeOptions.value = res.data;
};

const getRoleData = async () => {
  const res = await listAllRole();
  roleOptions.value = res.data;
};

const handleSizeChange = (val: number) => {
  queryParams.pageSize = val;
  getList();
};
const handleCurrentChange = (val: number) => {
  queryParams.pageNum = val;
  getList();
};

const resetForm = () => {
  form.value = {
    userId: undefined,
    userName: '',
    nickName: '',
    phonenumber: '',
    password: '',
    roleIds: [],
    storeIds: [],
    postIds: [],
    status: '0',
    avatar: ''
  };
  userFormRef.value?.resetFields();
  userFormRef.value?.clearValidate();
};

const handleAdd = async () => {
  resetForm();
  isEdit.value = false;
  await userApi.getUser();
  form.value.password = initPassword.value;
  dialogVisible.value = true;
};

const handleEdit = async (row: any) => {
  resetForm();
  isEdit.value = true;
  const { data } = await userApi.getUser(row.userId);
  Object.assign(form.value, data.user);

  form.value.roleIds = data.roleIds || [];
  form.value.storeIds = data.storeIds || (data.user && data.user.storeIds) || [];
  form.value.password = '';
  
  // 处理头像回显
  if (data.user.avatar && data.user.avatarUrl) {
    form.value.avatar = [{ ossId: data.user.avatar, url: data.user.avatarUrl }];
  } else if (data.user.avatar) {
    form.value.avatar = data.user.avatar;
  } else {
    form.value.avatar = '';
  }
  
  dialogVisible.value = true;
};

const handleStatusChange = async (row: any) => {
  const text = row.status === '0' ? '启用' : '废弃';
  try {
    await ElMessageBox.confirm(`确认要${text} ${row.userName} 的账号吗?`, '提示', { type: 'warning' });
    await userApi.changeUserStatus(row.userId, row.status);
    ElMessage.success(`${text}成功`);
  } catch {
    row.status = row.status === '0' ? '1' : '0';
  }
};

const handleResetPwd = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确认重置 ${row.userName} 的密码为 ${initPassword.value} 吗？`, '提示', { type: 'warning' });
    await userApi.resetUserPwd(row.userId, initPassword.value);
    ElMessage.success('重置成功');
  } catch {}
};

const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('是否确认删除该账号？', '提示', { type: 'warning' });
    await userApi.delUser(row.userId);
    ElMessage.success('删除成功');
    getList();
  } catch {}
};

const saveAccount = () => {
  userFormRef.value?.validate(async (valid) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        const formData = { ...form.value };
        if (Array.isArray(formData.avatar)) {
          formData.avatar = formData.avatar.map((item: any) => item.ossId).join(',');
        }
        if (formData.userId) {
          await userApi.updateUser(formData);
        } else {
          await userApi.addUser(formData);
        }
        ElMessage.success('保存成功');
        dialogVisible.value = false;
        getList();
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

onMounted(() => {
  getList();
  getStoreData();
  getRoleData();
  proxy?.getConfigKey('sys.user.initPassword').then((res: any) => {
    if (res && res.data) {
      initPassword.value = res.data;
    }
  });
});
</script>

<style scoped>
.page-container {
  padding: 8px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
:deep(.circular-upload .el-upload--picture-card),
:deep(.circular-upload .el-upload-list--picture-card .el-upload-list__item) {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}
:deep(.circular-upload .el-upload-list__item-actions) {
  border-radius: 50%;
}
</style>
