import type {
  IAppointment,
  IAppointmentDetail,
  IApprovalDetail,
  IApprovalInstance,
  IApprovalRecord,
  IApprovalTemplate,
  IBanner,
  IBannerAdmin,
  INotice,
  INoticeAdmin,
  IEmployee,
  IGoodsTemplate,
  IInvitation,
  ILoginRes,
  IPageParams,
  IPageResult,
  IPermission,
  IRoleApplication,
  ISystemModule,
  ISystemRole,
  ITodayStats,
  IUserInfo,
  IUserAdmin,
  IDepartment,
  IVisitRecord,
  IVisitorVO,
  IEmployeeCertification,
  IDepartmentItem,
  IDepartmentTreeNode,
} from './types/appointment'
import { http } from '@/http/http'
import { getEnvBaseUrl } from '@/utils'

// ==================== Banner ====================

/** 获取首页轮播图 */
export function getBanners() {
  return http.get<IBanner[]>('/v1/banners')
}

/** 获取系统通知 */
export function getNotices() {
  return http.get<INotice[]>('/v1/notices')
}

// ==================== 认证 ====================

/** 微信登录 */
export function loginByCode(code: string) {
  return http.post<ILoginRes>('/v1/auth/login', { code })
}

/** 获取用户信息 */
export function getUserInfo() {
  return http.get<IUserInfo>('/v1/auth/userinfo')
}

/** 更新用户信息 */
export function updateUserInfo(data: Record<string, any>) {
  return http.put('/v1/auth/userinfo', data)
}

/** 绑定手机号 */
export function bindPhone(data: { code: string, encrypted_data: string, iv: string }) {
  return http.post('/v1/auth/phone', data)
}

// ==================== 访客预约 ====================

/** 搜索员工 */
export function searchEmployees(keyword: string) {
  return http.post<IEmployee[]>('/v1/appointment/employees/search', { keyword })
}

/** 验证员工姓名+手机号 */
export function verifyEmployee(name: string, phone: string) {
  return http.post<IEmployee>('/v1/appointment/employees/verify', { name, phone })
}

/** 获取当前用户历史访客列表 */
export function getMyVisitors() {
  return http.get<IVisitorVO[]>('/v1/appointment/visitors/my')
}

/** 保存为常用访客 */
export function saveVisitorTemplate(data: {
  name: string
  phone: string
  company?: string
  gender?: number
  id_type?: string
  id_number?: string
  license_plate?: string
}) {
  return http.post('/v1/appointment/visitor-templates', data)
}

/** 删除常用访客 */
export function deleteVisitorTemplate(id: number) {
  return http.delete(`/v1/appointment/visitor-templates/${id}`)
}

/** 获取物品模板列表 */
export function getGoodsTemplates() {
  return http.get<IGoodsTemplate[]>('/v1/appointment/goods-templates')
}

/** 创建物品模板 */
export function createGoodsTemplate(data: { name: string; quantity?: number; model?: string; remark?: string }) {
  return http.post<IGoodsTemplate>('/v1/appointment/goods-templates', data)
}

/** 更新物品模板 */
export function updateGoodsTemplate(id: number, data: Partial<IGoodsTemplate>) {
  return http.put(`/v1/appointment/goods-templates/${id}`, data)
}

/** 删除物品模板 */
export function deleteGoodsTemplate(id: number) {
  return http.delete(`/v1/appointment/goods-templates/${id}`)
}

// ==================== 车辆模板 ====================

/** 获取车辆模板列表 */
export function getVehicleTemplates() {
  return http.get<any[]>('/v1/appointment/vehicles')
}

/** 创建车辆模板 */
export function createVehicleTemplate(data: { license_plate: string; brand?: string; color?: string }) {
  return http.post<any>('/v1/appointment/vehicles', data)
}

/** 更新车辆模板 */
export function updateVehicleTemplate(id: number, data: { license_plate: string; brand?: string; color?: string }) {
  return http.put(`/v1/appointment/vehicles/${id}`, data)
}

/** 删除车辆模板 */
export function deleteVehicleTemplate(id: number) {
  return http.delete(`/v1/appointment/vehicles/${id}`)
}

