import 'dart:typed_data';
import 'dart:ui';

import 'package:cs_resources/generated/assets.dart';
import 'package:domain/entity/response/job_title_edit_index_entity.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:plugin_basic/service/app_config_service.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:shared/utils/util.dart';
import 'package:widgets/ext/ex_widget.dart';
import 'package:cs_resources/constants/color_constants.dart';
import 'package:widgets/my_load_image.dart';
import 'package:widgets/my_text_field.dart';
import 'package:widgets/my_text_view.dart';
import 'package:widgets/picker/option_pick_util.dart';
import 'package:widgets/shatter/form_require_text.dart';
import 'package:widgets/widget_export.dart';

/**
 * 添加工作标题的弹窗
 */
class AddJobTitleDialog extends StatefulWidget {
  JobTitleEditIndexEntity? editIndexEntity;

  void Function(String jobTitleId, String jobTitle, String templateId, String sort)? confirmAction;

  AddJobTitleDialog({this.editIndexEntity, this.confirmAction});

  @override
  State<AddJobTitleDialog> createState() => _AddJobTitleDialogState();
}

class _AddJobTitleDialogState extends State<AddJobTitleDialog> {
  String? jobTitle;
  JobTitleEditIndexTemplate? template;
  String? sort;
  late TextEditingController jobTitleController;
  late FocusNode jobTitleFocusNode;
  late TextEditingController sortController;
  late FocusNode sortFocusNode;

