import 'package:cs_resources/constants/color_constants.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:plugin_basic/base/base_state.dart';
import 'package:plugin_basic/base/base_stateful_page.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_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 'labour_template_add_controller.dart';

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

import 'labour_template_add_state.dart';

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

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

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

  @override
  State<LabourTemplateAddPage> createState() => _LabourTemplateAddState();
}

class _LabourTemplateAddState extends BaseState<LabourTemplateAddPage, LabourTemplateAddController> {
  late LabourTemplateAddState state;

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

  @override
  Widget build(BuildContext context) {
    return autoCtlGetBuilder(
        id: "all",
        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,
                          ),

                          //年龄
                          Visibility(
                            visible: state.indexEntity?.ageList.isNotEmpty == true,
                            child: MyTextView(
                              "Age".tr,
                              textColor: Colors.white,
                              fontSize: 14,
                              isFontRegular: true,
                              marginLeft: 15,
                              marginTop: 15,
                            ),
                          ),

                          // 年龄的多选
                          Visibility(
                            visible: state.indexEntity?.ageList.isNotEmpty == true,
                            child: 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),
                          ),

                          //性别
                          Visibility(
                            visible: state.indexEntity?.sexList.isNotEmpty == true,
                            child: MyTextView(
                              "Gender".tr,
                              textColor: Colors.white,
                              fontSize: 14,
                              isFontRegular: true,
                              marginLeft: 15,
                              marginTop: 15,
                            ),
                          ),

                          //性别单选
                          Visibility(
                            visible: state.indexEntity?.sexList.isNotEmpty == true,
                            child: 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(
                            "Language".tr,
                            textColor: Colors.white,
                            fontSize: 14,
                            isFontRegular: true,
                            marginLeft: 15,
                            marginTop: 15,
                          ),

                          // 语言的多选
                          GetBuilder<LabourTemplateAddController>(
                            builder: (controller) {
                              return CustomCheckBox(
                                options: state.optionLanguageList,
                                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() ?? [],
                              );
                            },
                            id: "language",
                            init: controller,
                          ).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['desc']!['focusNode'].unfocus();
                                  FocusScope.of(context).requestFocus(state.formData['note']!['focusNode']);
                                },
                              ),
                            ),
                          ),

                          //备注
                          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['note']!['focusNode'].unfocus();
                                },
                              ),
                            ),
                          ),

                          //提交按钮
                          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),
                        ],
                      ),
                    ),
                  ),
                ),
              ),
            ),
          );
        });
  }
}
