const { useState, useMemo, useEffect, useCallback } = React;
const {
  Card, Table, Button, Space, Tag, Badge, Tabs, Descriptions, Modal,
  Form, Input, Select, Checkbox, DatePicker, Row, Col,
  Alert, Tooltip, Typography, Divider, Timeline, Switch, message, Spin,
} = antd;
const {
  PlusOutlined, SearchOutlined, ExportOutlined, WarningOutlined,
  EditOutlined, EyeOutlined, UserOutlined, FileProtectOutlined,
  PhoneOutlined, AuditOutlined, SolutionOutlined, SendOutlined,
  RollbackOutlined, ExclamationCircleOutlined, SafetyOutlined, ReloadOutlined,
} = icons;
const { Text, Title } = Typography;
const { TextArea } = Input;

// ---- API client ----
const api = {
  async get(path) {
    const res = await fetch(`/api/${path}`);
    if (!res.ok) throw new Error(await res.text());
    return res.json();
  },
  async post(path, body) {
    const res = await fetch(`/api/${path}`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body),
    });
    if (!res.ok) throw new Error(await res.text());
    return res.json();
  },
};

// ---- constants ----
const COST_TYPES = [
  { value: "FUEL", label: "航油" }, { value: "GROUND_HANDLING", label: "地面操作" },
  { value: "AIRPORT", label: "机场" }, { value: "WAREHOUSE", label: "货站操作" },
  { value: "CATERING", label: "航食" }, { value: "CREW_TRANSPORT", label: "机组地面交通" },
  { value: "HOTEL", label: "酒店" }, { value: "TRUCKING", label: "卡车转运" },
];
const COOP_STATUS = [
  { value: "ACTIVE", label: "合作中", color: "green" },
  { value: "POTENTIAL", label: "潜在", color: "blue" },
  { value: "SUSPENDED", label: "暂停", color: "orange" },
  { value: "BLACKLISTED", label: "黑名单", color: "red" },
];
const APPROVAL_STATUS = [
  { value: "DRAFT", label: "草稿", color: "default" },
  { value: "PENDING_APPROVAL", label: "审批中", color: "processing" },
  { value: "APPROVED", label: "已生效", color: "success" },
  { value: "REJECTED", label: "已驳回", color: "error" },
];
const SELECTABLE_VENDORS = [
  { id: "1", code: "V2026-0001", name: "Asia Fuel Supply Ltd", disabled: true, reason: "资质过期" },
  { id: "6", code: "V2026-0004", name: "Pacific Oil Trading", disabled: false },
  { id: "7", code: "V2026-0009", name: "JetFuel Partners", disabled: false },
  { id: "4", code: "V2025-0042", name: "Legacy Vendor Inc", disabled: true, reason: "档案不完整" },
];
const alertTypeMap = {
  qual_expiring: { text: "资质即将到期", color: "orange" },
  qual_expired: { text: "资质已过期", color: "red" },
  contract_expiring: { text: "合同即将到期", color: "orange" },
  contract_expired: { text: "合同已失效", color: "red" },
  no_contact: { text: "无有效对接人", color: "purple" },
  major_issue: { text: "重大履约", color: "red" },
  incomplete: { text: "档案不完整", color: "gold" },
};

