import 'package:cs_resources/constants/color_constants.dart';
import 'package:cs_resources/generated/assets.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:shared/utils/screen_util.dart';
import 'package:shared/utils/util.dart';
import 'package:widgets/ext/ex_widget.dart';
import 'package:widgets/my_appbar.dart';
import 'package:widgets/my_button.dart';
import 'package:widgets/my_load_image.dart';
import 'package:widgets/my_text_view.dart';
import 'package:widgets/no_shadow_scroll_behavior.dart';
import 'package:widgets/shatter/custom_check_box.dart';
import 'package:widgets/shatter/custom_radio_check.dart';
import 'package:widgets/shatter/form_require_text.dart';
import 'package:widgets/shatter/round_my_text_field.dart';
import 'package:widgets/widget_export.dart';

import 'job_template_add_controller.dart';

import 'package:plugin_basic/base/base_stateless_page.dart';
import 'package:plugin_basic/utils/ext_get_nav.dart';
import 'package:router/path/router_path.dart';

import 'job_template_add_state.dart';

/*
 * 模板的添加与编辑
 */
class JobTemplateAddPage extends BaseStatelessPage<JobTemplateAddController> {
  JobTemplateAddPage({Key? key}) : super(key: key);

  //启动当前页面
  static void startInstance(
    String templateId,
    void Function(dynamic value)? cb,
  ) {
    return Get.start(RouterPath.jobTemplateAddSG, arguments: {'templateId': templateId, 'cb': cb});
  }

  late JobTemplateAddState state;

  @override
  void initState() {
    state = controller.state;
    state.templateId = Get.arguments['templateId'];
    state.cb = Get.arguments['cb'] as void Function(dynamic)?;
  }

  @override
  JobTemplateAddController createRawController() {
    return JobTemplateAddController();
  }

