package com.nursinghome.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import com.nursinghome.common.ApiException;
import com.nursinghome.common.ApiResponse;
import com.nursinghome.dto.FeedbackRequest;
import com.nursinghome.dto.PayRequest;
import com.nursinghome.entity.*;
import com.nursinghome.mapper.*;
import com.nursinghome.service.BillService;
import com.nursinghome.service.FamilyService;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/family")
@SaCheckRole("FAMILY")
public class FamilyController {
    private final FamilyService familyService;
    private final ElderMapper elderMapper;
    private final CareRecordMapper careRecordMapper;
    private final HealthRecordMapper healthRecordMapper;
    private final BillService billService;
    private final BillMapper billMapper;
    private final NoticeMapper noticeMapper;
    private final FeedbackMapper feedbackMapper;

    public FamilyController(FamilyService familyService,
                            ElderMapper elderMapper,
                            CareRecordMapper careRecordMapper,
                            HealthRecordMapper healthRecordMapper,
                            BillService billService,
                            BillMapper billMapper,
                            NoticeMapper noticeMapper,
                            FeedbackMapper feedbackMapper) {
        this.familyService = familyService;
        this.elderMapper = elderMapper;
        this.careRecordMapper = careRecordMapper;
        this.healthRecordMapper = healthRecordMapper;
        this.billService = billService;
        this.billMapper = billMapper;
        this.noticeMapper = noticeMapper;
        this.feedbackMapper = feedbackMapper;
    }

    @GetMapping("/elders")
    public ApiResponse<List<Elder>> listElders() {
        Long familyId = Long.valueOf(StpUtil.getLoginId().toString());
        List<FamilyElder> relations = familyService.listRelations(familyId);
        List<Elder> elders = new ArrayList<>();
        for (FamilyElder relation : relations) {
            Elder elder = elderMapper.findById(relation.getElderId());
            if (elder != null) {
                elders.add(elder);
            }
        }
        return ApiResponse.success(elders);
    }

    @GetMapping("/care-records")
    public ApiResponse<List<CareRecord>> listCare(@RequestParam Long elderId) {
        Long familyId = Long.valueOf(StpUtil.getLoginId().toString());
        boolean allowed = false;
        for (FamilyElder relation : familyService.listRelations(familyId)) {
            if (relation.getElderId().equals(elderId)) {
                allowed = true;
                break;
            }
        }
        if (!allowed) {
            throw new ApiException("无权访问该亲属");
        }
        return ApiResponse.success(careRecordMapper.listByElderId(elderId));
    }

    @GetMapping("/health-records")
    public ApiResponse<List<HealthRecord>> listHealth(@RequestParam Long elderId) {
        Long familyId = Long.valueOf(StpUtil.getLoginId().toString());
        boolean allowed = false;
        for (FamilyElder relation : familyService.listRelations(familyId)) {
            if (relation.getElderId().equals(elderId)) {
                allowed = true;
                break;
            }
        }
        if (!allowed) {
            throw new ApiException("无权访问该亲属");
        }
        return ApiResponse.success(healthRecordMapper.listByElderId(elderId));
    }

    @GetMapping("/bills")
    public ApiResponse<List<Bill>> listBills(@RequestParam Long elderId) {
        Long familyId = Long.valueOf(StpUtil.getLoginId().toString());
        boolean allowed = false;
        for (FamilyElder relation : familyService.listRelations(familyId)) {
            if (relation.getElderId().equals(elderId)) {
                allowed = true;
                break;
            }
        }
        if (!allowed) {
            throw new ApiException("无权访问该亲属");
        }
        return ApiResponse.success(billService.listByElderId(elderId));
    }

    @PostMapping("/bills/{id}/pay")
    public ApiResponse<Void> pay(@PathVariable Long id, @RequestBody PayRequest request) {
        Long familyId = Long.valueOf(StpUtil.getLoginId().toString());
        Bill bill = billMapper.findById(id);
        if (bill == null) {
            throw new ApiException("账单不存在");
        }
        boolean allowed = false;
        for (FamilyElder relation : familyService.listRelations(familyId)) {
            if (relation.getElderId().equals(bill.getElderId())) {
                allowed = true;
                break;
            }
        }
        if (!allowed) {
            throw new ApiException("无权访问该账单");
        }
        if ("PAID".equals(bill.getStatus())) {
            throw new ApiException("账单已支付");
        }
        BigDecimal amount = bill.getTotal() == null ? BigDecimal.ZERO : bill.getTotal();
        billService.payBill(id, familyId, request.getMethod(), amount);
        return ApiResponse.success();
    }

    @PostMapping("/feedback")
    public ApiResponse<Feedback> createFeedback(@RequestBody FeedbackRequest request) {
        Feedback feedback = new Feedback();
        feedback.setFamilyId(Long.valueOf(StpUtil.getLoginId().toString()));
        feedback.setElderId(request.getElderId());
        feedback.setType(request.getType());
        feedback.setContent(request.getContent());
        feedback.setRating(request.getRating());
        feedback.setStatus("NEW");
        feedback.setCreatedAt(LocalDateTime.now());
        feedbackMapper.insert(feedback);
        return ApiResponse.success(feedback);
    }

    @GetMapping("/feedback")
    public ApiResponse<List<Feedback>> listFeedback() {
        Long familyId = Long.valueOf(StpUtil.getLoginId().toString());
        return ApiResponse.success(feedbackMapper.listByFamilyId(familyId));
    }

    @GetMapping("/notices")
    public ApiResponse<List<Notice>> listNotices() {
        Long familyId = Long.valueOf(StpUtil.getLoginId().toString());
        return ApiResponse.success(noticeMapper.listByTarget("FAMILY", familyId));
    }
}