// ---- VendorListView ----
const VendorListView = ({ vendors, loading, onViewDetail, onAddVendor }) => {
  const [onlyMine, setOnlyMine] = useState(false);
  const [createVisible, setCreateVisible] = useState(false);
  const [saving, setSaving] = useState(false);
  const [createForm] = Form.useForm();

  const qualStatusRender = (status) => {
    if (!status) return <Text type="secondary">—</Text>;
    if (status === "valid") return <Tag color="green">有效</Tag>;
    if (status === "expiring") return <Tag color="orange">即将到期</Tag>;
    if (status === "expired") return <Tag color="red">已过期·限制询价与新建合同</Tag>;
  };
  const columns = [
    { title: "编码", dataIndex: "code", width: 120 },
    { title: "名称", dataIndex: "name", width: 180, render: (text, r) => <Button type="link" size="small" onClick={() => onViewDetail(r)}>{text}</Button> },
    { title: "品类", dataIndex: "categories", width: 160, render: (cats) => (!cats || cats.length === 0) ? <Tag color="gold">档案不完整</Tag> : cats.map(c => <Tag key={c}>{COST_TYPES.find(t => t.value === c)?.label}</Tag>) },
    { title: "国家", dataIndex: "country", width: 60 },
    { title: "覆盖机场", dataIndex: "airports", width: 120, render: (v) => (Array.isArray(v) ? v.join(" / ") : v) || "—" },
    { title: "合作状态", dataIndex: "coop_status", width: 90, render: (v) => { const s = COOP_STATUS.find(x => x.value === v); return <Tag color={s?.color}>{s?.label}</Tag>; } },
    { title: "标记", dataIndex: "coop_tag", width: 70, render: (v) => v === "PREFERRED" ? "首选" : v === "STRATEGIC" ? "战略" : v === "BACKUP" ? "备选" : "—" },
    { title: "资质", dataIndex: "qual_status", width: 160, render: qualStatusRender },
    { title: "合同", dataIndex: "contract_status", width: 90, render: qualStatusRender },
    { title: "负责人", dataIndex: "owner", width: 80, render: (v) => v || <Text type="secondary">未分配</Text> },
    { title: "操作", width: 120, fixed: "right", render: (_, r) => (<Space size="small"><Button type="link" size="small" icon={<EyeOutlined />} onClick={() => onViewDetail(r)}>查看</Button><Button type="link" size="small" icon={<EditOutlined />} onClick={() => onViewDetail(r)}>编辑</Button></Space>) },
  ];

  const handleCreate = async () => {
    const values = await createForm.validateFields();
    setSaving(true);
    try {
      const created = await api.post("vendors", {
        ...values,
        airports: values.airports?.split(/[\/,\s]+/).map(s => s.trim()).filter(Boolean) || [],
      });
      onAddVendor(created);
      createForm.resetFields();
      setCreateVisible(false);
      message.success(`供应商 ${created.code} 已创建`);
    } catch (e) { message.error(e.message); }
    finally { setSaving(false); }
  };

  return (
    <>
      <Card size="small" style={{ marginBottom: 16 }}>
        <Space wrap>
          <Input placeholder="供应商名称" prefix={<SearchOutlined />} style={{ width: 160 }} />
          <Input placeholder="编码 V2026-..." style={{ width: 140 }} />
          <Input placeholder="机场三字码" style={{ width: 100 }} />
          <Select placeholder="品类" style={{ width: 140 }} options={[{ value: "", label: "全部" }, ...COST_TYPES]} allowClear />
          <Select placeholder="合作状态" style={{ width: 110 }} options={[{ value: "", label: "全部" }, ...COOP_STATUS]} allowClear />
          <Select placeholder="资质到期" style={{ width: 130 }} options={[{ value: "", label: "全部" }, { value: "30d", label: "30天内" }, { value: "expired", label: "已过期" }]} allowClear />
          <Select placeholder="合同到期" style={{ width: 130 }} options={[{ value: "", label: "全部" }, { value: "30d", label: "30天内" }, { value: "expired", label: "已过期" }]} allowClear />
          <Divider type="vertical" />
          <Switch size="small" checked={onlyMine} onChange={setOnlyMine} />
          <Text type="secondary" style={{ fontSize: 12 }}>只看我的</Text>
          <Divider type="vertical" />
          <Button type="primary" icon={<SearchOutlined />} onClick={() => message.info("Demo: 筛选功能仅为交互展示")}>查询</Button>
          <Button onClick={() => message.info("Demo: 已重置筛选条件")}>重置</Button>
        </Space>
      </Card>
      <div className="stat-bar">
        <Tag>总数 <Text strong>{vendors.length}</Text></Tag>
        <Tag color="orange">资质预警 2</Tag><Tag color="orange">合同预警 1</Tag>
        <Tag color="purple">无对接人 1</Tag><Tag color="gold">档案不完整 2</Tag>
        <Tag color="red">黑名单/暂停 1</Tag>
      </div>
      <Card size="small" title="供应商清单" extra={<Space><Button type="primary" icon={<PlusOutlined />} onClick={() => setCreateVisible(true)}>新建供应商</Button><Button icon={<ExportOutlined />} onClick={() => message.info("Demo: 导出功能仅为交互展示")}>导出 Excel</Button></Space>}>
        <Table size="small" columns={columns} dataSource={vendors} rowKey="id" loading={loading} pagination={{ total: vendors.length, pageSize: 20, showTotal: t => `共 ${t} 条` }} scroll={{ x: 1400 }} />
      </Card>
      <Modal title="新建供应商" open={createVisible} confirmLoading={saving} onCancel={() => { setCreateVisible(false); createForm.resetFields(); }} onOk={handleCreate} okText="保存并进入详情" width={640}>
        <Form form={createForm} layout="vertical">
          <Form.Item label="供应商名称" name="name" rules={[{ required: true }]} extra="同组织内名称完全相同将被拦截"><Input placeholder="主体全称" /></Form.Item>
          <Form.Item label="品类 / 费用类型（至少选 1 项）" name="categories" rules={[{ required: true }]}><Select mode="multiple" placeholder="可多选" options={COST_TYPES} /></Form.Item>
          <Row gutter={16}>
            <Col span={8}><Form.Item label="合作状态" name="coop_status" rules={[{ required: true }]} initialValue="POTENTIAL"><Select options={COOP_STATUS} /></Form.Item></Col>
            <Col span={8}><Form.Item label="国家" name="country" rules={[{ required: true }]}><Select placeholder="请选择" options={[{ value: "CN" }, { value: "HK" }, { value: "AE" }, { value: "SG" }]} /></Form.Item></Col>
            <Col span={8}><Form.Item label="合作标记" name="coop_tag"><Select placeholder="无" options={[{ value: "STRATEGIC", label: "战略" }, { value: "PREFERRED", label: "首选" }, { value: "BACKUP", label: "备选" }]} allowClear /></Form.Item></Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}><Form.Item label="覆盖机场" name="airports" rules={[{ required: true }]} extra="为空不算任何机场的准入供应商"><Input placeholder="多个用 / 分隔，如 HKG/PVG" /></Form.Item></Col>
            <Col span={12}><Form.Item label="负责人" name="owner"><Select placeholder="请选择" options={[{ value: "张三" }, { value: "李四" }, { value: "王五" }]} allowClear /></Form.Item></Col>
          </Row>
          <Form.Item label="备注" name="remarks"><TextArea rows={2} placeholder="服务范围、初步沟通内容…" /></Form.Item>
        </Form>
      </Modal>
    </>
  );
};

