import 'package:cs_resources/constants/color_constants.dart';
import 'package:cs_resources/generated/assets.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:plugin_platform/engine/directory/directory_util.dart';
import 'package:plugin_platform/engine/image/image_preview.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:shared/utils/util.dart';
import 'package:widgets/ext/ex_widget.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/search_app_bar.dart';
import 'package:widgets/widget_export.dart';

import 'applied_staff_item.dart';
import 'job_applied_controller.dart';

import 'package:plugin_basic/base/base_state.dart';
import 'package:plugin_basic/base/base_stateful_page.dart';
import 'package:plugin_basic/utils/ext_get_nav.dart';
import 'package:router/path/router_path.dart';
import 'package:shared/utils/screen_util.dart';
import 'package:widgets/my_appbar.dart';
import 'job_applied_state.dart';

/*
 * 已申请的页面 （新加坡）
 */
class JobAppliedPage extends BaseStatefulPage<JobAppliedController> {
  JobAppliedPage({Key? key}) : super(key: key);

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

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

  @override
  State<JobAppliedPage> createState() => _JobAppliedState();
}

class _JobAppliedState extends BaseState<JobAppliedPage, JobAppliedController> {
  late JobAppliedState state;
  String path = "";

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

    if (!kIsWeb) {
      path = DirectoryUtil.getTempPath() ?? "";
      Log.e("path:$path");
    }
  }

  @override
  Widget build(BuildContext context) {
    return autoCtlGetBuilder(builder: (controller) {
      return SafeArea(
        bottom: MediaQuery.of(context).padding.bottom > 38,
        top: false,
        child: Container(
          width: double.infinity,
          height: double.infinity,
          padding: EdgeInsets.only(top: ScreenUtil.getStatusBarH(context)),
          decoration: const BoxDecoration(
            gradient: LinearGradient(
              colors: [
                Color(0xFF091D44),
                Color(0xFF245A8A),
                Color(0xFF7F7CEC),
              ],
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
            ),
          ),
          child: Column(
            children: [
              MyAppBar.titleBar(
                context,
                state.appliedIndexEntity?.jobTitle ?? "Title".tr,
                subTitle: "(${state.appliedIndexEntity?.jobDate ?? "-"})",
                subTitleColor: ColorConstants.textGrayAECAE5,
              ),

              //搜索的条件
              Row(
                children: [
                  Container(
                    padding: const EdgeInsets.only(left: 11, right: 11),
                    margin: const EdgeInsets.only(right: 10),
                    height: 40,
                    decoration: BoxDecoration(
                      color: const Color(0xFF4DCFF6).withOpacity(0.2),
                      borderRadius: const BorderRadius.all(Radius.circular(20)),
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.max,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        MyTextView(
                          state.selectedStatusTxt ?? "",
                          fontSize: 14,
                          hint: "Status".tr,
                          textHintColor: ColorConstants.textGrayAECAE5,
                          isFontMedium: true,
                          textColor: ColorConstants.white,
                        ).expanded(),

                        //下拉选图标
                        const MyAssetImage(Assets.baseServiceTriangleDropDownIcon, width: 11.5, height: 6.28),
                      ],
                    ),
                  ).onTap(() {
                    FocusScope.of(context).unfocus();
                    controller.pickStatus();
                  }).expanded(),
                  SearchAppBar(
                    value: state.keyword,
                    searchBarHeight: 40,
                    margin: const EdgeInsets.only(right: 10),
                    onSearch: (keyword) {
                      controller.doSearch(keyword);
                    },
                    hintText: "Search".tr,
                    controller: state.searchController,
                  ).expanded(),
                  MyButton(
                    onPressed: () {
                      FocusScope.of(context).unfocus();
                      controller.resetFiltering();
                    },
                    text: "Reset".tr,
                    textColor: ColorConstants.white,
                    backgroundColor: hexToColor("#2BA9F9", opacity: 0.5),
                    radius: 20,
                    minWidth: 60,
                    minHeight: 40,
                  ),
                ],
              ).marginOnly(top: 10, left: 15, right: 15, bottom: 5),

              Row(
                children: [
                  MyButton(
                    type: ClickType.throttle,
                    milliseconds: 500,
                    onPressed: () {
                      FocusScope.of(context).unfocus();
                      controller.confirmJob();
                    },
                    padding: const EdgeInsets.symmetric(horizontal: 5.0),
                    text: "Operation Approve".tr,
                    textColor: ColorConstants.white,
                    fontSize: 16,
                    radius: 20,
                    backgroundColor: hexToColor("#855EF5"),
                    fontWeight: FontWeight.w500,
                  ).expanded(),

                  // 添加按钮
                  Visibility(
                    visible: state.appliedIndexEntity?.canAppend == true,
                    child: MyButton(
                      type: ClickType.throttle,
                      milliseconds: 500,
                      onPressed: () {
                        FocusScope.of(context).unfocus();
                        controller.gotoAddStaffPage();
                      },
                      text: "Add Staff".tr,
                      padding: const EdgeInsets.symmetric(horizontal: 5.0),
                      textColor: ColorConstants.white,
                      fontSize: 16,
                      radius: 20,
                      backgroundColor: hexToColor("#FFBB1B"),
                      fontWeight: FontWeight.w500,
                    ).marginOnly(left: 10).expanded(),
                  ),
                ],
              ).marginOnly(left: 15, right: 15, top: 5, bottom: 10),

              //底部的列表
              EasyRefresh(
                controller: controller.refreshController,
                onRefresh: controller.onRefresh,
                onLoad: controller.loadMore,
                child: LoadStateLayout(
                  state: controller.loadingState,
                  errorMessage: controller.errorMessage,
                  errorRetry: () {
                    controller.retryRequest();
                  },
                  successSliverWidget: [
                    SliverList(
                        delegate: SliverChildBuilderDelegate(
                      (context, index) {
                        return AppliedStaffItem(
                          index: index,
                          item: state.datas[index],
                          onEditAction: () {
                            controller.showAppliedEditDialog(state.datas[index]);
                          },
                          onRemarkAction: () {
                            controller.showRemarkDialog(state.datas[index]);
                          },
                          onReviseAction: () {
                            controller.gotoReviseAppliedPage(state.datas[index]);
                          },
                          onModifyAction: () {
                            controller.showAppliedEditDialog(state.datas[index]);
                          },
                          onItemAction: () {
                            controller.doSelectedOrNot(state.datas[index]);
                          },
                          onMemberAction: () {
                            controller.gotoStaffDetailPage(state.datas[index]);
                          },
                          onStatusAction: (targetContext) {
                            controller.dropDownStatus(index, targetContext);
                          },
                          onImagePreviewAction: (imageUrl) {
                            if (Utils.isNotEmpty(imageUrl)) {
                              ImagePreviewEngine.singleImagePreview(context, imageUrl!);
                            }
                          },
                        );
                      },
                      childCount: state.datas.length,
                    ))
                  ],
                ),
              ).expanded(),

              MyTextView(
                "Batch Modify".tr,
                fontSize: 17,
                isFontMedium: true,
                boxHeight: 48,
                onClick: () {
                  controller.showBatchModifyDialog();
                },
                alignment: Alignment.center,
                textAlign: TextAlign.center,
                textColor: Colors.white,
                backgroundColor: Color(0XFFFFBB1B),
              ),
            ],
          ),
        ),
      );
    });
  }
}
