import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/services/report.m.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/values/font_sizes.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/pages/user/report_template/controller.dart';
import 'package:get/get.dart';

class TemplateSimpleCard extends FisView<ReportTemplateController>
    implements FPage {
  TemplateSimpleCard(this.index);
  final int index;
  @override
  final String pageName = 'TemplateSimpleCard';
  late ReportTemplateController reportTemplateController =
      Get.find<ReportTemplateController>();
  @override
  FWidget build(BuildContext context) {
    final currentTemplate = controller.state.templates[index];

    ///是否为当前组织的模板
    final isCurrentOrganization =
        currentTemplate.organizationCode == Store.user.rootOrganizationCode;

    ///是否为个人创建的模板
    final isCurrentPersonal = currentTemplate.personalCode == Store.user.code;

    ///是否自建模板
    final isReportTemplateTypePersonal =
        currentTemplate.reportTemplateType == ReportTemplateTypeEnum.Personal;

    ///是否机构创建模板
    final isReportTemplateTypeOrganization =
        currentTemplate.reportTemplateType ==
                ReportTemplateTypeEnum.Organization &&
            controller.state.isOrg;

    ///是否有权限编辑或删除
    final isCanEditOrDelete = (isCurrentOrganization || isCurrentPersonal) &&
        (isReportTemplateTypePersonal || isReportTemplateTypeOrganization);
    return FColumn(
      children: [
        FRow(
          children: [
            _buildTemplatePreView(),
            const FSizedBox(width: 10),
            FExpanded(
              child: FColumn(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  _buildTemplateName(),
                  FSizedBox(height: 7),
                  _buildPlatform(index),
                  FSizedBox(height: 7),
                  if (!controller.state.isOrg) ...[
                    _buildDefaultTemplate(index),
                  ],
                ],
              ),
            ),
          ],
        ),
        FSizedBox(height: 7),
        if (isCanEditOrDelete) ...[
          FPadding(
            padding: const EdgeInsets.only(right: 10),
            child: FDivider(
              height: 1,
              color: index == controller.state.selectTemplateIndex
                  ? Colors.white
                  : Colors.grey,
            ),
          ),
          FSizedBox(height: 7),
          _buildOperateLine(),
        ],
      ],
    );
  }

  ///模板名称
  FWidget _buildTemplateName() {
    return FMaterialTooltip(
      message: controller.state.templates[index].reportTemplateName ?? "",
      child: FText(
        controller.state.templates[index].reportTemplateName ?? "",
        overflow: TextOverflow.ellipsis,
        style: TextStyle(
          color: controller.state.selectTemplateIndex == index
              ? Colors.white
              : null,
          fontSize: FFontSizes.H5,
        ),
      ),
    );
  }

  ///平台默认
  FWidget _buildDefaultTemplate(int index) {
    final state = controller.state;
    return FRow(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        FText(
          i18nBook.user.defaultTemplate.t,
          style: TextStyle(
            color: controller.state.selectTemplateIndex == index
                ? Colors.white
                : null,
            fontSize: FFontSizes.H6,
          ),
        ),
        FSizedBox(
          width: 5,
        ),
        FSwitch(
          value: state.templates[index].reportTemplateCode ==
              state.defaultTemplateCode,
          inactiveThumbColor: Colors.green,
          inactiveTrackColor: Colors.grey.withAlpha(88),
          activeColor: Colors.white,
          activeTrackColor: Colors.green,
          onChanged: (value) {
            controller.setDefaultTemplate(index);
          },
        )
      ],
    );
  }

  ///模板类型
  FWidget _buildPlatform(int index) {
    String type = i18nBook.common.platformDefault.t;
    final currentTemplate = controller.state.templates[index];
    final reportTemplateType = currentTemplate.reportTemplateType;
    switch (reportTemplateType) {
      case ReportTemplateTypeEnum.Default:
        type = i18nBook.common.platformDefault.t;
        break;
      case ReportTemplateTypeEnum.Organization:
        type = i18nBook.remedical.orgTemplate.t;
        break;
      case ReportTemplateTypeEnum.Personal:
        type = i18nBook.remedical.selfCreated.t;
        break;
    }
    return FText(
      i18nBook.remedical.creations.t + ': ' + type,
      style: TextStyle(
          color: controller.state.selectTemplateIndex == index
              ? Colors.white
              : null),
    );
  }

  /// 确认是否删除
  void _onMakeSureDelete(ReportTemplateDTO currentTemplate) {
    FConfirmAlert.show(
      context: Get.context!,
      title: i18nBook.common.tip.t,
      subTitle: i18nBook.common.confirm.t +
          i18nBook.common.delete.t +
          i18nBook.homePage.reportTemplate.t +
          '？',
      confrimLabel: i18nBook.common.confirm.t,
      cancelLabel: i18nBook.common.cancel.t,
      onConfirm: () async {
        await reportTemplateController.busyHandle(
          () async {
            await controller
                .removeTemplate(currentTemplate.reportTemplateCode ?? '');
          },
          text: i18nBook.remedical.deleting.t,
        );
      },
      businessParent: this,
    );
  }

  ///操作行，删除、编辑
  ///
  /// 删除权限
  /// 是否是本机构下的报告或者是本人的报告并且（是自建的报告或者是机构管理员创建的机构报告）
  ///
  FWidget _buildOperateLine() {
    final currentTemplate = controller.state.templates[index];

    final name = currentTemplate.reportTemplateName;
    return FRow(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        FIconButton(
          name: name,
          businessParent: this,
          icon: FIcon(
            Icons.edit,
            color: index == controller.state.selectTemplateIndex
                ? Colors.white
                : Color.fromARGB(186, 0, 0, 0),
          ),
          onPressed: () {
            controller.editTemplate(
              name ?? '',
              currentTemplate.reportTemplateCode ?? '',
              currentTemplate.reportTemplateUsageType,
              true,
            );
          },
        ),
        const FSizedBox(width: 10),
        FIconButton(
          businessParent: this,
          name: "delete",
          icon: FIcon(
            Icons.delete,
            color: index == controller.state.selectTemplateIndex
                ? Colors.white
                : Color.fromARGB(186, 0, 0, 0),
          ),
          onPressed: () {
            _onMakeSureDelete(currentTemplate);
          },
        ),
      ],
    );
  }

  ///模板图标
  FWidget _buildTemplatePreView() {
    return FIcon(
      FIcons.report_a4,
      size: 70,
    );
  }

  BoxDecoration getBoxDecoration() {
    return BoxDecoration(
      border: new Border.all(
        width: 1,
        color: index == controller.state.selectTemplateIndex
            ? Colors.white
            : Color.fromARGB(186, 0, 0, 0),
      ),
    );
  }
}