// ---- VendorDetailView ----
const VendorDetailView = ({ vendor, onBack, onCreateRfq }) => {
  const v = vendor;
  const [contacts, setContacts] = useState([]);
  const [quals, setQuals] = useState([]);
  const [contracts, setContracts] = useState([]);
  const [followUps, setFollowUps] = useState([]);
  const [perfs, setPerfs] = useState([]);
  const [loadingDetail, setLoadingDetail] = useState(true);
  const [contactFormVisible, setContactFormVisible] = useState(false);
  const [followFormVisible, setFollowFormVisible] = useState(false);
  const [perfFormVisible, setPerfFormVisible] = useState(false);
  const [contactForm] = Form.useForm();
  const [followForm] = Form.useForm();
  const [perfForm] = Form.useForm();

  useEffect(() => {
    if (!v) return;
    setLoadingDetail(true);
    Promise.all([
      api.get(`contacts?vendor_id=${v.id}`),
      api.get(`qualifications?vendor_id=${v.id}`),
      api.get(`contracts?vendor_id=${v.id}`),
      api.get(`follow-ups?vendor_id=${v.id}`),
      api.get(`perf-records?vendor_id=${v.id}`),
    ]).then(([c, q, ct, f, p]) => {
      setContacts(c); setQuals(q); setContracts(ct); setFollowUps(f); setPerfs(p);
    }).finally(() => setLoadingDetail(false));
  }, [v?.id]);

  if (!v) return null;

  const handleAddContact = async () => {
    const values = await contactForm.validateFields();
    const created = await api.post("contacts", { vendor_id: v.id, ...values, is_emergency: !!values.is_emergency });
    setContacts(prev => [...prev, created]);
    contactForm.resetFields(); setContactFormVisible(false);
    message.success("联系人已添加");
  };
  const handleAddFollowUp = async () => {
    const values = await followForm.validateFields();
    const created = await api.post("follow-ups", {
      vendor_id: v.id, time: values.time?.format("YYYY-MM-DD HH:mm") || new Date().toISOString().slice(0, 10),
      channel: values.channel, user: "当前用户", content: values.content,
      conclusion: values.conclusion || "", todo: values.todo || null,
      next_followup: values.next_followup?.format("YYYY-MM-DD") || null,
    });
    setFollowUps(prev => [created, ...prev]);
    followForm.resetFields(); setFollowFormVisible(false);
    message.success("跟进记录已保存");
  };
  const handleAddPerf = async () => {
    const values = await perfForm.validateFields();
    const created = await api.post("perf-records", {
      vendor_id: v.id, date: values.date?.format("YYYY-MM-DD") || new Date().toISOString().slice(0, 10),
      airport: values.airport, type: values.type, desc: values.desc,
      resolution: values.resolution || "", is_major: !!values.is_major,
    });
    setPerfs(prev => [...prev, created]);
    perfForm.resetFields(); setPerfFormVisible(false);
    message.success("履约异常已记录");
  };

  const approvalTag = (status) => { const s = APPROVAL_STATUS.find(x => x.value === status); return <Badge status={s?.color} text={s?.label} />; };
  const contractColumns = [
    { title: "服务类型", dataIndex: "type", width: 100, render: v => COST_TYPES.find(t => t.value === v)?.label },
    { title: "机场", dataIndex: "airport", width: 60 },
    { title: "扫描件", dataIndex: "scan", width: 140, render: v => v ? <Button type="link" size="small" onClick={() => message.info("Demo: 文件预览功能仅为交互展示")}>{v}</Button> : <Text type="secondary">未上传</Text> },
    { title: "生效", dataIndex: "valid_from", width: 100 }, { title: "到期", dataIndex: "valid_to", width: 100 },
    { title: "账期", dataIndex: "settlement", width: 70 },
    { title: "信用额度", dataIndex: "credit", width: 100, render: v => v ? v.toLocaleString() : "—" },
    { title: "审批状态", dataIndex: "approval_status", width: 120, render: status => !status ? <Text type="secondary">—（存量）</Text> : approvalTag(status) },
    { title: "有效期", dataIndex: "expiry", width: 140, render: v => { if (!v) return "—"; if (v === "expiring") return <Tag color="orange">即将到期</Tag>; if (v === "expired") return <Tag color="red">已失效</Tag>; } },
    { title: "操作", width: 180, fixed: "right", render: (_, r) => {
      const tip = () => message.info("Demo: 合同操作功能仅为交互展示");
      if (r.approval_status === "PENDING_APPROVAL") return <Space size="small"><Button size="small" icon={<RollbackOutlined />} onClick={tip}>撤回审批</Button><Button size="small" disabled>编辑(锁定)</Button></Space>;
      if (r.approval_status === "DRAFT") return <Space size="small"><Button size="small" icon={<EditOutlined />} onClick={tip}>编辑</Button><Button size="small" type="primary" icon={<SendOutlined />} onClick={tip}>提交审批</Button></Space>;
      if (r.approval_status === "REJECTED") return <Space size="small"><Button size="small" icon={<EditOutlined />} onClick={tip}>编辑</Button><Button size="small" type="primary" icon={<SendOutlined />} onClick={tip}>重新提交</Button></Space>;
      if (r.expiry === "expiring") return <Space size="small"><Button size="small" onClick={tip}>续约</Button><Button size="small" onClick={tip}>重新寻源</Button></Space>;
      if (r.expiry === "expired") return <Button size="small" onClick={tip}>更新合同</Button>;
      return <Button size="small" icon={<EyeOutlined />} onClick={tip}>查看</Button>;
    }},
  ];
  const contactColumns = [
    { title: "姓名", dataIndex: "name", width: 100 }, { title: "岗位", dataIndex: "position", width: 100 },
    { title: "邮箱", dataIndex: "email", width: 180, render: v => v || "—" },
    { title: "电话", dataIndex: "phone", width: 120, render: v => v || "—" },
    { title: "紧急联系人", dataIndex: "is_emergency", width: 90, render: v => v ? <Tag color="red">是</Tag> : "否" },
    { title: "状态", dataIndex: "is_active", width: 100, render: v => v ? <Badge status="success" text="有效" /> : <Badge status="default" text="已停用" /> },
    { title: "操作", width: 140, render: (_, r) => r.is_active ? <Space size="small"><Button type="link" size="small" onClick={() => message.info("Demo: 编辑联系人功能仅为交互展示")}>编辑</Button><Button type="link" size="small" danger onClick={() => message.info("Demo: 停用功能仅为交互展示")}>停用</Button></Space> : <Button type="link" size="small" onClick={() => message.info("Demo: 查看功能仅为交互展示")}>查看</Button> },
  ];
  const qualColumns = [
    { title: "资质类型", dataIndex: "type", width: 120, render: (v, r) => <>{r.name}{r.mandatory ? <Text type="danger"> *</Text> : null}</> },
    { title: "附件", dataIndex: "file", width: 140, render: v => v ? <Button type="link" size="small" onClick={() => message.info("Demo: 文件预览功能仅为交互展示")}>{v}</Button> : <Text type="secondary">待补原件</Text> },
    { title: "生效日", dataIndex: "valid_from", width: 100 }, { title: "到期日", dataIndex: "valid_to", width: 100 },
    { title: "状态", dataIndex: "status", width: 140, render: v => { if (v === "VALID") return <Tag color="green">有效</Tag>; if (v === "EXPIRING") return <Tag color="orange">即将到期</Tag>; if (v === "EXPIRED") return <Tag color="red">已过期</Tag>; return <Tag>待补原件</Tag>; } },
    { title: "操作", width: 80, render: () => <Button type="link" size="small" onClick={() => message.info("Demo: 资质更新功能仅为交互展示")}>更新</Button> },
  ];

  const tabItems = [
    { key: "profile", label: "档案", children: (<Descriptions bordered size="small" column={2}><Descriptions.Item label="编码">{v.code}</Descriptions.Item><Descriptions.Item label="名称">{v.name}</Descriptions.Item><Descriptions.Item label="品类">{(v.categories || []).map(c => <Tag key={c}>{COST_TYPES.find(t => t.value === c)?.label}</Tag>)}</Descriptions.Item><Descriptions.Item label="合作状态"><Tag color={COOP_STATUS.find(s => s.value === v.coop_status)?.color}>{COOP_STATUS.find(s => s.value === v.coop_status)?.label}</Tag></Descriptions.Item><Descriptions.Item label="国家">{v.country || "—"}</Descriptions.Item><Descriptions.Item label="覆盖机场">{(Array.isArray(v.airports) ? v.airports.join(" / ") : v.airports) || "（未设置）"}</Descriptions.Item><Descriptions.Item label="负责人">{v.owner || "未分配"}</Descriptions.Item><Descriptions.Item label="所属组织">总部</Descriptions.Item></Descriptions>) },
    { key: "qual", label: "资质", children: (<><Alert type="warning" showIcon style={{ marginBottom: 12 }} message="闸门规则（服务端强制）：资质过期或即将到期 → 限制该供应商新增询价 AND 新建合同。" /><Button type="primary" icon={<PlusOutlined />} style={{ marginBottom: 12 }} onClick={() => message.info("Demo: 上传资质功能仅为交互展示")}>上传资质</Button><Table size="small" columns={qualColumns} dataSource={quals} rowKey="id" loading={loadingDetail} pagination={false} /></>) },
    { key: "contact", label: "联系人", children: (<><Button type="primary" icon={<PlusOutlined />} style={{ marginBottom: 12 }} onClick={() => setContactFormVisible(true)}>新增联系人</Button><Table size="small" columns={contactColumns} dataSource={contacts} rowKey="id" loading={loadingDetail} pagination={false} /><Alert type="info" showIcon style={{ marginTop: 12 }} message="离职联系人仅停用保留历史，不删除。" /></>) },
    { key: "contract", label: "合同", children: (<><Space style={{ marginBottom: 12 }}><Button type="primary" icon={<PlusOutlined />} onClick={() => message.info("Demo: 新建合同功能仅为交互展示")}>新建合同</Button><Button icon={<AuditOutlined />} onClick={() => message.info("Demo: 手动审批功能仅为交互展示")}>手动审批（管理员降级）</Button></Space><Table size="small" columns={contractColumns} dataSource={contracts} rowKey="id" loading={loadingDetail} pagination={false} scroll={{ x: 1300 }} /><Alert type="info" showIcon style={{ marginTop: 12 }} message="审批流：DRAFT → PENDING_APPROVAL → APPROVED / REJECTED" /></>) },
    { key: "follow", label: "跟进时间线", children: (<><Button type="primary" icon={<PlusOutlined />} style={{ marginBottom: 12 }} onClick={() => setFollowFormVisible(true)}>新增跟进记录</Button>{loadingDetail ? <Spin /> : <Timeline items={followUps.map((f, i) => ({ color: i === 0 ? "blue" : "gray", children: <><Text strong>{f.time}</Text> · {f.channel} · {f.user}<br />{f.content}<br /><Text type="secondary">结论：{f.conclusion}{f.todo ? ` · 待办：${f.todo}` : ""}{f.next_followup ? ` · 下次回访：${f.next_followup}` : ""}</Text></> }))} />}</>) },
    { key: "perf", label: "履约异常", children: (<><Button type="primary" icon={<PlusOutlined />} style={{ marginBottom: 12 }} onClick={() => setPerfFormVisible(true)}>登记履约异常</Button><Table size="small" rowKey="id" loading={loadingDetail} pagination={false} dataSource={perfs} columns={[{ title: "事件时间", dataIndex: "date", width: 100 }, { title: "机场/航线", dataIndex: "airport", width: 120 }, { title: "问题类型", dataIndex: "type", width: 100 }, { title: "描述", dataIndex: "desc", width: 200 }, { title: "处理结果", dataIndex: "resolution", width: 160 }, { title: "重大", dataIndex: "is_major", width: 80, render: v => v ? <Tag color="red">重大</Tag> : "否" }]} /></>) },
    { key: "approval_log", label: "审批记录", children: (<Table size="small" rowKey="id" pagination={false} dataSource={[{ id: "al1", contract: "航油@HKG", action: "重新提交", from_status: "REJECTED", to_status: "PENDING_APPROVAL", operator: "张三", time: "2026-07-12 11:30", remark: "修改附加费条款后重新提交" }, { id: "al2", contract: "航油@HKG", action: "驳回", from_status: "PENDING_APPROVAL", to_status: "REJECTED", operator: "赵总", time: "2026-07-10 17:22", remark: "附加费条款需细化" }, { id: "al5", contract: "航油@PVG", action: "批准", from_status: "PENDING_APPROVAL", to_status: "APPROVED", operator: "赵总", time: "2025-11-20 16:10", remark: null }]} columns={[{ title: "合同", dataIndex: "contract", width: 120 }, { title: "操作", dataIndex: "action", width: 90, render: v => { if (v === "批准") return <Tag color="green">{v}</Tag>; if (v === "驳回") return <Tag color="red">{v}</Tag>; return <Tag color="blue">{v}</Tag>; } }, { title: "原状态", dataIndex: "from_status", width: 100, render: v => APPROVAL_STATUS.find(a => a.value === v)?.label || "—" }, { title: "目标状态", dataIndex: "to_status", width: 100, render: v => APPROVAL_STATUS.find(a => a.value === v)?.label || "—" }, { title: "操作人", dataIndex: "operator", width: 70 }, { title: "时间", dataIndex: "time", width: 140 }, { title: "备注", dataIndex: "remark", render: v => v || "—" }]} />) },
    { key: "log", label: "操作日志", children: (<Table size="small" rowKey="id" pagination={false} dataSource={[{ id: "l1", time: "2026-07-10 14:22", user: "张三", action: "上传", target: "资质", summary: "更新保险凭证" }, { id: "l2", time: "2026-07-08 09:10", user: "张三", action: "修改", target: "主档", summary: "标记：备选 → 首选" }, { id: "l3", time: "2026-06-20 16:01", user: "李四", action: "新增", target: "跟进", summary: "新增沟通记录" }]} columns={[{ title: "时间", dataIndex: "time", width: 140 }, { title: "操作人", dataIndex: "user", width: 80 }, { title: "动作", dataIndex: "action", width: 60 }, { title: "对象", dataIndex: "target", width: 80 }, { title: "摘要", dataIndex: "summary" }]} />) },
  ];

  return (
    <>
      <Button onClick={onBack} style={{ marginBottom: 12 }}>← 返回列表</Button>
      <Card size="small" style={{ marginBottom: 16 }}>
        <Descriptions size="small" column={4}>
          <Descriptions.Item label="编码">{v.code}</Descriptions.Item>
          <Descriptions.Item label="名称"><Text strong>{v.name}</Text></Descriptions.Item>
          <Descriptions.Item label="品类">{(v.categories || []).map(c => <Tag key={c}>{COST_TYPES.find(t => t.value === c)?.label}</Tag>)}</Descriptions.Item>
          <Descriptions.Item label="状态"><Tag color={COOP_STATUS.find(s => s.value === v.coop_status)?.color}>{COOP_STATUS.find(s => s.value === v.coop_status)?.label}</Tag></Descriptions.Item>
        </Descriptions>
        <Divider style={{ margin: "8px 0" }} />
        <Space>
          <Button icon={<EditOutlined />} onClick={() => message.info("Demo: 编辑主档功能仅为交互展示")}>编辑主档</Button>
          <Button icon={<SearchOutlined />} onClick={() => onCreateRfq?.(v)}>发起询价</Button>
          <Button icon={<FileProtectOutlined />} onClick={() => message.info("Demo: 新建合同功能仅为交互展示")}>新建合同</Button>
          <Button icon={<PhoneOutlined />} onClick={() => setFollowFormVisible(true)}>新增跟进</Button>
        </Space>
      </Card>
      <Card size="small"><Tabs items={tabItems} /></Card>

      <Modal title="新增联系人" open={contactFormVisible} onCancel={() => { setContactFormVisible(false); contactForm.resetFields(); }} onOk={handleAddContact} okText="保存" width={520}>
        <Form form={contactForm} layout="vertical">
          <Row gutter={16}><Col span={12}><Form.Item label="姓名" name="name" rules={[{ required: true }]}><Input placeholder="联系人全名" /></Form.Item></Col><Col span={12}><Form.Item label="岗位" name="position" rules={[{ required: true }]}><Select placeholder="请选择" options={[{ value: "商务对接" }, { value: "运营操作" }, { value: "财务对账" }]} /></Form.Item></Col></Row>
          <Row gutter={16}><Col span={12}><Form.Item label="邮箱" name="email"><Input placeholder="name@company.com" /></Form.Item></Col><Col span={12}><Form.Item label="电话" name="phone"><Input placeholder="+852-xxxx-xxxx" /></Form.Item></Col></Row>
          <Form.Item name="is_emergency" valuePropName="checked"><Checkbox>标记为紧急联系人</Checkbox></Form.Item>
        </Form>
      </Modal>
      <Modal title="新增跟进记录" open={followFormVisible} onCancel={() => { setFollowFormVisible(false); followForm.resetFields(); }} onOk={handleAddFollowUp} okText="保存" width={560}>
        <Form form={followForm} layout="vertical">
          <Row gutter={16}><Col span={8}><Form.Item label="沟通时间" name="time" rules={[{ required: true }]}><DatePicker showTime style={{ width: "100%" }} /></Form.Item></Col><Col span={8}><Form.Item label="渠道" name="channel" rules={[{ required: true }]}><Select options={[{ value: "邮件" }, { value: "电话" }, { value: "会议" }, { value: "微信" }]} /></Form.Item></Col><Col span={8}><Form.Item label="下次回访" name="next_followup"><DatePicker style={{ width: "100%" }} /></Form.Item></Col></Row>
          <Form.Item label="沟通内容" name="content" rules={[{ required: true }]}><TextArea rows={3} placeholder="沟通要点…" /></Form.Item>
          <Form.Item label="结论" name="conclusion"><Input placeholder="如：对方同意续签" /></Form.Item>
          <Form.Item label="待办事项" name="todo"><Input placeholder="如：准备比价表" /></Form.Item>
        </Form>
      </Modal>
      <Modal title="登记履约异常" open={perfFormVisible} onCancel={() => { setPerfFormVisible(false); perfForm.resetFields(); }} onOk={handleAddPerf} okText="保存" width={560}>
        <Form form={perfForm} layout="vertical">
          <Row gutter={16}><Col span={8}><Form.Item label="事件时间" name="date" rules={[{ required: true }]}><DatePicker style={{ width: "100%" }} /></Form.Item></Col><Col span={8}><Form.Item label="涉及机场/航线" name="airport" rules={[{ required: true }]}><Input placeholder="如 HKG / CT158" /></Form.Item></Col><Col span={8}><Form.Item label="问题类型" name="type" rules={[{ required: true }]}><Select options={[{ value: "供油异常" }, { value: "单证延迟" }, { value: "价格争议" }, { value: "服务失误" }, { value: "其他" }]} /></Form.Item></Col></Row>
          <Form.Item label="问题描述" name="desc" rules={[{ required: true }]}><TextArea rows={3} /></Form.Item>
          <Form.Item label="处理结果" name="resolution"><TextArea rows={2} /></Form.Item>
          <Form.Item name="is_major" valuePropName="checked"><Checkbox>标记为重大履约问题</Checkbox></Form.Item>
        </Form>
      </Modal>
    </>
  );
};