/** 创建预约 */
export function createAppointment(data: Record<string, any>) {
  return http.post<IAppointment>('/v1/appointment/appointments', data)
}

/** 我的预约列表 */
export function getMyAppointments(params: IPageParams) {
  return http.get<IPageResult<IAppointment>>('/v1/appointment/appointments/my', params)
}

/** 全部预约列表（员工专属，按申请时间降序） */
export function getAllAppointments(params: IPageParams & { status?: number }) {
  return http.get<IPageResult<IAppointment>>('/v1/appointment/appointments/all', params)
}

/** 预约详情 */
export function getAppointmentDetail(id: number) {
  return http.get<IAppointmentDetail>('/v1/appointment/appointments/' + id)
}

/** 审核预约 */
export function auditAppointment(id: number, data: { status: number, comment?: string }) {
  return http.put(`/v1/appointment/appointments/${id}/audit`, data)
}

/** 获取预约的审批步骤 */
export function getApprovalSteps(id: number) {
  return http.get<any[]>(`/v1/appointment/appointments/${id}/steps`)
}

/** 取消预约 */
export function cancelAppointment(id: number) {
  return http.put(`/v1/appointment/appointments/${id}/cancel`)
}

// ==================== 邀请 ====================

/** 生成邀请 */
export function createInvitation(data: Record<string, any>) {
  return http.post<IInvitation>('/v1/appointment/invitations', data)
}

/** 公开邀请详情 */
export function getInvitationDetail(code: string) {
  return http.get<IInvitation>(`/v1/public/invitations/${code}`)
}

// ==================== 保安 ====================

/** 今日预约 */
export function getTodayAppointments() {
  return http.get<{ stats: ITodayStats, appointments: IAppointment[] }>('/v1/guard/today-appointments')
}

/** 登记进场 */
export function checkIn(data: { appointment_id: number, remark?: string }) {
  return http.post<IVisitRecord>('/v1/guard/check-in', data)
}

/** 登记出场 */
export function checkOut(data: { appointment_id: number, remark?: string }) {
  return http.post<IVisitRecord>('/v1/guard/check-out', data)
}

/** 获取预约的进出场记录 */
export function getVisitRecords(appointmentId: number) {
  return http.get<IVisitRecord[]>('/v1/guard/records', { appointment_id: appointmentId })
}

// ==================== 领导 ====================

/** 部门预约 */
export function getLeaderAppointments(params: IPageParams) {
  return http.get<IPageResult<IAppointment>>('/v1/leader/appointments', params)
}

// ==================== 管理 ====================

/** 角色列表 */
export function getRoles() {
  return http.get<ISystemRole[]>('/v1/admin/roles')
}

/** 创建角色 */
export function createRole(data: Partial<ISystemRole>) {
  return http.post<ISystemRole>('/v1/admin/roles', data)
}

/** 更新角色 */
export function updateRole(id: number, data: Partial<ISystemRole>) {
  return http.put(`/v1/admin/roles/${id}`, data)
}

/** 删除角色 */
export function deleteRole(id: number) {
  return http.delete(`/v1/admin/roles/${id}`)
}

/** 模块列表 */
export function getModules() {
  return http.get<ISystemModule[]>('/v1/admin/modules')
}

/** 创建模块 */
export function createModule(data: Partial<ISystemModule>) {
  return http.post<ISystemModule>('/v1/admin/modules', data)
}

/** 更新模块 */
export function updateModule(id: number, data: Partial<ISystemModule>) {
  return http.put(`/v1/admin/modules/${id}`, data)
}

/** 删除模块 */
export function deleteModule(id: number) {
  return http.delete(`/v1/admin/modules/${id}`)
}

/** 权限列表 */
export function getPermissions(params?: { roleCode?: string, moduleCode?: string }) {
  return http.get<IPermission[]>('/v1/admin/permissions', params)
}

/** 添加权限 */
export function createPermission(data: { roleCode: string, moduleCode: string, resource: string, action: string }) {
  return http.post<IPermission>('/v1/admin/permissions', data)
}

/** 删除权限 */
export function deletePermission(id: number) {
  return http.delete(`/v1/admin/permissions/${id}`)
}

