import 'package:fis_jsonrpc/services/diagnosis.m.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:vitalapp/architecture/utils/prompt_box.dart';
import 'package:vitalapp/components/appbar.dart';
import 'package:vitalapp/components/dialog_table.dart';
import 'package:vitalapp/consts/styles.dart';
import 'package:vitalapp/global.dart';
import 'package:vitalapp/managers/interfaces/models/diagnosis_aggregation_record_model.dart';
import 'package:vitalapp/pages/medical/records/controller.dart';
import 'package:vitalapp/pages/patient/list/widgets/status.dart';
import 'package:vitalapp/pages/widgets/record_common_item.dart';

class MedicalRecordsPage extends GetView<MedicalRecordsController> {
  const MedicalRecordsPage({super.key});

  @override
  Widget build(BuildContext context) {
    return GetBuilder(
      init: MedicalRecordsController(),
      id: "MedicalRecords",
      builder: (_) {
        return Scaffold(
          backgroundColor: const Color.fromRGBO(238, 238, 238, 1),
          appBar: VAppBar(
            titleWidget: const Text('健康检测记录'),
          ),
          body: Stack(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  _buildDiagram(),
                  _buildListView(),
                ],
              )
            ],
          ),
        );
      },
    );
  }

  Widget _buildDiagram() {
    return Expanded(
      flex: 1,
      child: Padding(
        padding: const EdgeInsets.all(16.0).copyWith(right: 0),
        child: Container(
          // color: Colors.white,
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: Colors.white,
            border: Border.all(
              color: Colors.white,
            ),
            borderRadius: GlobalStyles.borderRadius,
          ),
          child: Image.asset(
            'assets/images/exam/normalMeasurementChart.png',
            height: double.infinity,
            fit: BoxFit.fitWidth,
          ),
        ),
      ),
    );
  }

  Widget _buildListView() {
    final scrollController = ScrollController();
    scrollController.addListener(
      () {
        // 如果滑动到底部
        try {
          if (scrollController.position.atEdge) {
            if (scrollController.position.pixels != 0) {
              if (controller.state.hasNextPage) {
                controller.loadNextPageList();
              }
            }
          }
        } catch (e) {
          // logger.e("listViewScrollController exception:", e);
        }
      },
    );
    return Expanded(
      flex: 2,
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: RefreshIndicator(
            child: Obx(() {
              final children = <Widget>[];
              for (var element in controller.state.dataList) {
                children.add(_MedicalRecordCard(
                  dto: element,
                ));
              }
              return controller.state.dataList.isEmpty
                  ? Container(
                      margin: const EdgeInsets.only(top: 80),
                      child: Column(
                        children: [
                          Center(
                            child: Image.asset(
                              "assets/images/no_data.png",
                              width: 300,
                              height: 300,
                              fit: BoxFit.cover,
                            ),
                          ),
                          const Text(
                            "暂无数据，先看看别的吧",
                            style: TextStyle(fontSize: 18),
                          ),
                        ],
                      ),
                    )
                  : Scrollbar(
                      trackVisibility: true,
                      controller: scrollController,
                      child: GridView(
                        shrinkWrap: true,
                        controller: scrollController,
                        gridDelegate:
                            const SliverGridDelegateWithFixedCrossAxisCount(
                          crossAxisCount: 1,
                          mainAxisSpacing: 16,
                          crossAxisSpacing: 20,
                          childAspectRatio: 1080 / 180,
                        ),
                        children: children,
                      ),
                    );
            }),
            onRefresh: () async {}),
      ),
    );
  }
}

class _MedicalRecordCard extends GetView<MedicalRecordsController> {
  final DiagnosisAggregationRecordModel dto;
  const _MedicalRecordCard({required this.dto});

  @override
  Widget build(BuildContext context) {
    final body = Stack(
      children: [
        Row(
          children: [
            Expanded(
              flex: 10,
              child: Container(
                padding: const EdgeInsets.symmetric(
                  horizontal: 30,
                  vertical: 12,
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const SizedBox(
                      height: 8,
                    ),
                    Wrap(
                      alignment: WrapAlignment.start,
                      spacing: 20,
                      runSpacing: 8,
                      children: [
                        RecordCommonItem(
                          itemName: '姓名',
                          itemValue: dto.patientName ?? '',
                          fontSize: 18,
                        ),
                      ],
                    ),
                    const SizedBox(
                      height: 20,
                    ),
                    Wrap(
                      alignment: WrapAlignment.start,
                      spacing: 20,
                      runSpacing: 8,
                      children: [
                        SizedBox(
                          width: 250,
                          child: RecordCommonItem(
                            itemName: '检查医生',
                            itemValue: dto.doctorName ?? '',
                            fontSize: 18,
                          ),
                        ),
                        RecordCommonItem(
                          itemName: '诊断时间',
                          itemValue: DateFormat("yyyy-MM-dd HH:mm:ss")
                              .format(dto.diagnosisTime!.toLocal()),
                          fontSize: 18,
                        ),
                      ],
                    )
                  ],
                ),
              ),
            ),
            Expanded(
                flex: 1,
                child: Icon(
                  Icons.keyboard_arrow_right,
                  size: 64,
                  color: Colors.grey.shade400,
                ))
          ],
        ),
        Positioned(
          top: 16,
          right: 0,
          child: _diagnosisSignStatusTag(
            dto: dto,
          ),
        ),
      ],
    );
    return Material(
      borderRadius: GlobalStyles.borderRadius,
      child: Ink(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: GlobalStyles.borderRadius,
        ),
        child: InkWell(
          borderRadius: GlobalStyles.borderRadius,
          onTap: () async {
            var result = await controller.getTableData(dto);
            await VDialogTable(
              isExistLocalData: dto.isExistLocalData,
              title: '数据展示',
              columnNames: const ['序号', '检测项目', '检测结果', '单位'],
              tableData: result,
              diagnosisTime: DateFormat("yyyy-MM-dd HH:mm:ss")
                  .format(dto.diagnosisTime!.toLocal()),
            ).show();
          },
          child: body,
        ),
      ),
    );
  }
}

// ignore: camel_case_types
class _diagnosisSignStatusTag extends StatelessWidget {
  final DiagnosisAggregationRecordModel dto;

  const _diagnosisSignStatusTag({required this.dto});
  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.centerRight,
      width: 120,
      child: StatusLabel(
        title: dto.isExistLocalData! ? "未上传" : "已上传",
        color: dto.isExistLocalData! ? Colors.red : Colors.green,
      ),
    );
  }
}