  @override
  Widget buildWidget(BuildContext context) {
    return autoCtlGetBuilder(builder: (controller) {
      return Scaffold(
        extendBodyBehindAppBar: true,
        appBar: MyAppBar.appBar(context, Utils.isEmpty(state.templateId) ? "Create Template".tr : "Edit Template".tr),
        body: SafeArea(
        bottom: MediaQuery.of(context).padding.bottom > 38,
          top: false,
          child: Container(
            width: double.infinity,
            height: double.infinity,
            padding: EdgeInsets.only(top: kToolbarHeight + ScreenUtil.getStatusBarH(context) + 1),
            decoration: const BoxDecoration(
              gradient: LinearGradient(
                colors: [
                  Color(0xFF091D44),
                  Color(0xFF245A8A),
                  Color(0xFF7F7CEC),
                ],
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
              ),
            ),
            child: Scrollbar(
              child: ScrollConfiguration(
                behavior: NoShadowScrollBehavior(),
                child: SingleChildScrollView(
                  scrollDirection: Axis.vertical,
                  physics: const BouncingScrollPhysics(),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      //模板名称
                      FormRequireText(text: "Template Name".tr).marginOnly(left: 15, top: 19),

                      CustomTextField(
                        formKey: "template_name",
                        formData: state.formData,
                        height: 46,
                        fontSize: 14,
                        onSubmit: (key, value) {
                          state.formData[key]!['focusNode'].unfocus();
                          FocusScope.of(context).requestFocus(state.formData['desc']!['focusNode']);
                        },
                        marginTop: 10,
                      ),

                      //必选 - 选择职位
                      FormRequireText(text: "agency_position".tr).marginOnly(left: 15, top: 15),

                      //下拉选
                      Container(
                        padding: const EdgeInsets.only(left: 16, right: 10),
                        margin: const EdgeInsets.only(top: 10, left: 15, right: 15),
                        height: 45,
                        decoration: BoxDecoration(
                          color: const Color(0xFF4DCFF6).withOpacity(0.2),
                          borderRadius: const BorderRadius.all(Radius.circular(5)),
                        ),
                        child: Row(
                          mainAxisSize: MainAxisSize.max,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            MyTextView(
                              state.positionName ?? "",
                              fontSize: 14,
                              hint: "Choose Position".tr,
                              textHintColor: ColorConstants.textGrayAECAE5,
                              isFontMedium: true,
                              textColor: ColorConstants.white,
                            ).expanded(),

                            //下拉选图标
                            const MyAssetImage(Assets.baseServiceTriangleDropDownIcon, width: 11.5, height: 6.28),
                          ],
                        ),
                      ).onTap(() {
                        if (state.positionList.isNotEmpty) {
                          FocusScope.of(context).unfocus();
                          controller.pickPosition();
                        }
                      }),

                      //年龄
                      MyTextView(
                        "Age".tr,
                        textColor: Colors.white,
                        fontSize: 14,
                        isFontRegular: true,
                        marginLeft: 15,
                        marginTop: 15,
                      ),

                      // 年龄的多选
                      CustomCheckBox(
                        options: state.indexEntity?.ageList.map((e) => e.txt!).toList() ?? [],
                        onOptionsSelected: (selected) {
                          // 转换选中的索引为对应的 value
                          state.selectedAgeList = selected
                              .map((index) {
                                return state.indexEntity?.ageList[index].value; // 获取对应的 value
                              })
                              .whereType<String>()
                              .toList();
                        },
                        selectedOptions: state.indexEntity?.ageList.where((e) => e.checked == "checked").map((e) => e.txt!).toList() ?? [],
                      ).marginOnly(left: 15, right: 15, top: 10),

                      // //性别
                      // MyTextView(
                      //   "Gender".tr,
                      //   textColor: Colors.white,
                      //   fontSize: 14,
                      //   isFontRegular: true,
                      //   marginLeft: 15,
                      //   marginTop: 15,
                      // ),
                      //
                      // //性别单选
                      // CustomRadioCheck(
                      //   options: state.indexEntity?.sexList.map((e) => e.txt!).toList() ?? [],
                      //   onOptionSelected: (index, text) {
                      //     state.gender = state.indexEntity!.sexList[index].value;
                      //   },
                      //   selectedPosition: state.indexEntity?.sexList.indexWhere((e) => e.checked == "checked") ?? -1,
                      // ).marginOnly(left: 15, right: 15, top: 10),

                      //语言
                      MyTextView(
                        "Preferred Language".tr,
                        textColor: Colors.white,
                        fontSize: 14,
                        isFontRegular: true,
                        marginLeft: 15,
                        marginTop: 15,
                      ),

                      // 语言的多选
                      CustomCheckBox(
                        options: state.indexEntity?.languageList.map((e) => e.txt!).toList() ?? [],
                        onOptionsSelected: (selected) {
                          // 转换选中的索引为对应的 value
                          state.selectedLanguageList = selected
                              .map((index) {
                                return state.indexEntity?.languageList[index].value; // 获取对应的 value
                              })
                              .whereType<String>()
                              .toList();
                        },
                        selectedOptions: state.indexEntity?.languageList.where((e) => e.checked == "checked").map((e) => e.txt!).toList() ?? [],
                      ).marginOnly(left: 15, right: 15, top: 10),

                      //食品安全证书
                      MyTextView(
                        "Food Hygiene Cert".tr,
                        textColor: Colors.white,
                        fontSize: 14,
                        isFontRegular: true,
                        marginLeft: 15,
                        marginTop: 15,
                      ),

                      //食品安全证书单选
                      CustomRadioCheck(
                        options: state.indexEntity?.withFoodCert != null ? state.foodHygieneCertOption : [],
                        onOptionSelected: (index, text) {
                          state.foodCert = index == 0 ? "1" : "0";
                        },
                        selectedPosition: state.indexEntity?.withFoodCert != null
                            ? state.indexEntity?.withFoodCert == 0 ? 1 : 0 : -1,
                      ).marginOnly(left: 15, right: 15, top: 10),

                      //模板详情
                      MyTextView(
                        "Description".tr,
                        textColor: Colors.white,
                        fontSize: 14,
                        isFontRegular: true,
                        marginLeft: 15,
                        marginTop: 15,
                      ),

                      IgnoreKeyboardDismiss(
                        child: Container(
                          height: 130,
                          margin: const EdgeInsets.only(left: 15, right: 15, top: 10),
                          padding: const EdgeInsets.symmetric(vertical: 15, horizontal: 15),
                          decoration: BoxDecoration(
                            color: const Color(0xFF4DCFF6).withOpacity(0.2),
                            borderRadius: const BorderRadius.all(Radius.circular(5)),
                          ),
                          child: TextField(
                            cursorColor: ColorConstants.white,
                            cursorWidth: 1.5,
                            autofocus: false,
                            enabled: true,
                            focusNode: state.formData["desc"]!['focusNode'],
                            controller: state.formData["desc"]!['controller'],
                            // 装饰
                            decoration: InputDecoration(
                              isDense: true,
                              isCollapsed: true,
                              border: InputBorder.none,
                              hintText: state.formData["desc"]!['hintText'],
                              hintStyle: const TextStyle(
                                color: ColorConstants.textGrayAECAE5,
                                fontSize: 15.0,
                                fontWeight: FontWeight.w400,
                              ),
                            ),
                            style: const TextStyle(
                              color: ColorConstants.white,
                              fontSize: 15.0,
                              fontWeight: FontWeight.w400,
                            ),
                            // 键盘动作右下角图标
                            textInputAction: TextInputAction.next,
                            onSubmitted: (value) {
                              state.formData[key]!['focusNode'].unfocus();
                              FocusScope.of(context).requestFocus(state.formData['contact']!['focusNode']);
                            },
                          ),
                        ),
                      ),

                      //联系人
                      MyTextView(
                        "Contact".tr,
                        textColor: Colors.white,
                        fontSize: 14,
                        isFontRegular: true,
                        marginLeft: 15,
                        marginTop: 15,
                      ),

                      CustomTextField(
                        formKey: "contact",
                        formData: state.formData,
                        height: 46,
                        fontSize: 14,
                        onSubmit: (key, value) {
                          state.formData[key]!['focusNode'].unfocus();
                          FocusScope.of(context).requestFocus(state.formData['contact_no']!['focusNode']);
                        },
                        marginTop: 10,
                      ),

                      //联系人电话
                      MyTextView(
                        "Contact No".tr,
                        textColor: Colors.white,
                        fontSize: 14,
                        isFontRegular: true,
                        marginLeft: 15,
                        marginTop: 18,
                      ),

                      CustomTextField(
                        formKey: "contact_no",
                        formData: state.formData,
                        fontSize: 14,
                        height: 46,
                        textInputType: TextInputType.phone,
                        onSubmit: (key, value) {
                          state.formData[key]!['focusNode'].unfocus();
                          FocusScope.of(context).requestFocus(state.formData['note']!['focusNode']);
                        },
                        marginTop: 10,
                      ),

                      //备注
                      MyTextView(
                        "Note".tr,
                        textColor: Colors.white,
                        fontSize: 14,
                        isFontRegular: true,
                        marginLeft: 15,
                        marginTop: 18,
                      ),

                      IgnoreKeyboardDismiss(
                        child: Container(
                          height: 130,
                          margin: const EdgeInsets.only(left: 15, right: 15, top: 10),
                          padding: const EdgeInsets.symmetric(vertical: 15, horizontal: 15),
                          decoration: BoxDecoration(
                            color: const Color(0xFF4DCFF6).withOpacity(0.2),
                            borderRadius: const BorderRadius.all(Radius.circular(5)),
                          ),
                          child: TextField(
                            cursorColor: ColorConstants.white,
                            cursorWidth: 1.5,
                            autofocus: false,
                            enabled: true,
                            focusNode: state.formData["note"]!['focusNode'],
                            controller: state.formData["note"]!['controller'],
                            // 装饰
                            decoration: InputDecoration(
                              isDense: true,
                              isCollapsed: true,
                              border: InputBorder.none,
                              hintText: state.formData["note"]!['hintText'],
                              hintStyle: const TextStyle(
                                color: ColorConstants.textGrayAECAE5,
                                fontSize: 14.0,
                                fontWeight: FontWeight.w400,
                              ),
                            ),
                            style: const TextStyle(
                              color: ColorConstants.white,
                              fontSize: 14.0,
                              fontWeight: FontWeight.w400,
                            ),
                            // 键盘动作右下角图标
                            textInputAction: TextInputAction.next,
                            onSubmitted: (value) {
                              state.formData[key]!['focusNode'].unfocus();
                              FocusScope.of(context).requestFocus(state.formData['contact']!['focusNode']);
                            },
                          ),
                        ),
                      ),

                      //提交按钮
                      MyButton(
                        type: ClickType.throttle,
                        milliseconds: 500,
                        onPressed: () {
                          FocusScope.of(context).unfocus();
                          controller.doSubmit();
                        },
                        text: "Submit".tr,
                        textColor: ColorConstants.white,
                        fontSize: 16,
                        radius: 20,
                        backgroundColor: ColorConstants.textYellowFFBB1B,
                        fontWeight: FontWeight.w500,
                      ).marginSymmetric(vertical: 25, horizontal: 15),
                    ],
                  ),
                ),
              ),
            ),
          ),
        ),
      );
    });
  }
}