/** 申请列表 */
export function getApplications() {
  return http.get<IRoleApplication[]>('/v1/admin/applications')
}

/** 审批申请 */
export function auditApplication(id: number, data: { status: number }) {
  return http.put(`/v1/admin/applications/${id}/audit`, data)
}

// ==================== 角色申请 ====================

/** 提交角色申请 */
export function submitRoleApply(data: { apply_role: number, reason: string }) {
  return http.post('/v1/role/apply', data)
}

/** 我的申请记录 */
export function getMyApplications() {
  return http.get<IRoleApplication[]>('/v1/role/applications')
}

// ==================== 上传（公开接口，无需权限） ====================

/** 上传图片到 MinIO */
export function uploadImageToMinio(filePath: string) {
  return new Promise<{ url: string }>((resolve, reject) => {
    uni.uploadFile({
      url: '/v1/upload/minio',
      filePath,
      name: 'file',
      success: (res) => {
        try {
          const data = JSON.parse(res.data)
          if (data.code === 200) {
            resolve(data.data)
          } else {
            reject(new Error(data.msg || '上传失败'))
          }
        } catch {
          reject(new Error('解析响应失败'))
        }
      },
      fail: (err) => {
        reject(err)
      },
    })
  })
}

/** 上传图片到微信服务器 */
export function uploadImage(filePath: string) {
  return new Promise<{ url: string }>((resolve, reject) => {
    uni.uploadFile({
      url: `${getEnvBaseUrl()}/v1/upload/image`,
      filePath,
      name: 'file',
      success: (res) => {
        try {
          const data = JSON.parse(res.data)
          if (data.code === 200) {
            resolve(data.data)
          } else {
            reject(new Error(data.msg || '上传失败'))
          }
        } catch {
          reject(new Error('解析响应失败'))
        }
      },
      fail: (err) => {
        reject(err)
      },
    })
  })
}

/** 通过图片链接上传到微信服务器 */
export function uploadImageByURL(url: string) {
  return http.post<{ url: string }>('/v1/upload/image-by-url', { url })
}

/** 更新用户头像（接受微信图片 URL） */
export function updateAvatar(userId: number, url: string) {
  return http.put(`/v1/user/${userId}/avatar`, { url })
}

// ==================== 审批流程 ====================

/** 发起审批 */
export function startApproval(data: {
  template_code: string
  business_type: string
  business_id: number
  variables?: Record<string, any>
}) {
  return http.post<IApprovalInstance>('/v1/approval/start', data)
}

/** 审批通过 */
export function approveRecord(data: {
  record_id: number
  comment?: string
  variables?: Record<string, any>
}) {
  return http.post<IApprovalRecord>('/v1/approval/approve', data)
}

/** 审批拒绝 */
export function rejectRecord(data: {
  record_id: number
  comment?: string
}) {
  return http.post<IApprovalRecord>('/v1/approval/reject', data)
}

/** 获取待审批列表 */
export function getPendingApprovals(params: {
  business_type?: string
  page?: number
  page_size?: number
}) {
  return http.get<IPageResult<IApprovalRecord>>('/v1/approval/pending', params)
}

/** 获取我的审批列表（按状态筛选） */
export function getMyApprovals(params: {
  status?: number
  page?: number
  page_size?: number
}) {
  return http.get<IPageResult<IApprovalRecord>>('/v1/approval/my', params)
}

/** 获取审批实例详情 */
export function getApprovalDetail(instanceId: number) {
  return http.get<IApprovalDetail>(`/v1/approval/instance/${instanceId}`)
}

/** 获取审批模板列表 */
export function getApprovalTemplates() {
  return http.get<IApprovalTemplate[]>('/v1/approval/templates')
}

// ==================== 员工认证 ====================

/** 提交员工认证申请 */
export function submitCertification(data: {
  real_name: string
  phone: string
  role_type: string
  snapshot: string[]
  position?: string
  department_id?: number | null
}) {
  return http.post<IEmployeeCertification>('/v1/certification/submit', data)
}

/** 获取我的认证申请 */
export function getMyCertification() {
  return http.get<IEmployeeCertification | null>('/v1/certification/my')
}

