import 'dart:ui';

import 'package:cs_resources/generated/assets.dart';
import 'package:domain/entity/response/t_h_o_a_attachment_entity.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:plugin_basic/basic_export.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:widgets/ext/ex_widget.dart';
import 'package:cs_resources/constants/color_constants.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/my_button.dart';
import 'package:widgets/my_load_image.dart';
import 'package:widgets/my_text_view.dart';
import 'package:widgets/widget_export.dart';

import 'oa_attach_list_controller.dart';

/*
 * OA 的附件列表弹窗
 */
class OaAttachListDialog extends StatefulWidget {
  String requestId;
  String jobTitle;
  String jobDate;

  OaAttachListDialog({required this.requestId, required this.jobTitle, required this.jobDate});

  @override
  State<OaAttachListDialog> createState() => _AppliedAddStaffState();
}

class _AppliedAddStaffState extends State<OaAttachListDialog> {
  @override
  void initState() {
    super.initState();
    OaAttachListController controller = Get.put(OaAttachListController());
    controller.requestId = widget.requestId;
  }

  @override
  void dispose() {
    super.dispose();
    Get.delete<OaAttachListController>();
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<OaAttachListController>(
      assignId: true,
      builder: (controller) {
        return Container(
          width: 300,
          height: 555,
          decoration: const BoxDecoration(
            color: Color(0XFFF7F7F7),
            borderRadius: BorderRadius.all(Radius.circular(15)),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.max,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Stack(
                children: [
                  Center(
                    child: MyTextView(
                      "Attachment".tr,
                      fontSize: 19,
                      isFontMedium: true,
                      textColor: ColorConstants.black,
                      marginTop: 22,
                      marginLeft: 22,
                      marginRight: 22,
                    ),
                  ),
                  const MyAssetImage(
                    Assets.baseServiceRedDeleteIcon,
                    width: 20,
                    height: 20,
                  ).marginOnly(top: 15, right: 15).onTap(() {
                    onCancel();
                  }).alignRight(),
                ],
              ),
              MyButton(
                type: ClickType.throttle,
                milliseconds: 500,
                onPressed: () {
                  controller.pickAttFile();
                },
                text: "Add File".tr,
                minHeight: 35,
                textColor: ColorConstants.white,
                fontSize: 12,
                radius: 20,
                backgroundColor: hexToColor("#FFBB1B"),
                fontWeight: FontWeight.w500,
              ).marginOnly(left: 15, right: 15, top: 5),

              //工作信息
              MyTextView(
                "${widget.jobTitle} ${widget.jobDate}",
                isFontRegular: true,
                fontSize: 14,
                textColor: ColorConstants.black,
                marginLeft: 10,
                marginRight: 10,
                textAlign: TextAlign.center,
                marginBottom: 10,
              ),

              //列表容器
              Container(
                decoration: const BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.only(bottomLeft: Radius.circular(15), bottomRight: Radius.circular(15)),
                ),
                child: EasyRefresh(
                  header: ClassicHeader(
                    dragText: 'Pull to refresh'.tr,
                    armedText: 'Release ready'.tr,
                    readyText: 'Refreshing...'.tr,
                    processingText: 'Refreshing...'.tr,
                    processedText: 'Succeeded'.tr,
                    noMoreText: 'No more'.tr,
                    failedText: 'Failed'.tr,
                    messageText: 'Last updated at %T'.tr,
                    textStyle: const TextStyle(color: ColorConstants.black66, fontSize: 14),
                    messageStyle: const TextStyle(color: ColorConstants.black66, fontSize: 12),
                    iconTheme: const IconThemeData(color: ColorConstants.black66),
                    backgroundColor: Colors.transparent,
                  ),
                  footer: ClassicFooter(
                    dragText: 'Pull to load'.tr,
                    armedText: 'Release ready'.tr,
                    readyText: 'Loading...'.tr,
                    processingText: 'Loading...'.tr,
                    processedText: 'Succeeded'.tr,
                    noMoreText: 'No more'.tr,
                    failedText: 'Failed'.tr,
                    showMessage: false,
                    triggerOffset: 50,
                    iconDimension: 22,
                    textStyle: const TextStyle(color: ColorConstants.black66, fontSize: 14),
                    messageStyle: const TextStyle(color: ColorConstants.black66, fontSize: 12),
                    iconTheme: const IconThemeData(color: ColorConstants.black66),
                    backgroundColor: Colors.transparent,
                  ),
                  controller: controller.refreshController,
                  onRefresh: controller.onRefresh,
                  onLoad: controller.loadMore,
                  child: LoadStateLayout(
                    themeColor: ColorConstants.black66,
                    state: controller.loadingState,
                    errorMessage: controller.errorMessage,
                    errorRetry: () {
                      controller.retryRequest();
                    },
                    successSliverWidget: [
                      SliverList(
                          delegate: SliverChildBuilderDelegate(
                                (context, index) {
                              return _buildStaffItem(controller.datas[index], () {
                                //删除
                                controller.doDeleteAction(controller.datas[index].id??"", index);
                              });
                            },
                            childCount: controller.datas.length,
                          ))
                    ],
                  ),
                ),
              ).expanded(),
            ],
          ),
        );
      },
    );
  }

  //取消弹框
  void onCancel() async {
    SmartDialog.dismiss();
  }

  Widget _buildStaffItem(THOAAttachmentRows item, VoidCallback deleteAction) {
    return Column(
      children: [
        //姓名
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            MyTextView(
              "${"Url".tr}:",
              textColor: ColorConstants.black66,
              fontSize: 13,
              marginRight: 3,
              isFontRegular: true,
            ),
            MyTextView(
              item.attUrl ?? "-",
              textColor: ColorConstants.string2Color("#06A962"),
              fontSize: 12,
              onClick: () {
                _openFile(item.attUrl??"");
              },
              marginLeft: 10,
              isFontRegular: true,
            ).expanded(),
            MyButton(
              onPressed: () {
                deleteAction.call();
              },
              text: "Delete".tr,
              textColor: ColorConstants.white,
              backgroundColor: ColorConstants.redFF4066,
              radius: 17.25,
              fontSize: 12,
              minWidth: 48,
              minHeight: 30,
            ).marginOnly(left: 10)
          ],
        ).marginOnly(top: 15),

        Row(
          children: [
            MyTextView(
              "Created At:".tr,
              textColor: ColorConstants.black66,
              fontSize: 13,
              marginRight: 3,
              isFontRegular: true,
            ),
            MyTextView(
              item.createdAt ?? "-",
              textColor: ColorConstants.black,
              fontSize: 12,
              isFontRegular: true,
            ),
          ],
        ).marginOnly(top: 10),

        Container(
          margin: const EdgeInsets.only(top: 16),
          width: double.infinity,
          height: 1,
          color: const Color(0XFFF7F7F7),
        )
      ],
    ).paddingOnly(left: 19, right: 11);
  }

  ///尝试预览文件
  void _openFile(String attUrl) async {
    // 创建一个 Uri 对象
    final Uri url = Uri.parse(attUrl);
    if (await canLaunchUrl(url)) {
      await launchUrl(url);
    } else {
      ToastEngine.show("无法打开链接");
    }
  }
}
