import { useCallback, useEffect, useMemo, useState } from "react"
import {
  EyeOutlined,
  FileSearchOutlined,
  ReloadOutlined,
  SearchOutlined,
  SyncOutlined,
} from "@ant-design/icons"
import {
  Button,
  Card,
  Col,
  Descriptions,
  Empty,
  Input,
  InputNumber,
  Modal,
  Row,
  Select,
  Space,
  Statistic,
  Table,
  Tag,
  Timeline,
  Typography,
  type TableColumnsType,
} from "antd"
import { toast } from "../../utils/toast"
import type { UpstreamActionLog } from "../../api/upstreamActions"
import {
  getAdminServiceOrder,
  listAdminServiceOrders,
  unsubscribeAdminServiceOrder,
  type AdminServiceOrder,
} from "../api/service_orders"
import {
  ignoreAdminUpstreamAction,
  markAdminUpstreamActionHandled,
  retryAdminUpstreamAction,
  syncAdminUpstreamAction,
} from "../api/upstream_actions"

const { Title, Paragraph, Text } = Typography

const ORDER_STATUS_META: Record<string, { label: string; color: string }> = {
  pending: { label: "待处理", color: "warning" },
  paid: { label: "已支付", color: "green" },
  cancelled: { label: "已退订", color: "default" },
  refunded: { label: "已退款", color: "purple" },
}

const REFUND_TYPE_META: Record<string, { label: string; color: string }> = {
  full: { label: "全额退款", color: "green" },
  prorated: { label: "按量退款", color: "blue" },
  no_refund: { label: "不退款", color: "red" },
  unavailable: { label: "不可退订", color: "default" },
}

const RESOURCE_STATUS_META: Record<string, { label: string; color: string }> = {
  none: { label: "无资源动作", color: "default" },
  running: { label: "处理中", color: "processing" },
  failed: { label: "处理失败", color: "red" },
  finished: { label: "已完成", color: "green" },
  manual_handled: { label: "人工已处理", color: "purple" },
  ignored: { label: "已忽略", color: "default" },
}

const INSTANCE_STATUS_META: Record<string, { label: string; color: string }> = {
  provisioning: { label: "开通中", color: "processing" },
  active: { label: "运行中", color: "green" },
  suspended: { label: "已暂停", color: "orange" },
  terminated: { label: "已销毁", color: "default" },
  failed: { label: "失败", color: "red" },
  provision_failed: { label: "开通失败", color: "red" },
}

const ACTION_STATUS_META: Record<string, { label: string; color: string }> = {
  submitted: { label: "已提交", color: "processing" },
  running: { label: "执行中", color: "blue" },
  success: { label: "成功", color: "green" },
  failed: { label: "失败", color: "red" },
  no_task: { label: "无任务", color: "green" },
  manual_handled: { label: "人工已处理", color: "purple" },
  ignored: { label: "已忽略", color: "default" },
  superseded: { label: "已被重试替代", color: "default" },
}

const ACTION_LABEL: Record<string, string> = {
  instance_delete: "删除实例",
  instance_suspend: "暂停实例",
  instance_unsuspend: "解除暂停",
  disk_delete: "删除云盘",
  disk_resize_rollback: "回滚磁盘扩容",
  package_instance_rollback: "回滚套餐",
  package_bandwidth_rollback: "回滚带宽",
}

function yuan(cents: number | null | undefined) {
  return `¥${((cents ?? 0) / 100).toFixed(2)}`
}

function fmtDate(value: string | null | undefined) {
  if (!value) return "-"
  return new Date(value).toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    hour12: false,
  })
}

function tag(meta: Record<string, { label: string; color: string }>, value: string | null | undefined) {
  const item = meta[value || ""] ?? { label: value || "未知", color: "default" }
  return <Tag color={item.color}>{item.label}</Tag>
}

function timelineColor(status?: string | null) {
  if (!status) return "gray"
  if (["success", "finished", "active", "paid", "refunded", "terminated", "manual_handled"].includes(status)) return "green"
  if (["failed", "provision_failed"].includes(status)) return "red"
  if (["running", "submitted", "provisioning"].includes(status)) return "blue"
  return "gray"
}