// ---- RfqCompareView ----
const RfqCompareView = ({ initialRfq }) => {
  const [rfqs, setRfqs] = useState([]);
  const [quotes, setQuotes] = useState([]);
  const [loading, setLoading] = useState(true);
  const [rfqFormVisible, setRfqFormVisible] = useState(!!initialRfq);
  const [quoteFormVisible, setQuoteFormVisible] = useState(false);
  const [selectedRfq, setSelectedRfq] = useState(null);
  const [rfqForm] = Form.useForm();
  const [quoteForm] = Form.useForm();

  const loadData = useCallback(async () => {
    setLoading(true);
    const [r, q] = await Promise.all([api.get("rfqs"), api.get("quotes")]);
    setRfqs(r); setQuotes(q); setLoading(false);
  }, []);
  useEffect(() => { loadData(); }, [loadData]);

  const handleAddRfq = async () => {
    const values = await rfqForm.validateFields();
    const created = await api.post("rfqs", {
      airport: values.airport, service_type: values.service_type,
      period: [values.period_from?.format("YYYY-MM"), values.period_to?.format("YYYY-MM")].filter(Boolean).join(" ~ ") || "—",
      created_by: "当前用户",
    });
    setRfqs(prev => [...prev, created]);
    rfqForm.resetFields(); setRfqFormVisible(false);
    message.success(`询价单 ${created.rfq_number} 已创建`);
  };
  const handleAddQuote = async () => {
    const values = await quoteForm.validateFields();
    const sv = SELECTABLE_VENDORS.find(s => s.id === values.vendor);
    const created = await api.post("quotes", {
      rfq: selectedRfq?.rfq_number || "—", airport: selectedRfq?.airport || "—",
      vendor: sv?.name || values.vendor, vendor_code: sv?.code || "—",
      quote_type: values.quote_type, base_price: parseFloat(values.base_price) || 0,
      surcharge: values.surcharge || null, valid_to: values.valid_to?.format("YYYY-MM-DD") || null,
    });
    setQuotes(prev => [...prev, created]);
    quoteForm.resetFields(); setQuoteFormVisible(false);
    message.success("报价已录入");
  };

  const rfqColumns = [
    { title: "询价单号", dataIndex: "rfq_number", width: 130 }, { title: "机场", dataIndex: "airport", width: 60 },
    { title: "服务类型", dataIndex: "service_type", width: 100, render: v => COST_TYPES.find(t => t.value === v)?.label },
    { title: "周期", dataIndex: "period", width: 130 }, { title: "关联供应商", dataIndex: "vendor_count", width: 90 },
    { title: "已收报价", dataIndex: "quote_count", width: 80 }, { title: "发起人", dataIndex: "created_by", width: 70 },
    { title: "发起时间", dataIndex: "created_at", width: 100 },
    { title: "状态", dataIndex: "status", width: 90, render: v => v === "OPEN" ? <Tag color="blue">报价收集中</Tag> : <Tag>已关闭</Tag> },
    { title: "操作", width: 180, fixed: "right", render: (_, r) => (<Space size="small">{r.status === "OPEN" && <Button size="small" onClick={() => setQuoteFormVisible(true)}>录入报价</Button>}<Button size="small" type="primary" onClick={() => setSelectedRfq(r)}>比价</Button></Space>) },
  ];
  const quoteStatusRender = v => { if (v === "VALID") return <Tag color="green">有效</Tag>; if (v === "DRAFT") return <Tag>待完善</Tag>; if (v === "EXPIRED") return <Tag color="default">已失效</Tag>; };
  const compareColumns = [
    { title: "供应商", dataIndex: "vendor", width: 150 }, { title: "标记", dataIndex: "tag", width: 60, render: v => v || "—" },
    { title: "报价类型", dataIndex: "quote_type", width: 80, render: v => v === "TERM" ? "长约" : "现货" },
    { title: "基准油价", dataIndex: "base_price", width: 90 }, { title: "附加费", dataIndex: "surcharge", width: 80, render: v => v || "—" },
    { title: "有效期", dataIndex: "valid_to", width: 100, render: v => v || "（空）" },
    { title: "合同状态", dataIndex: "contract", width: 100, render: v => { if (v === "expiring") return <Tag color="orange">即将到期</Tag>; if (v === "valid") return <Tag color="green">有效</Tag>; return <Text type="secondary">无合同</Text>; } },
    { title: "履约风险", dataIndex: "risk", width: 120, render: v => v ? <Text type="danger">{v}</Text> : "无" },
    { title: "状态", dataIndex: "status", width: 100, render: quoteStatusRender },
    { title: "可选", width: 60, render: (_, r) => r.status === "VALID" ? <Checkbox /> : <Checkbox disabled /> },
  ];

  return (
    <>
      <Card size="small" title="询价单" style={{ marginBottom: 16 }} extra={<Button type="primary" icon={<PlusOutlined />} onClick={() => setRfqFormVisible(true)}>新建询价</Button>}>
        <Table size="small" columns={rfqColumns} dataSource={rfqs} rowKey="id" loading={loading} pagination={false} scroll={{ x: 1100 }} />
      </Card>
      {selectedRfq && (
        <Card size="small" title={<>比价 · {selectedRfq.rfq_number}</>} style={{ marginBottom: 16 }} extra={<Space><Button onClick={() => setSelectedRfq(null)}>收起</Button><Button onClick={() => message.info("Demo: 标记意向供应商功能仅为交互展示")}>标记意向供应商</Button><Button icon={<ExportOutlined />} onClick={() => message.info("Demo: 导出比价表功能仅为交互展示")}>导出比价表</Button></Space>}>
          <div style={{ display: "flex", gap: 16, marginBottom: 12, flexWrap: "wrap", alignItems: "center" }}>
            <Text type="secondary">机场 <Text strong>{selectedRfq.airport}</Text></Text>
            <Text type="secondary">服务 <Text strong>{COST_TYPES.find(t => t.value === selectedRfq.service_type)?.label}</Text></Text>
            <Text type="secondary">周期 <Text strong>{selectedRfq.period}</Text></Text>
            <Divider type="vertical" /><Switch size="small" defaultChecked /> <Text type="secondary" style={{ fontSize: 12 }}>仅显示有效报价</Text>
          </div>
          <Table size="small" columns={compareColumns} dataSource={quotes.filter(q => q.rfq === selectedRfq.rfq_number)} rowKey="id" pagination={false} scroll={{ x: 1100 }} />
        </Card>
      )}
      <Modal title="新建询价" open={rfqFormVisible} onCancel={() => { setRfqFormVisible(false); rfqForm.resetFields(); }} onOk={handleAddRfq} okText="保存询价" width={640}>
        <Form form={rfqForm} layout="vertical" initialValues={initialRfq ? { airport: initialRfq.airports?.[0] } : undefined}>
          <Row gutter={16}><Col span={8}><Form.Item label="目标机场" name="airport" rules={[{ required: true }]}><Input placeholder="如 HKG" /></Form.Item></Col><Col span={8}><Form.Item label="服务类型" name="service_type" rules={[{ required: true }]}><Select options={COST_TYPES} placeholder="选择品类" /></Form.Item></Col><Col span={8}><Form.Item label="报价类型" name="quote_type"><Select options={[{ value: "SPOT", label: "现货" }, { value: "TERM", label: "长约" }]} placeholder="现货/长约" /></Form.Item></Col></Row>
          <Row gutter={16}><Col span={12}><Form.Item label="周期起" name="period_from"><DatePicker style={{ width: "100%" }} /></Form.Item></Col><Col span={12}><Form.Item label="周期止" name="period_to"><DatePicker style={{ width: "100%" }} /></Form.Item></Col></Row>
          <Form.Item label="关联供应商（可多选）"><div style={{ border: "1px solid #d9d9d9", borderRadius: 6, padding: 12 }}>{SELECTABLE_VENDORS.map(sv => (<div key={sv.id} style={{ marginBottom: 4 }}><Checkbox disabled={sv.disabled} defaultChecked={!sv.disabled && sv.id !== "7"}>{sv.name}（{sv.code}）{sv.disabled && <Tag color="red" style={{ marginLeft: 8 }}>{sv.reason} · 不可选</Tag>}</Checkbox></div>))}</div><Text type="secondary" style={{ fontSize: 12, marginTop: 4, display: "block" }}>资质过期或档案不完整的供应商不可被选入询价</Text></Form.Item>
          <Form.Item label="备注" name="remarks"><TextArea rows={2} placeholder="业务要求说明…" /></Form.Item>
        </Form>
      </Modal>
      <Modal title="录入报价" open={quoteFormVisible} onCancel={() => { setQuoteFormVisible(false); quoteForm.resetFields(); }} onOk={handleAddQuote} okText="保存报价" width={560}>
        <Form form={quoteForm} layout="vertical">
          <Form.Item label="供应商" name="vendor" rules={[{ required: true }]}><Select placeholder="选择供应商" options={SELECTABLE_VENDORS.filter(v => !v.disabled).map(v => ({ value: v.id, label: `${v.name}（${v.code}）` }))} /></Form.Item>
          <Row gutter={16}><Col span={8}><Form.Item label="报价类型" name="quote_type" rules={[{ required: true }]}><Select options={[{ value: "SPOT", label: "现货" }, { value: "TERM", label: "长约" }]} /></Form.Item></Col><Col span={8}><Form.Item label="基准单价" name="base_price" rules={[{ required: true }]}><Input placeholder="如 2.08" suffix="USD" /></Form.Item></Col><Col span={8}><Form.Item label="币种" name="currency"><Select defaultValue="USD" options={[{ value: "USD" }, { value: "CNY" }, { value: "EUR" }]} /></Form.Item></Col></Row>
          <Form.Item label="附加费规则" name="surcharge"><Input placeholder="如 into-plane +0.05" /></Form.Item>
          <Row gutter={16}><Col span={12}><Form.Item label="报价生效日" name="valid_from" rules={[{ required: true }]}><DatePicker style={{ width: "100%" }} /></Form.Item></Col><Col span={12}><Form.Item label="报价失效日" name="valid_to" rules={[{ required: true }]}><DatePicker style={{ width: "100%" }} /></Form.Item></Col></Row>
          <Form.Item label="报价附件" name="attachment"><Button onClick={() => message.info("Demo: 文件上传功能仅为交互展示")}>上传报价单</Button></Form.Item>
          <Form.Item label="备注" name="remarks"><TextArea rows={2} /></Form.Item>
        </Form>
        <Alert type="info" showIcon message="缺少有效期或基准价的报价将标为「待完善」，不参与正式比价。" />
      </Modal>
    </>
  );
};

