import 'dart:convert';

import 'package:fis_jsonrpc/rpc.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:vnoteapp/components/alert_dialog.dart';
import 'package:vnoteapp/components/appbar.dart';
import 'package:vnoteapp/components/cell.dart';
import 'package:vnoteapp/components/dialog_date.dart';
import 'package:vnoteapp/components/panel.dart';
import 'controller.dart';

class ServicePackageContractPage
    extends GetView<ServicePackageContractController> {
  const ServicePackageContractPage({super.key});
  static const double labelSize = 20;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color.fromRGBO(238, 238, 238, 1),
      appBar: VAppBar(
        titleWidget: const Text(
          "签约",
          style: TextStyle(fontSize: 24),
        ),
        actions: [
          TextButton(
            onPressed: () {
              Get.toNamed(
                "/contract/contract_template",
                parameters: {
                  "templateCode": "53C3323BB6444A109B2369703EFFDFF9",
                  "patientInfo": json.encode(controller.patient.toJson()),
                  "servicePackageCodes":
                      controller.state.selectedServicePackageCode,
                  "servicePackageNames":
                      controller.state.selectedServicePackageName,
                },
              );
            },
            child: const Text(
              '下一步',
              style: TextStyle(color: Colors.white, fontSize: 20),
            ),
          ),
          const SizedBox(
            width: 15,
          ),
        ],
      ),
      endDrawer: _servicePackageDrawer(context),
      body: Builder(builder: (context) {
        return Padding(
          padding: const EdgeInsets.symmetric(horizontal: 200, vertical: 8),
          child: ListView(
            children: [
              Column(
                children: [
                  _buildPhotoVPanel(),
                  const SizedBox(height: 16),
                  _buildContractDoctorVPanel(),
                  const SizedBox(height: 16),
                  _buildPatientVPanel(),
                  const SizedBox(height: 16),
                  _buildServicePackageVPanel(context),
                ],
              ),
            ],
          ),
        );
      }),
    );
  }

  Drawer _servicePackageDrawer(BuildContext context) {
    const double titleSize = 20;
    const double labelSize = 18;
    Widget buildAlertDialog(ServicePackDTO servicePackDTO) {
      return VAlertDialog(
        title: '${servicePackDTO.name}详情',
        content: Container(
            height: 200,
            alignment: Alignment.topLeft,
            padding: const EdgeInsets.symmetric(horizontal: 15),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                LayoutBuilder(
                  builder: (BuildContext context, BoxConstraints constraints) {
                    return ConstrainedBox(
                      constraints: const BoxConstraints(
                        maxHeight: 100,
                      ),
                      child: Scrollbar(
                        thumbVisibility: true,
                        child: ListView(
                          shrinkWrap: true,
                          children: [
                            Text(
                              servicePackDTO.content ?? "",
                              style: const TextStyle(fontSize: 16),
                            ),
                          ],
                        ),
                      ),
                    );
                  },
                ),
                const SizedBox(
                  height: 5,
                ),
                const Text(
                  '服务项目',
                  style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18),
                ),
                const SizedBox(
                  height: 5,
                ),
                Expanded(
                  child: Text(
                    controller.getServiceItemsName(
                      servicePackDTO.items ?? [],
                    ),
                  ),
                )
              ],
            )),
        // actions: <Widget>[
        //   TextButton(
        //     child: const Text('取消'),
        //     onPressed: () {
        //       Navigator.of(context).pop(); // 关闭对话框
        //     },
        //   ),
        //   TextButton(
        //     child: const Text('确定'),
        //     onPressed: () {
        //       // 在这里处理确定按钮的逻辑
        //       Navigator.of(context).pop(); // 关闭对话框
        //     },
        //   ),
        // ],
      );
    }

    Widget buildItem(ServicePackDTO servicePackDTO) {
      return InkWell(
        onTap: () {
          controller.changeServicePackage(servicePackDTO);
        },
        child: Container(
          margin: const EdgeInsets.symmetric(
            vertical: 10,
            horizontal: 50,
          ),
          padding: const EdgeInsets.symmetric(horizontal: 30, vertical: 15),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: const BorderRadius.all(
              Radius.circular(
                8,
              ),
            ),
            border: Border.all(
              color: controller.state.selectedServicePackage
                      .contains(servicePackDTO)
                  ? const Color.fromRGBO(34, 164, 211, 1)
                  : Colors.transparent,
              width: 2,
            ),
          ),
          child: Row(
            children: [
              Container(
                padding: const EdgeInsets.only(right: 20),
                child: Obx(
                  () => Icon(
                    Icons.check_circle_outline,
                    size: 35,
                    color: controller.state.selectedServicePackage
                            .contains(servicePackDTO)
                        ? const Color.fromRGBO(34, 164, 211, 1)
                        : Colors.grey.shade500,
                  ),
                ),
              ),
              Expanded(
                child: Column(
                  children: [
                    Row(
                      children: [
                        Expanded(
                          child: Text(
                            servicePackDTO.name ?? '',
                            style: const TextStyle(
                              fontSize: 25,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                        Expanded(
                          child: Row(
                            children: [
                              const Text(
                                '服务人群：',
                                style: TextStyle(fontSize: titleSize),
                              ),
                              Text(
                                controller.setNormalLabels(
                                  servicePackDTO.labels ?? [],
                                ),
                                style: const TextStyle(fontSize: labelSize),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(
                      height: 10,
                    ),
                    Row(
                      mainAxisSize: MainAxisSize.max,
                      children: [
                        Expanded(
                          child: Row(
                            mainAxisSize: MainAxisSize.max,
                            children: [
                              const Text(
                                '服务包介绍：',
                                style: TextStyle(fontSize: titleSize),
                              ),
                              Expanded(
                                child: Container(
                                  alignment: Alignment.centerLeft,
                                  height: 50,
                                  child: Text(
                                    servicePackDTO.content ?? '',
                                    overflow: TextOverflow.ellipsis,
                                    maxLines: 2,
                                    style: const TextStyle(fontSize: labelSize),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              Container(
                padding: const EdgeInsets.only(left: 20),
                child: TextButton(
                  child: const Text(
                    '查看',
                    style: TextStyle(fontSize: 18),
                  ),
                  onPressed: () async {
                    await Get.toNamed(
                      '/contract/package_info',
                      parameters: {
                        "servicePack": json.encode(servicePackDTO.toJson()),
                      },
                    );
                    // showDialog(
                    //   context: context,
                    //   builder: (BuildContext context) {
                    //     return buildAlertDialog(servicePackDTO);
                    //   },
                    // );
                  },
                ),
              ),
            ],
          ),
        ),
      );
    }

    Widget buildCancelButton() {
      return TextButton(
        onPressed: () {
          Get.back();
        },
        child: const Text(
          '取消',
          style: TextStyle(fontSize: 25),
        ),
      );
    }

    Widget buildConfirmButton() {
      return TextButton(
        onPressed: () {},
        child: const Text(
          '确定',
          style: TextStyle(fontSize: 25),
        ),
      );
    }

    Widget buildHeader() {
      return Container(
        decoration: const BoxDecoration(
          color: Colors.white,
        ),
        height: 90,
        padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            buildCancelButton(),
            buildConfirmButton(),
          ],
        ),
      );
    }

    Widget buildServicePackageList() {
      return Obx(
        () => Expanded(
          child: controller.state.servicePackageItems.isEmpty
              ? const Center(
                  child: Text('暂无数据'),
                )
              : ListView(
                  children: controller.state.servicePackageItems
                      .map((ServicePackDTO e) => buildItem(e))
                      .toList(),
                ),
        ),
      );
    }

    return Drawer(
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadiusDirectional.horizontal(
          end: Radius.circular(0),
        ),
      ),
      width: MediaQuery.of(context).size.width * 0.7,
      child: Container(
        color: Colors.grey.shade300,
        child: Column(
          mainAxisSize: MainAxisSize.max,
          children: [
            // buildHeader(),
            const SizedBox(
              height: 30,
            ),
            buildServicePackageList(),
            const SizedBox(
              height: 10,
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildPhotoVPanel() {
    return VPanel(
      child: VListFormCellGroup(
        children: [
          VListFormCell(
            label: '拍照',
            height: 70,
            contentWidget: const Center(
              child: Icon(
                Icons.supervised_user_circle_outlined,
                size: 70,
              ),
            ),
            onTap: () {
              print('拍照拍照');
            },
          ),
        ],
      ),
    );
  }

  Widget _buildContractDoctorVPanel() {
    return VPanel(
      child: VListFormCellGroup(
        children: [
          Obx(
            () => VListFormCell(
              label: '服务日期',
              content: DateFormat('yyyy-MM-dd')
                  .format(controller.state.serviceStartDate),
              onTap: () async {
                final result = await VDialogDate(
                  title: '服务日期',
                  initialValue: controller.state.serviceStartDate,
                ).show();
                controller.state.serviceStartDate = result;
              },
            ),
          ),
          const VListFormCell(
            label: '签约医生',
            content: '李四',
          ),
          const VListFormCell(
            label: '医生电话',
            content: '18712341234',
          ),
        ],
      ),
    );
  }

  Widget _buildPatientVPanel() {
    return Stack(
      children: [
        VPanel(
            child: Obx(
          () => VListFormCellGroup(
            children: [
              VListFormCell(
                label: '姓名',
                content: controller.state.name,
              ),
              VListFormCell(
                label: '联系电话',
                content: controller.state.phone,
              ),
              if (controller.state.isExpendPatient) ...[
                const VListFormCell(
                  label: '身份证号码',
                  content: '5130221999099987',
                ),
                const VListFormCell(
                  label: '民族',
                  content: '汉族',
                ),
                VListFormCell(
                  label: '性别',
                  content: controller.state.genderDesc,
                ),
                const VListFormCell(
                  label: '出生日期',
                  content: '张三',
                ),
              ]
            ],
          ),
        )),
        Positioned(
          right: 0,
          top: 0,
          child: IconButton(
            onPressed: () {
              controller.state.isExpendPatient =
                  !controller.state.isExpendPatient;
            },
            icon: Obx(
              () => Icon(
                controller.state.isExpendPatient
                    ? Icons.keyboard_arrow_up_rounded
                    : Icons.keyboard_arrow_down_rounded,
                color: Colors.grey.shade400,
                size: 30,
              ),
            ),
          ),
        )
      ],
    );
  }

  Widget _buildServicePackageVPanel(BuildContext context) {
    return VPanel(
      child: VListFormCellGroup(
        children: [
          Obx(
            () => VListFormCell(
              label: '家庭医生服务包',
              height: 70,
              content: controller.state.selectedServicePackageName,
              onTap: () {
                Scaffold.of(context).openEndDrawer();
              },
            ),
          ),
          const VListFormCell(
            label: '备注',
            content: '5130221999099987',
          ),
        ],
      ),
    );
  }
}