/** 撤回认证申请 */
export function withdrawCertification(id: number) {
  return http.put(`/v1/certification/${id}/withdraw`)
}

// ==================== 管理员：员工认证审核 ====================

/** 认证申请列表 */
export function adminGetCertifications(params?: IPageParams & { status?: number }) {
  return http.get<IPageResult<IEmployeeCertification>>('/v1/admin/certifications', params)
}

/** 审核认证申请 */
export function adminAuditCertification(id: number, data: {
  status: number
  department_id?: number
  comment?: string
}) {
  return http.put(`/v1/admin/certifications/${id}/audit`, data)
}

// ==================== 管理员：部门管理 ====================

/** 获取部门树 */
export function adminGetDepartmentTree() {
  return http.get<IDepartmentTreeNode[]>('/v1/admin/department-tree')
}

/** 获取所有部门（扁平列表） */
export function adminGetAllDepartments() {
  return http.get<IDepartmentItem[]>('/v1/admin/departments-all')
}

/** 创建部门 */
export function adminCreateDepartment(data: {
  name: string
  parent_id?: number
  leader_name?: string
  leader_phone?: string
  sort?: number
}) {
  return http.post('/v1/admin/departments', data)
}

/** 更新部门 */
export function adminUpdateDepartment(id: number, data: Record<string, any>) {
  return http.put(`/v1/admin/departments/${id}`, data)
}

/** 删除部门 */
export function adminDeleteDepartment(id: number) {
  return http.delete(`/v1/admin/departments/${id}`)
}

// ==================== 审批配置 ====================

interface IApprovalConfig {
  id: number
  step: number
  approver_id: number
  approver?: { id: number; name: string; phone: string }
  description: string
  created_at: string
}

interface IEmployeeSimple {
  id: number
  name: string
  phone: string
  department_name: string
  position: string
}

/** 获取审批配置列表 */
export function adminGetApprovalConfigs() {
  return http.get<IApprovalConfig[]>('/v1/admin/approval-config')
}

/** 创建审批配置 */
export function adminCreateApprovalConfig(data: {
  step: number
  approver_id: number
  description?: string
}) {
  return http.post('/v1/admin/approval-config', data)
}

/** 更新审批配置 */
export function adminUpdateApprovalConfig(id: number, data: {
  step?: number
  approver_id?: number
  description?: string
}) {
  return http.put(`/v1/admin/approval-config/${id}`, data)
}

/** 删除审批配置 */
export function adminDeleteApprovalConfig(id: number) {
  return http.delete(`/v1/admin/approval-config/${id}`)
}

/** 获取所有员工（用于选择审批人） */
export function adminGetAllEmployees() {
  return http.get<{list: IEmployeeSimple[]}>('/v1/admin/employees', { page: 1, page_size: 1000 })
}

/** 获取知会通知配置列表 */
export function adminGetApprovalNotifies() {
  return http.get<IApprovalNotifyInfo[]>('/v1/admin/approval-notify')
}

/** 创建知会通知配置 */
export function adminCreateApprovalNotify(data: { employee_id: number }) {
  return http.post('/v1/admin/approval-notify', data)
}

/** 删除知会通知配置 */
export function adminDeleteApprovalNotify(id: number) {
  return http.delete(`/v1/admin/approval-notify/${id}`)
}

/** 为用户添加角色 */
export function adminAddUserRole(userId: number, roleId: number) {
  return http.post(`/v1/admin/users/${userId}/roles`, { role_id: roleId })
}

/** 为用户移除角色 */
export function adminRemoveUserRole(userId: number, roleId: number) {
  return http.delete(`/v1/admin/users/${userId}/roles/${roleId}`)
}

export interface IApprovalNotifyInfo {
  id: number
  employee_id: number
  employee?: { id: number; name: string; phone: string; department_name?: string }
}

// ==================== 公共数据 ====================

/** 获取所有启用的来访目的 */
export function getVisitTypes() {
  return http.get<any[]>('/v1/public/visit-types')
}

/** 获取所有启用的到访区域 */
export function getVisitorAreas() {
  return http.get<any[]>('/v1/public/visitor-areas')
}