// ---- AlertsView ----
const AlertsView = () => {
  const [alerts, setAlerts] = useState([]);
  const [loading, setLoading] = useState(true);
  useEffect(() => { api.get("alerts").then(setAlerts).finally(() => setLoading(false)); }, []);
  const columns = [
    { title: "类型", dataIndex: "type", width: 120, render: v => <Tag color={alertTypeMap[v]?.color}>{alertTypeMap[v]?.text}</Tag> },
    { title: "供应商", dataIndex: "vendor", width: 150 }, { title: "对象", dataIndex: "object", width: 150 },
    { title: "到期/事件日", dataIndex: "date", width: 110, render: v => v || "—" },
    { title: "系统动作", dataIndex: "action", width: 200 },
    { title: "操作", width: 100, render: () => <Button type="link" size="small" onClick={() => message.info("Demo: 点击后将跳转到对应供应商详情页处理")}>去处理</Button> },
  ];
  return (
    <>
      <div className="stat-bar">
        <Tag color="orange">资质即将到期 2</Tag><Tag color="red">资质已过期 1</Tag>
        <Tag color="orange">合同即将到期 1</Tag><Tag color="red">合同已失效 1</Tag>
        <Tag color="purple">无对接人 1</Tag><Tag color="red">重大履约 1</Tag><Tag color="gold">档案不完整 2</Tag>
      </div>
      <Card size="small" title="预警清单"><Table size="small" columns={columns} dataSource={alerts} rowKey="id" loading={loading} pagination={false} /></Card>
    </>
  );
};