  @override
  void initState() {
    super.initState();
    jobTitle = widget.editIndexEntity?.jobTitle;
    template = widget.editIndexEntity?.template.firstWhere((element) => element?.selected == 'selected', orElse: () => null);
    sort = widget.editIndexEntity?.sort.toString();
    jobTitleController = TextEditingController();
    if (Utils.isNotEmpty(jobTitle)) {
      jobTitleController.text = jobTitle!;
    }
    jobTitleFocusNode = FocusNode();
    sortController = TextEditingController();
    if (Utils.isNotEmpty(sort)) {
      sortController.text = sort!;
    }
    sortFocusNode = FocusNode();
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.only(
        bottom: ConfigService.to.isFullScreenDevice ? MediaQuery.of(context).viewInsets.bottom : 0, //小屏手机不移动
      ), // 在底部加上键盘高度
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          //Title （如果使用 Container 为最外层容器则默认为 match_parent 的效果，除非我们限制宽度和最大高度最小高度）
          Container(
            padding: EdgeInsets.symmetric(horizontal: 16.5),
            width: double.infinity,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: const BorderRadius.all(Radius.circular(15)),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Center(
                  child: MyTextView(
                    "Add New".tr,
                    fontSize: 19,
                    isFontMedium: true,
                    textColor: ColorConstants.black,
                    marginTop: 22,
                    marginBottom: 20,
                  ),
                ),

                // 输入工作标题
                FormRequireText(
                  fontSize: 14,
                  textColor: ColorConstants.black33,
                  fontWeight: FontWeight.w400,
                  text: "Job Title".tr,
                ),

                IgnoreKeyboardDismiss(
                  child: MyTextField(
                    "job_title",
                    jobTitle ?? "",
                    hintText: "Enter...".tr,
                    hintStyle: TextStyle(
                      color: ColorConstants.gray88,
                      fontSize: 14,
                      fontWeight: FontWeight.w400,
                    ),
                    controller: jobTitleController,
                    focusNode: jobTitleFocusNode,
                    margin: EdgeInsets.only(left: 0, right: 0, top: 8),
                    showDivider: false,
                    fillBackgroundColor: ColorConstants.grayECECEC,
                    fillCornerRadius: 5,
                    padding: EdgeInsets.only(left: 16, right: 16, top: 0, bottom: 0),
                    height: 45,
                    style: TextStyle(
                      color: ColorConstants.black33,
                      fontSize: 14,
                      fontWeight: FontWeight.w400,
                    ),
                    inputType: TextInputType.text,
                    textInputAction: TextInputAction.next,
                    enabled: true,
                    onSubmit: (key, value) {},
                    cursorColor: ColorConstants.black33,
                    showLeftIcon: false,
                    showRightIcon: false,
                  ),
                ),

                //选择模板
                MyTextView(
                  "Template".tr,
                  fontSize: 14,
                  marginTop: 14,
                  textColor: ColorConstants.black33,
                  isFontRegular: true,
                ),

                //选择模板
                Container(
                  padding: EdgeInsets.only(left: 16, right: 10),
                  margin: EdgeInsets.only(top: 10),
                  height: 45,
                  decoration: BoxDecoration(
                    color: ColorConstants.grayECECEC,
                    borderRadius: const BorderRadius.all(Radius.circular(5)),
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.max,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      MyTextView(
                        template?.txt ?? "",
                        fontSize: 14,
                        hint: "Choose Outlet".tr,
                        textHintColor: ColorConstants.black33,
                        isFontMedium: true,
                        textColor: ColorConstants.black33,
                      ).expanded(),
                      MyAssetImage(Assets.baseServiceTriangleDropDownIcon, width: 11.5, height: 6.28),
                    ],
                  ),
                ).onTap(() {
                  jobTitleFocusNode.unfocus();
                  sortFocusNode.unfocus();
                  FocusScope.of(context).unfocus();
                  pickerJobTemplate();
                }),

                //输入自定义排序
                MyTextView(
                  "Sort".tr,
                  fontSize: 14,
                  marginTop: 14,
                  textColor: ColorConstants.black33,
                  isFontRegular: true,
                ),

                IgnoreKeyboardDismiss(
                  child: MyTextField(
                    "sort",
                    sort ?? "",
                    hintText: "Enter...".tr,
                    hintStyle: TextStyle(
                      color: ColorConstants.gray88,
                      fontSize: 14,
                      fontWeight: FontWeight.w400,
                    ),
                    controller: sortController,
                    focusNode: sortFocusNode,
                    margin: EdgeInsets.only(left: 0, right: 0, top: 8),
                    showDivider: false,
                    fillBackgroundColor: ColorConstants.grayECECEC,
                    fillCornerRadius: 5,
                    padding: EdgeInsets.only(left: 16, right: 16, top: 0, bottom: 0),
                    height: 45,
                    style: TextStyle(
                      color: ColorConstants.black33,
                      fontSize: 14,
                      fontWeight: FontWeight.w400,
                    ),
                    inputType: TextInputType.number,
                    textInputAction: TextInputAction.next,
                    enabled: true,
                    inputFormatters: <TextInputFormatter>[FilteringTextInputFormatter.digitsOnly],
                    onSubmit: (key, value) {},
                    cursorColor: ColorConstants.black33,
                    showLeftIcon: false,
                    showRightIcon: false,
                  ),
                ),

                //分割线
                Container(
                  margin: EdgeInsets.only(top: 21),
                  color: Color(0XFFCECECE),
                  height: 0.5,
                ),
                Row(
                  children: [
                    Expanded(
                        flex: 1,
                        child: InkWell(
                          onTap: () {
                            onCancel();
                          },
                          child: MyTextView(
                            "Cancel".tr,
                            fontSize: 17.5,
                            isFontMedium: true,
                            textAlign: TextAlign.center,
                            textColor: Color(0XFF0085C4),
                            cornerRadius: 3,
                            borderWidth: 1,
                          ),
                        )),
                    Container(
                      color: Color(0xff09141F).withOpacity(0.13),
                      width: 0.5,
                    ),
                    Expanded(
                        flex: 1,
                        child: InkWell(
                          onTap: () async {
                            doCallBack();
                            onCancel();
                          },
                          child: MyTextView(
                            "Submit".tr,
                            marginLeft: 10,
                            fontSize: 17.5,
                            isFontMedium: true,
                            textAlign: TextAlign.center,
                            textColor: Color(0XFF0085C4),
                            cornerRadius: 3,
                          ),
                        )),
                  ],
                ).constrained(height: 46),
              ],
            ),
          ),
        ],
      ).constrained(width: 285),
    );
  }

  /// 选择工作模板
  void pickerJobTemplate() {
    if (widget.editIndexEntity == null) return;

    var selectedTemplateIndex = 0;
    if (template != null) {
      int selectedIndex = widget.editIndexEntity?.template.indexWhere((element) => element?.selected == 'selected') ?? -1;
      if (selectedIndex < 0) {
        selectedTemplateIndex = 0;
      }
    }

    OptionPickerUtil.showCupertinoOptionPicker(
      items: widget.editIndexEntity!.template.map((e) => e?.txt ?? "").toList(growable: false),
      initialSelectIndex: selectedTemplateIndex,
      onPickerChanged: (_, index) {
        setState(() {
          template = widget.editIndexEntity!.template[index];
        });
      },
    );
  }

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

  void doCallBack() {
    String jobTitle = jobTitleController.text.toString();
    String sort = sortController.text.toString();

    if (Utils.isEmpty(jobTitle)) {
      ToastEngine.show("Enter Job Title".tr);
      return;
    }

    widget.confirmAction?.call(widget.editIndexEntity?.titleId.toString() ?? "", jobTitle, template?.value.toString() ?? "", sort);
  }
}