function userLabel(order: AdminServiceOrder) {
  return order.user?.nickname || order.user?.username || order.user?.email || `用户 #${order.user?.id ?? "-"}`
}

function formatInstanceSpec(instance: AdminServiceOrder["instances"][number]) {
  const parts: string[] = []
  if (instance.cpu) parts.push(`${instance.cpu} 核`)
  if (instance.memory) parts.push(`${instance.memory} MB`)
  if (instance.system_disk_size) parts.push(`系统盘 ${instance.system_disk_size}G`)
  if (instance.data_disk_size) parts.push(`数据盘 ${instance.data_disk_size}G`)
  if (instance.in_bw || instance.out_bw) parts.push(`带宽 ${instance.in_bw || instance.out_bw}Mbps`)
  if (instance.ip_num) parts.push(`IP ${instance.ip_num}`)
  if (instance.os_image) parts.push(instance.os_image)
  return parts.join(" / ") || "-"
}

function errorMessage(error: unknown, fallback: string) {
  return (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail || fallback
}

export default function AdminServiceOrders() {
  const [orders, setOrders] = useState<AdminServiceOrder[]>([])
  const [loading, setLoading] = useState(false)
  const [keyword, setKeyword] = useState("")
  const [status, setStatus] = useState("")
  const [refundType, setRefundType] = useState("")
  const [resourceStatus, setResourceStatus] = useState("")
  const [userId, setUserId] = useState<number | null>(null)
  const [instanceId, setInstanceId] = useState<number | null>(null)
  const [detail, setDetail] = useState<AdminServiceOrder | null>(null)
  const [detailLoading, setDetailLoading] = useState(false)
  const [actionLoading, setActionLoading] = useState<string | null>(null)

  const loadOrders = useCallback(async () => {
    setLoading(true)
    try {
      const res = await listAdminServiceOrders({
        keyword: keyword.trim() || undefined,
        status: status || undefined,
        refund_type: refundType || undefined,
        resource_status: resourceStatus || undefined,
        user_id: userId ?? undefined,
        instance_id: instanceId ?? undefined,
        limit: 200,
      })
      setOrders(res.data ?? [])
    } catch (error) {
      toast.error(errorMessage(error, "加载服务订单失败"))
    } finally {
      setLoading(false)
    }
  }, [instanceId, keyword, refundType, resourceStatus, status, userId])

  useEffect(() => {
    void loadOrders()
  }, [loadOrders])

  const stats = useMemo(() => ({
    total: orders.length,
    paid: orders.filter((item) => item.status === "paid").length,
    refunded: orders.filter((item) => item.refund).length,
    failed: orders.filter((item) => item.resource_summary?.status === "failed" || (item.resource_summary?.failed_count ?? 0) > 0).length,
  }), [orders])

  const openDetail = async (order: AdminServiceOrder) => {
    setDetail(order)
    setDetailLoading(true)
    try {
      const res = await getAdminServiceOrder(order.id)
      setDetail(res.data ?? order)
    } catch (error) {
      toast.error(errorMessage(error, "加载订单详情失败"))
    } finally {
      setDetailLoading(false)
    }
  }

  const refreshDetail = async () => {
    if (!detail) return
    const res = await getAdminServiceOrder(detail.id)
    setDetail(res.data ?? detail)
  }

  const runAction = async (key: string, label: string, fn: () => Promise<unknown>) => {
    setActionLoading(key)
    try {
      await fn()
      toast.success(`${label}已完成`)
      await Promise.all([loadOrders(), refreshDetail()])
    } catch (error) {
      toast.error(errorMessage(error, `${label}失败`))
    } finally {
      setActionLoading(null)
    }
  }

  const confirmUnsubscribe = (record: AdminServiceOrder) => {
    const policy = record.refund_policy ?? {
      reason: "暂无可退订信息",
      refund_amount: 0,
    }
    Modal.confirm({
      title: "确认退订该订单？",
      okText: "确认退订",
      okButtonProps: { danger: true },
      cancelText: "取消",
      content: (
        <Space orientation="vertical" size={8}>
          <Text>订单号：{record.out_order_no}</Text>
          <Text>退订规则：{policy.reason}</Text>
          <Text>预计退款：<Text strong>{yuan(policy.refund_amount)}</Text></Text>
          {record.points_claimed ? <Text type="warning">该订单已领取积分，可能无法现金退款。</Text> : null}
        </Space>
      ),
      onOk: () => runAction(
        `unsubscribe-${record.id}`,
        "退订",
        () => unsubscribeAdminServiceOrder(record.id),
      ),
    })
  }

  const confirmRetry = (action: UpstreamActionLog) => {
    let remark = ""
    Modal.confirm({
      title: "重试该资源动作？",
      okText: "确认重试",
      cancelText: "取消",
      content: (
        <Space orientation="vertical" size={8} style={{ width: "100%" }}>
          <Text type="secondary">系统会按原请求重新下发一次，并将旧失败动作标记为已被重试替代。</Text>
          <Input.TextArea
            rows={3}
            maxLength={255}
            showCount
            placeholder="处理备注，可选"
            onChange={(event) => { remark = event.target.value }}
          />
        </Space>
      ),
      onOk: () => runAction(
        `retry-${action.id}`,
        "重试",
        () => retryAdminUpstreamAction(action.id, remark.trim() || undefined),
      ),
    })
  }

  const confirmHandled = (action: UpstreamActionLog) => {
    let remark = ""
    Modal.confirm({
      title: "标记为人工已处理？",
      okText: "确认",
      cancelText: "取消",
      content: (
        <Space orientation="vertical" size={8} style={{ width: "100%" }}>
          <Text type="secondary">该动作会被视为已完成，并同步更新相关本地资源状态。</Text>
          <Input.TextArea
            rows={3}
            maxLength={255}
            showCount
            placeholder="处理备注，可选"
            onChange={(event) => { remark = event.target.value }}
          />
        </Space>
      ),
      onOk: () => runAction(
        `handled-${action.id}`,
        "标记已处理",
        () => markAdminUpstreamActionHandled(action.id, remark.trim() || undefined),
      ),
    })
  }

  const confirmIgnore = (action: UpstreamActionLog) => {
    let remark = ""
    Modal.confirm({
      title: "忽略该资源动作？",
      okText: "确认",
      cancelText: "取消",
      content: (
        <Space orientation="vertical" size={8} style={{ width: "100%" }}>
          <Text type="secondary">该动作会从待处理异常中移除，但不会修改本地资源状态。</Text>
          <Input.TextArea
            rows={3}
            maxLength={255}
            showCount
            placeholder="处理备注，可选"
            onChange={(event) => { remark = event.target.value }}
          />
        </Space>
      ),
      onOk: () => runAction(
        `ignore-${action.id}`,
        "忽略",
        () => ignoreAdminUpstreamAction(action.id, remark.trim() || undefined),
      ),
    })
  }

  const orderColumns: TableColumnsType<AdminServiceOrder> = [
    {
      title: "订单号",
      dataIndex: "out_order_no",
      width: 210,
      render: (value: string) => <Text code>{value}</Text>,
    },
    {
      title: "用户",
      width: 150,
      render: (_, record) => (
        <Space orientation="vertical" size={0}>
          <Text>{userLabel(record)}</Text>
          <Text type="secondary" style={{ fontSize: 12 }}>#{record.user?.id ?? "-"}</Text>
        </Space>
      ),
    },
    {
      title: "实例",
      dataIndex: "instances",
      render: (instances: AdminServiceOrder["instances"]) => (
        <Space orientation="vertical" size={2}>
          {(instances ?? []).length > 0 ? (
            (instances ?? []).map((item) => (
              <Space orientation="vertical" size={0} key={item.id}>
                <Text>{item.main_ip || item.hostname || `实例 #${item.id}`}</Text>
                <Text type="secondary" style={{ fontSize: 12 }}>{formatInstanceSpec(item)}</Text>
              </Space>
            ))
          ) : (
            <Text type="secondary">服务订单</Text>
          )}
        </Space>
      ),
    },
    {
      title: "实付 / 退款",
      width: 135,
      align: "right",
      render: (_, record) => (
        <Space orientation="vertical" size={0} align="end">
          <Text strong>{yuan(record.paid_amount)}</Text>
          <Text type="secondary" style={{ fontSize: 12 }}>{record.refund ? `退款 ${yuan(record.refund.refund_amount)}` : "未退款"}</Text>
        </Space>
      ),
    },
    { title: "订单状态", dataIndex: "status", width: 120, render: (value: string) => tag(ORDER_STATUS_META, value) },
    {
      title: "退订规则",
      width: 160,
      render: (_, record) => (
        <Space orientation="vertical" size={2}>
          {tag(REFUND_TYPE_META, record.refund_policy?.refund_type)}
          <Text type="secondary" style={{ fontSize: 12 }}>{record.refund_policy?.reason ?? "暂无可退订信息"}</Text>
        </Space>
      ),
    },
    {
      title: "资源状态",
      width: 145,
      render: (_, record) => (
        <Space orientation="vertical" size={2}>
          {tag(RESOURCE_STATUS_META, record.resource_summary?.status)}
          {(record.resource_summary?.failed_count ?? 0) > 0 ? (
            <Text type="danger" style={{ fontSize: 12 }}>{record.resource_summary?.failed_count ?? 0} 条失败</Text>
          ) : null}
        </Space>
      ),
    },
    { title: "创建时间", dataIndex: "created_at", width: 165, render: fmtDate },
    {
      title: "操作",
      width: 170,
      fixed: "right",
      render: (_, record) => (
        <Space size={6}>
          <Button size="small" icon={<EyeOutlined />} onClick={() => void openDetail(record)}>
            详情
          </Button>
          <Button
            size="small"
            danger
            disabled={!record.refund_policy?.action_allowed}
            loading={actionLoading === `unsubscribe-${record.id}`}
            onClick={() => confirmUnsubscribe(record)}
          >
            退订
          </Button>
        </Space>
      ),
    },
  ]

  const actionColumns: TableColumnsType<UpstreamActionLog> = [
    {
      title: "动作",
      dataIndex: "action_type",
      width: 170,
      render: (value: string, record) => (
        <Space orientation="vertical" size={0}>
          <Text>{ACTION_LABEL[value] ?? value}</Text>
          <Text type="secondary" style={{ fontSize: 12 }}>#{record.id}</Text>
        </Space>
      ),
    },
    { title: "状态", dataIndex: "status", width: 120, render: (value: string) => tag(ACTION_STATUS_META, value) },
    { title: "Task ID", dataIndex: "upstream_task_id", width: 110, render: (value: number | null) => value ? <Text code>{value}</Text> : "-" },
    { title: "备注 / 错误", ellipsis: true, render: (_, record) => record.error_message || record.remark || "-" },
    {
      title: "操作",
      width: 280,
      fixed: "right",
      render: (_, record) => (
        <Space size={6} wrap>
          <Button
            size="small"
            icon={<SyncOutlined />}
            disabled={!record.upstream_task_id}
            loading={actionLoading === `sync-${record.id}`}
            onClick={() => runAction(`sync-${record.id}`, "同步", () => syncAdminUpstreamAction(record.id))}
          >
            同步
          </Button>
          <Button
            size="small"
            danger
            disabled={!["failed", "manual_handled", "ignored"].includes(record.status)}
            loading={actionLoading === `retry-${record.id}`}
            onClick={() => confirmRetry(record)}
          >
            重试
          </Button>
          <Button
            size="small"
            disabled={record.status !== "failed"}
            loading={actionLoading === `handled-${record.id}`}
            onClick={() => confirmHandled(record)}
          >
            已处理
          </Button>
          <Button
            size="small"
            disabled={record.status !== "failed"}
            loading={actionLoading === `ignore-${record.id}`}
            onClick={() => confirmIgnore(record)}
          >
            忽略
          </Button>
        </Space>
      ),
    },
  ]

  return (
    <Space orientation="vertical" size={20} style={{ width: "100%" }}>
      <Row gutter={[16, 16]} align="bottom" justify="space-between">
        <Col>
          <Title level={3} style={{ margin: 0 }}>服务订单处理中心</Title>
          <Paragraph type="secondary" style={{ marginTop: 8, marginBottom: 0 }}>
            集中查看服务订单、退订规则、退款记录和资源动作处理进度。
          </Paragraph>
        </Col>
        <Col>
          <Button icon={<ReloadOutlined />} loading={loading} onClick={() => void loadOrders()}>
            刷新
          </Button>
        </Col>
      </Row>

      <Row gutter={[16, 16]}>
        <Col xs={24} sm={12} xl={6}>
          <Card variant="outlined"><Statistic title="当前订单" value={stats.total} prefix={<FileSearchOutlined />} /></Card>
        </Col>
        <Col xs={24} sm={12} xl={6}>
          <Card variant="outlined"><Statistic title="已支付" value={stats.paid} styles={{ content: { color: "#389e0d" } }} /></Card>
        </Col>
        <Col xs={24} sm={12} xl={6}>
          <Card variant="outlined"><Statistic title="退款记录" value={stats.refunded} styles={{ content: { color: "#722ed1" } }} /></Card>
        </Col>
        <Col xs={24} sm={12} xl={6}>
          <Card variant="outlined"><Statistic title="资源异常" value={stats.failed} styles={{ content: { color: "#cf1322" } }} /></Card>
        </Col>
      </Row>

      <Card variant="outlined">
        <Space orientation="vertical" size={16} style={{ width: "100%" }}>
          <Row gutter={[12, 12]}>
            <Col xs={24} md={8}>
              <Input
                allowClear
                prefix={<SearchOutlined />}
                placeholder="订单号 / 用户 / 主机名 / IP"
                value={keyword}
                onChange={(event) => setKeyword(event.target.value)}
                onPressEnter={() => void loadOrders()}
              />
            </Col>
            <Col>
              <Select
                value={status}
                onChange={setStatus}
                style={{ width: 140 }}
                options={[
                  { value: "", label: "全部状态" },
                  { value: "paid", label: "已支付" },
                  { value: "cancelled", label: "已退订" },
                  { value: "refunded", label: "已退款" },
                  { value: "pending", label: "待处理" },
                ]}
              />
            </Col>
            <Col>
              <Select
                value={refundType}
                onChange={setRefundType}
                style={{ width: 150 }}
                options={[
                  { value: "", label: "全部规则" },
                  { value: "full", label: "全额退款" },
                  { value: "prorated", label: "按量退款" },
                  { value: "no_refund", label: "不退款" },
                ]}
              />
            </Col>
            <Col>
              <Select
                value={resourceStatus}
                onChange={setResourceStatus}
                style={{ width: 155 }}
                options={[
                  { value: "", label: "全部资源" },
                  { value: "none", label: "无资源动作" },
                  { value: "running", label: "处理中" },
                  { value: "failed", label: "失败" },
                  { value: "finished", label: "已完成" },
                  { value: "manual_handled", label: "人工已处理" },
                  { value: "ignored", label: "已忽略" },
                ]}
              />
            </Col>
            <Col>
              <InputNumber min={1} precision={0} placeholder="用户 ID" value={userId} onChange={(value) => setUserId(typeof value === "number" ? value : null)} />
            </Col>
            <Col>
              <InputNumber min={1} precision={0} placeholder="实例 ID" value={instanceId} onChange={(value) => setInstanceId(typeof value === "number" ? value : null)} />
            </Col>
            <Col flex="auto" />
            <Col>
              <Button type="primary" icon={<SearchOutlined />} loading={loading} onClick={() => void loadOrders()}>
                查询
              </Button>
            </Col>
          </Row>

          <Table
            rowKey="id"
            loading={loading}
            columns={orderColumns}
            dataSource={orders}
            pagination={{ pageSize: 12, showSizeChanger: false }}
            scroll={{ x: 1280 }}
            locale={{ emptyText: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无服务订单" /> }}
          />
        </Space>
      </Card>

      <Modal
        title="服务订单详情"
        open={!!detail}
        onCancel={() => setDetail(null)}
        footer={(
          <Space>
            {detail?.refund_policy?.action_allowed ? (
              <Button
                danger
                loading={actionLoading === `unsubscribe-${detail.id}`}
                onClick={() => detail && confirmUnsubscribe(detail)}
              >
                退订
              </Button>
            ) : null}
            <Button onClick={() => setDetail(null)}>关闭</Button>
          </Space>
        )}
        width={1080}
      >
        {detail ? (
          <Space orientation="vertical" size={16} style={{ width: "100%" }}>
            <Descriptions column={2} size="small" bordered>
              <Descriptions.Item label="订单号">{detail.out_order_no}</Descriptions.Item>
              <Descriptions.Item label="订单状态">{tag(ORDER_STATUS_META, detail.status)}</Descriptions.Item>
              <Descriptions.Item label="用户">{userLabel(detail)} #{detail.user?.id ?? "-"}</Descriptions.Item>
              <Descriptions.Item label="创建时间">{fmtDate(detail.created_at)}</Descriptions.Item>
              <Descriptions.Item label="实付金额">{yuan(detail.paid_amount)}</Descriptions.Item>
              <Descriptions.Item label="预计退款">{yuan(detail.refund_policy?.refund_amount)}</Descriptions.Item>
              <Descriptions.Item label="积分状态">{detail.points_claimed ? <Tag color="red">已领取</Tag> : <Tag color="blue">未领取</Tag>}</Descriptions.Item>
              <Descriptions.Item label="资源状态">{tag(RESOURCE_STATUS_META, detail.resource_summary?.status)}</Descriptions.Item>
              <Descriptions.Item label="退订规则" span={2}>{detail.refund_policy?.reason ?? "暂无可退订信息"}</Descriptions.Item>
              <Descriptions.Item label="退款记录" span={2}>
                {detail.refund ? (
                  <Space orientation="vertical" size={2}>
                    <Text>{detail.refund.refund_no} / {yuan(detail.refund.refund_amount)} / {detail.refund.status}</Text>
                    <Space size={4}>
                      {tag(RESOURCE_STATUS_META, detail.refund.resource_status)}
                      {detail.refund.resource_error ? <Text type="danger">{detail.refund.resource_error}</Text> : null}
                    </Space>
                  </Space>
                ) : "-"}
              </Descriptions.Item>
            </Descriptions>

            <Card title="处理时间线" variant="outlined" loading={detailLoading}>
              {detail.timeline?.length ? (
                <Timeline
                  items={detail.timeline.map((item) => ({
                    key: item.key,
                    color: timelineColor(item.status),
                    children: (
                      <Space orientation="vertical" size={2}>
                        <Space wrap size={6}>
                          <Text strong>{item.title}</Text>
                          {item.status ? <Tag>{item.status}</Tag> : null}
                          {item.kind ? <Tag color="blue">{item.kind}</Tag> : null}
                        </Space>
                        {item.description ? <Text type="secondary">{item.description}</Text> : null}
                        <Text type="secondary" style={{ fontSize: 12 }}>
                          {fmtDate(item.at)}
                          {item.ref_id ? ` / #${item.ref_id}` : ""}
                        </Text>
                      </Space>
                    ),
                  }))}
                />
              ) : (
                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无时间线" />
              )}
            </Card>

            <Card title="关联实例" variant="outlined" loading={detailLoading}>
              <Table
                rowKey="id"
                size="small"
                pagination={false}
                dataSource={detail.instances || []}
                columns={[
                  { title: "ID", dataIndex: "id", width: 60 },
                  {
                    title: "标识",
                    render: (_, record) => (
                      <Space orientation="vertical" size={0}>
                        <Text>{record.hostname || "-"}</Text>
                        <Text type="secondary" style={{ fontSize: 12 }}>{record.main_ip || "-"}</Text>
                      </Space>
                    ),
                  },
                  { title: "规格", render: (_, record) => <Text style={{ fontSize: 12 }}>{formatInstanceSpec(record)}</Text> },
                  { title: "状态", dataIndex: "status", width: 120, render: (value: string) => tag(INSTANCE_STATUS_META, value) },
                  { title: "到期时间", dataIndex: "expires_at", width: 165, render: fmtDate },
                ]}
                locale={{ emptyText: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无实例" /> }}
              />
            </Card>

            <Card title="资源动作" variant="outlined" loading={detailLoading}>
              <Table
                rowKey="id"
                size="small"
                columns={actionColumns}
                dataSource={detail.upstream_actions || []}
                pagination={false}
                scroll={{ x: 960 }}
                locale={{ emptyText: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无资源动作" /> }}
              />
            </Card>
          </Space>
        ) : null}
      </Modal>
    </Space>
  )
}