// ---- BlacklistWarningDemo ----
const BlacklistWarningDemo = () => {
  const [visible, setVisible] = useState(false);
  return (
    <>
      <Alert type="info" showIcon message="结算流程中选择黑名单/暂停供应商时，系统弹出强警告并要求填写确认原因。" style={{ marginBottom: 16 }} />
      <Button danger onClick={() => setVisible(true)}>模拟：结算中选择黑名单供应商</Button>
      <Modal open={visible} onCancel={() => setVisible(false)} title={<><ExclamationCircleOutlined style={{ color: "#f5222d", marginRight: 8 }} />风险警告</>} okText="确认选择（已知悉风险）" okButtonProps={{ danger: true }} cancelText="取消，换一家供应商" onOk={() => { message.warning("已记录确认原因到 vrm_operation_log"); setVisible(false); }} width={520}>
        <Alert type="error" showIcon message={<>您选择的供应商 <Text strong>BadSupplier Co</Text>（V2026-0005）当前合作状态为：<Tag color="red">黑名单</Tag></>} style={{ marginBottom: 16 }} />
        <Form layout="vertical"><Form.Item label="确认原因（将记入可追溯记录）" required><TextArea rows={3} placeholder="请说明为何仍需选择该供应商进行结算…" /></Form.Item></Form>
        <Text type="secondary" style={{ fontSize: 12 }}>此原因将写入操作痕迹，可追溯。</Text>
      </Modal>
    </>
  );
};

