-- 1. 创建序列
CREATE SEQUENCE doc_record_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;

-- 2. 创建文书记录表
CREATE TABLE "doc_record" (
  -- 主键ID
  "id" int8 NOT NULL DEFAULT nextval('doc_record_id_seq'::regclass),
  
  -- 实体类字段
  "definition_id" int8 NOT NULL,
  "definition_bus_no" varchar(100) COLLATE "pg_catalog"."default" NOT NULL,
  "content_json" text COLLATE "pg_catalog"."default" NOT NULL,
  "status_enum" int4 NOT NULL DEFAULT 0,
  "organization_id" int8 NOT NULL,
  "encounter_id" int8 NOT NULL,
  "patient_id" int8 NOT NULL,
  "record_time" timestamptz(6) NOT NULL,
  
  -- 继承的审计字段
  "tenant_id" int8 NOT NULL,
  "delete_flag" char(1) COLLATE "pg_catalog"."default" NOT NULL DEFAULT '0',
  "create_by" varchar(32) COLLATE "pg_catalog"."default" NOT NULL DEFAULT '',
  "create_time" timestamptz(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "update_by" varchar(32) COLLATE "pg_catalog"."default",
  "update_time" timestamptz(6),
  
  -- 主键约束
  CONSTRAINT "doc_record_pkey" PRIMARY KEY ("id")
);

-- 3. 设置表所有者
ALTER TABLE "doc_record" OWNER TO "postgres";

-- 4. 表和字段注释
COMMENT ON TABLE "doc_record" IS '文书记录表';

COMMENT ON COLUMN "doc_record"."id" IS '主键ID';
COMMENT ON COLUMN "doc_record"."definition_id" IS '定义ID';
COMMENT ON COLUMN "doc_record"."definition_bus_no" IS '业务编码';
COMMENT ON COLUMN "doc_record"."content_json" IS '文档内容(JSON格式)';
COMMENT ON COLUMN "doc_record"."status_enum" IS '状态枚举: 0-草稿/暂存,1-提交,2-归档,3-修改';
COMMENT ON COLUMN "doc_record"."organization_id" IS '科室ID';
COMMENT ON COLUMN "doc_record"."encounter_id" IS '就诊记录ID';
COMMENT ON COLUMN "doc_record"."patient_id" IS '病人ID';
COMMENT ON COLUMN "doc_record"."record_time" IS '记录时间';
COMMENT ON COLUMN "doc_record"."tenant_id" IS '租户ID';
COMMENT ON COLUMN "doc_record"."delete_flag" IS '删除标志: 0-未删除,1-已删除';
COMMENT ON COLUMN "doc_record"."create_by" IS '创建人';
COMMENT ON COLUMN "doc_record"."create_time" IS '创建时间';
COMMENT ON COLUMN "doc_record"."update_by" IS '更新人';
COMMENT ON COLUMN "doc_record"."update_time" IS '更新时间';

-- 5. 索引设计
-- 按定义ID查询（高频场景）
CREATE INDEX "idx_doc_record_definition" ON "doc_record" ("definition_id");
-- 按病人ID查询（高频场景）
CREATE INDEX "idx_doc_record_patient" ON "doc_record" ("patient_id");
-- 按就诊ID查询（高频场景）
CREATE INDEX "idx_doc_record_encounter" ON "doc_record" ("encounter_id");
-- 按科室ID查询
CREATE INDEX "idx_doc_record_orgnization" ON "doc_record" ("orgnization_id");
-- 按记录时间范围查询
CREATE INDEX "idx_doc_record_time" ON "doc_record" ("record_time");
-- 按状态查询
CREATE INDEX "idx_doc_record_status" ON "doc_record" ("status_enum");



-- 向迁移历史表插入记录
INSERT INTO __MigrationsHistory (MigrationId, ProductVersion)
VALUES ('202508221059 doc_record', '1.0.0');