<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * 创建智慧社区核心表
     *
     * 依据《物业管理条例》和《智慧社区建设指南》，
     * 智慧社区需包含居民信息、房屋管理、报修服务、投诉建议、
     * 社区活动、邻里互助、物业缴费、公告通知等模块。
     */
    public function up(): void
    {
        // 居民信息表
        Schema::create('residents', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->nullable()->constrained('users')->nullOnDelete()->comment('关联用户');
            $table->string('name', 50)->comment('居民姓名');
            $table->text('id_card')->nullable()->comment('身份证号（加密存储）');
            $table->text('phone')->nullable()->comment('手机号（加密存储）');
            $table->string('gender', 10)->nullable()->comment('性别');
            $table->date('birthday')->nullable()->comment('出生日期');
            $table->string('address', 255)->nullable()->comment('居住地址');
            $table->json('tags')->nullable()->comment('标签');
            $table->json('special_groups')->nullable()->comment('特殊群体标识：elderly/disabled/veteran');
            $table->boolean('is_living')->default(true)->comment('是否常住');
            $table->timestamps();
            $table->softDeletes();
        });

        // 房屋信息表
        Schema::create('houses', function (Blueprint $table) {
            $table->id();
            $table->string('building', 50)->comment('楼栋');
            $table->string('unit', 20)->nullable()->comment('单元');
            $table->string('room', 20)->comment('房号');
            $table->decimal('area', 10, 2)->nullable()->comment('面积（平方米）');
            $table->string('type', 30)->nullable()->comment('户型');
            $table->string('status', 20)->default('occupied')->comment('状态：occupied/vacant/decorating');
            $table->timestamps();
            $table->softDeletes();
            $table->unique(['building', 'unit', 'room'], 'uk_house');
        });

        // 居民-房屋关联表
        Schema::create('resident_house', function (Blueprint $table) {
            $table->id();
            $table->foreignId('resident_id')->constrained('residents')->cascadeOnDelete()->comment('居民');
            $table->foreignId('house_id')->constrained('houses')->cascadeOnDelete()->comment('房屋');
            $table->string('relation', 30)->default('owner')->comment('关系：owner/tenant/family');
            $table->boolean('is_owner')->default(false)->comment('是否户主');
            $table->timestamps();
            $table->unique(['resident_id', 'house_id']);
        });

        // 报修工单表
        Schema::create('repairs', function (Blueprint $table) {
            $table->id();
            $table->foreignId('resident_id')->constrained('residents')->cascadeOnDelete()->comment('报修居民');
            $table->foreignId('house_id')->constrained('houses')->cascadeOnDelete()->comment('报修房屋');
            $table->string('category', 50)->comment('报修类别：water/electric/plumbing/structural/other');
            $table->text('description')->comment('报修描述');
            $table->string('status', 20)->default('pending')->comment('状态：pending/assigned/processing/completed/cancelled');
            $table->json('images')->nullable()->comment('报修图片');
            $table->foreignId('assigned_to')->nullable()->constrained('users')->nullOnDelete()->comment('指派维修人员');
            $table->timestamp('completed_at')->nullable()->comment('完成时间');
            $table->timestamps();
            $table->softDeletes();
        });

        // 报修日志表
        Schema::create('repair_logs', function (Blueprint $table) {
            $table->id();
            $table->foreignId('repair_id')->constrained('repairs')->cascadeOnDelete()->comment('报修工单');
            $table->string('action', 50)->comment('操作类型');
            $table->text('content')->nullable()->comment('操作内容');
            $table->foreignId('operator_id')->nullable()->constrained('users')->nullOnDelete()->comment('操作人');
            $table->timestamps();
        });

        // 投诉建议表
        Schema::create('complaints', function (Blueprint $table) {
            $table->id();
            $table->foreignId('resident_id')->constrained('residents')->cascadeOnDelete()->comment('投诉居民');
            $table->string('type', 50)->comment('投诉类型：noise/parking/pet/hygiene/other');
            $table->string('title', 200)->comment('投诉标题');
            $table->text('content')->comment('投诉内容');
            $table->string('status', 20)->default('pending')->comment('状态：pending/processing/resolved/closed');
            $table->json('images')->nullable()->comment('投诉图片');
            $table->boolean('is_anonymous')->default(false)->comment('是否匿名投诉');
            $table->timestamps();
            $table->softDeletes();
        });

        // 投诉回复表
        Schema::create('complaint_replies', function (Blueprint $table) {
            $table->id();
            $table->foreignId('complaint_id')->constrained('complaints')->cascadeOnDelete()->comment('投诉');
            $table->text('content')->comment('回复内容');
            $table->foreignId('replier_id')->nullable()->constrained('users')->nullOnDelete()->comment('回复人');
            $table->timestamps();
        });

        // 社区活动表
        Schema::create('activities', function (Blueprint $table) {
            $table->id();
            $table->string('title', 200)->comment('活动标题');
            $table->text('description')->nullable()->comment('活动描述');
            $table->string('location', 200)->comment('活动地点');
            $table->datetime('start_time')->comment('开始时间');
            $table->datetime('end_time')->comment('结束时间');
            $table->integer('max_participants')->nullable()->comment('最大参与人数');
            $table->string('status', 20)->default('draft')->comment('状态：draft/published/ongoing/ended/cancelled');
            $table->string('cover_image', 255)->nullable()->comment('封面图');
            $table->foreignId('organizer_id')->nullable()->constrained('users')->nullOnDelete()->comment('组织者');
            $table->timestamps();
            $table->softDeletes();
        });

        // 活动报名表
        Schema::create('activity_sign_ups', function (Blueprint $table) {
            $table->id();
            $table->foreignId('activity_id')->constrained('activities')->cascadeOnDelete()->comment('活动');
            $table->foreignId('resident_id')->constrained('residents')->cascadeOnDelete()->comment('报名居民');
            $table->string('status', 20)->default('registered')->comment('状态：registered/cancelled');
            $table->text('remark')->nullable()->comment('备注');
            $table->timestamps();
            $table->unique(['activity_id', 'resident_id']);
        });

        // 活动签到表
        Schema::create('activity_sign_ins', function (Blueprint $table) {
            $table->id();
            $table->foreignId('activity_id')->constrained('activities')->cascadeOnDelete()->comment('活动');
            $table->foreignId('resident_id')->constrained('residents')->cascadeOnDelete()->comment('签到居民');
            $table->timestamp('signed_at')->comment('签到时间');
            $table->string('method', 20)->default('qrcode')->comment('签到方式：qrcode/location/manual');
            $table->timestamps();
            $table->unique(['activity_id', 'resident_id']);
        });

        // 邻里互助表
        Schema::create('helps', function (Blueprint $table) {
            $table->id();
            $table->foreignId('resident_id')->constrained('residents')->cascadeOnDelete()->comment('求助居民');
            $table->string('category', 50)->comment('求助类别：borrow/look_after/escort/shopping/other');
            $table->string('title', 200)->comment('求助标题');
            $table->text('description')->comment('求助描述');
            $table->string('status', 20)->default('open')->comment('状态：open/taken/completed/cancelled');
            $table->foreignId('helper_id')->nullable()->constrained('residents')->nullOnDelete()->comment('应助居民');
            $table->timestamp('expires_at')->nullable()->comment('过期时间');
            $table->timestamps();
            $table->softDeletes();
        });

        // 互助消息表
        Schema::create('help_messages', function (Blueprint $table) {
            $table->id();
            $table->foreignId('help_id')->constrained('helps')->cascadeOnDelete()->comment('互助');
            $table->foreignId('sender_id')->constrained('residents')->cascadeOnDelete()->comment('发送人');
            $table->text('content')->comment('消息内容');
            $table->timestamps();
        });

        // 物业缴费表
        Schema::create('payments', function (Blueprint $table) {
            $table->id();
            $table->foreignId('resident_id')->constrained('residents')->cascadeOnDelete()->comment('缴费居民');
            $table->foreignId('house_id')->constrained('houses')->cascadeOnDelete()->comment('缴费房屋');
            $table->string('type', 50)->comment('缴费类型：property/water/electricity/gas/parking');
            $table->decimal('amount', 10, 2)->comment('缴费金额');
            $table->string('period', 20)->comment('缴费周期：202401');
            $table->string('status', 20)->default('unpaid')->comment('状态：unpaid/paid/overdue/cancelled');
            $table->date('due_date')->nullable()->comment('截止日期');
            $table->timestamp('paid_at')->nullable()->comment('缴费时间');
            $table->string('payment_method', 30)->nullable()->comment('支付方式：wechat/alipay/cash/transfer');
            $table->string('transaction_id', 100)->nullable()->comment('交易流水号');
            $table->timestamps();
            $table->softDeletes();
        });

        // 缴费记录表
        Schema::create('payment_records', function (Blueprint $table) {
            $table->id();
            $table->foreignId('payment_id')->constrained('payments')->cascadeOnDelete()->comment('缴费');
            $table->string('action', 50)->comment('操作类型');
            $table->text('content')->nullable()->comment('操作内容');
            $table->foreignId('operator_id')->nullable()->constrained('users')->nullOnDelete()->comment('操作人');
            $table->timestamps();
        });

        // 公告通知表
        Schema::create('notices', function (Blueprint $table) {
            $table->id();
            $table->string('title', 200)->comment('公告标题');
            $table->text('content')->comment('公告内容');
            $table->string('type', 30)->default('notice')->comment('类型：notice/emergency/activity/maintenance');
            $table->string('status', 20)->default('published')->comment('状态：draft/published/withdrawn');
            $table->boolean('is_top')->default(false)->comment('是否置顶');
            $table->foreignId('publisher_id')->nullable()->constrained('users')->nullOnDelete()->comment('发布人');
            $table->timestamp('published_at')->nullable()->comment('发布时间');
            $table->timestamps();
            $table->softDeletes();
        });

        // 公告已读日志表
        Schema::create('notice_read_logs', function (Blueprint $table) {
            $table->id();
            $table->foreignId('notice_id')->constrained('notices')->cascadeOnDelete()->comment('公告');
            $table->foreignId('resident_id')->constrained('residents')->cascadeOnDelete()->comment('居民');
            $table->timestamp('read_at')->comment('阅读时间');
            $table->timestamps();
            $table->unique(['notice_id', 'resident_id']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('notice_read_logs');
        Schema::dropIfExists('notices');
        Schema::dropIfExists('payment_records');
        Schema::dropIfExists('payments');
        Schema::dropIfExists('help_messages');
        Schema::dropIfExists('helps');
        Schema::dropIfExists('activity_sign_ins');
        Schema::dropIfExists('activity_sign_ups');
        Schema::dropIfExists('activities');
        Schema::dropIfExists('complaint_replies');
        Schema::dropIfExists('complaints');
        Schema::dropIfExists('repair_logs');
        Schema::dropIfExists('repairs');
        Schema::dropIfExists('resident_house');
        Schema::dropIfExists('houses');
        Schema::dropIfExists('residents');
    }
};