// ---- App root ----
const App = () => {
  const [activeTab, setActiveTab] = useState("list");
  const [detailVendor, setDetailVendor] = useState(null);
  const [rfqInitVendor, setRfqInitVendor] = useState(null);
  const [vendors, setVendors] = useState([]);
  const [loading, setLoading] = useState(true);
  const [resetting, setResetting] = useState(false);

  const loadVendors = useCallback(async () => {
    setLoading(true);
    try { setVendors(await api.get("vendors")); }
    catch (e) { message.error("加载失败: " + e.message); }
    finally { setLoading(false); }
  }, []);

  useEffect(() => { loadVendors(); }, [loadVendors]);

  const handleViewDetail = (vendor) => { setDetailVendor(vendor); setActiveTab("detail"); };
  const handleCreateRfq = (vendor) => { setRfqInitVendor(vendor); setActiveTab("rfq"); };
  const handleReset = async () => {
    setResetting(true);
    try {
      await api.post("reset", {});
      await loadVendors();
      setDetailVendor(null); setActiveTab("list");
      message.success("数据已重置为初始状态");
    } catch (e) { message.error(e.message); }
    finally { setResetting(false); }
  };

  const topTabs = [
    { key: "list", label: <><SolutionOutlined /> 供应商列表</> },
    { key: "detail", label: <><UserOutlined /> 供应商详情</>, disabled: !detailVendor },
    { key: "rfq", label: <><SearchOutlined /> 询价与比价</> },
    { key: "alerts", label: <><WarningOutlined /> 预警中心</> },
    { key: "blacklist", label: <><SafetyOutlined /> 黑名单警告</> },
  ];

  return (
    <div>
      <div className="page-header">
        <h2>供应商 CRM — 交互原型</h2>
        <Space>
          <Button size="small" icon={<ReloadOutlined />} onClick={loadVendors} loading={loading}>刷新</Button>
          <Button size="small" danger onClick={handleReset} loading={resetting}>重置全部数据</Button>
        </Space>
      </div>
      <Tabs activeKey={activeTab} onChange={(key) => { setActiveTab(key); if (key !== "rfq") setRfqInitVendor(null); }} items={topTabs} />
      {activeTab === "list" && <VendorListView vendors={vendors} loading={loading} onViewDetail={handleViewDetail} onAddVendor={(v) => setVendors(prev => [...prev, v])} />}
      {activeTab === "detail" && <VendorDetailView vendor={detailVendor} onBack={() => setActiveTab("list")} onCreateRfq={handleCreateRfq} />}
      {activeTab === "rfq" && <RfqCompareView initialRfq={rfqInitVendor} />}
      {activeTab === "alerts" && <AlertsView />}
      {activeTab === "blacklist" && <BlacklistWarningDemo />}
    </div>
  );
};

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
