import 'package:dotted_border/dotted_border.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:keyboard/base/base_page.dart';
import 'package:keyboard/data/bean/ai_model.dart';
import 'package:keyboard/data/bean/option_select_config.dart';
import 'package:keyboard/data/bean/option_select_item.dart';
import 'package:keyboard/module/intimacy_analyse/intimacy_analyse_upload/popup/ai_model_select_popup.dart';
import 'package:keyboard/module/intimacy_analyse/intimacy_analyse_upload/widget/upload_nine_grid.dart';
import 'package:keyboard/resource/colors.gen.dart';
import 'package:keyboard/resource/string.gen.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import '../../../resource/assets.gen.dart';
import '../../../router/app_page_arguments.dart';
import '../../../router/app_pages.dart';
import '../../../utils/step_card_util.dart';
import '../../../utils/string_format_util.dart';
import '../../../widget/actionbtn/action_btn.dart';
import '../../../widget/gradient_btn.dart';
import '../../../widget/gradient_text.dart';
import '../../user_info/enums/gender_type.dart';
import '../widget/intimacy_analyse_report_widget.dart';
import '../widget/intimacy_user_widget.dart';
import '../widget/option_select_widget.dart';
import '../widget/step/upload_step_card.dart';
import '../widget/step_card.dart';
import 'intimacy_analyse_upload_controller.dart';

/// 亲密度分析上传页
class IntimacyAnalyseUploadPage
    extends BasePage<IntimacyAnalyseUploadController> {
  IntimacyAnalyseUploadPage({super.key});

  /// Ai模型切换按钮的GlobalKey
  final GlobalKey _aiModelSwitchBtnAnchorKey = GlobalKey();

  @override
  bool immersive() {
    // 开启沉浸式
    return true;
  }

  @override
  backgroundColor() {
    return Colors.transparent;
  }

  /// 页面跳转
  static start(List<AssetEntity> selectedAssetList) {
    Get.toNamed(
      RoutePath.intimacyAnalyseUpload,
      arguments: {AppPageArguments.selectedAssetList: selectedAssetList},
    );
  }

  @override
  Widget buildBody(BuildContext context) {
    return Scaffold(
      backgroundColor: backgroundColor(),
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: Assets.images.bgIntimacyAnalyse.provider(),
            fit: BoxFit.fill,
          ),
        ),
        child: Column(
          children: [
            // 状态栏占位
            _buildStatusBar(),
            // 顶部栏
            _buildTopBar(),
            // 内容区域
            _buildContent(),
          ],
        ),
      ),
    );
  }

  /// 导航栏占位
  Widget _buildStatusBar() {
    double statusBarHeight = MediaQuery.of(Get.context!).padding.top;
    return Container(
      // 导航栏高度
      height: statusBarHeight,
      color: backgroundColor(),
    );
  }

  /// 顶部栏
  Widget _buildTopBar() {
    return Container(
      // 宽度撑满父组件
      width: double.infinity,
      // 高度为标准导航栏高度
      height: kToolbarHeight,
      // 背景颜色
      color: Colors.transparent,
      child: ConstrainedBox(
        // 设置宽度为无限大，撑满父组件，否则Stack获取不到高度，会报错
        constraints: BoxConstraints(minWidth: double.infinity),
        child: Stack(
          alignment: Alignment.center,
          children: [
            // 返回按钮
            Positioned(
              left: 16.0,
              child: GestureDetector(
                onTap: controller.clickBack,
                child: Assets.images.iconWhiteBackArrow.image(
                  width: 24.w,
                  height: 24.h,
                ),
              ),
            ),
            // TabBar
            Positioned(
              child: Text(
                StringName.intimacyAnalyse,
                style: TextStyle(
                  color: ColorName.white,
                  fontSize: 17.sp,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 上传步骤卡片
  Widget _buildUploadStepCard() {
    return Obx(() {
      return UploadStepCard(
        sceneType: controller.uploadSceneType,
        topTitleWidget: StepTitleWidget(
          stepLabel: StringFormatUtil.formatStr(
            StringName.intimacyAnalyseStep,
            1.toString(),
          ),
          stepTitle: StringName.intimacyAnalyseStepTitleSelectImage,
          stepDesc: StringName.intimacyAnalyseUploadCardTip,
        ),
        // 底部，添加上当前的亲密关系
        bottomChild: _buildRecommendIntimacy(),
        onClickAddCallback: () {
          if (Get.context != null) {
            controller.clickUploadBtn(Get.context!);
          }
        },
        // 上传信息列表
        imageUploadInfoList: controller.uploadInfoList.value,
        onClickDeleteCallback: (uploadInfo) {
          controller.deleteUploadInfo(uploadInfo);
        },
      );
    });
  }

  /// 预测方向步骤卡片
  Widget _buildPredictionDirectionStepCard() {
    return StepCard(
      bgImageProvider: Assets.images.bgIntimacyAnalyseNormalCard.provider(),
      topTitleWidget: StepTitleWidget(
        stepLabel: StringFormatUtil.formatStr(
          StringName.intimacyAnalyseStep,
          2.toString(),
        ),
        stepTitle: StringName.intimacyAnalyseStepTitleSelectPredictionDirection,
        stepDesc: StringName.intimacyAnalysePredictionDirectionCardTip,
      ),
      contentWidget: Column(
        children: [
          SizedBox(height: 14.h),
          Container(
            margin: EdgeInsets.only(left: 12.w, right: 12.w),
            padding: EdgeInsets.only(
              left: 12.w,
              top: 12.h,
              right: 12.w,
              bottom: 12.h,
            ),
            decoration: BoxDecoration(
              color: ColorName.white,
              borderRadius: BorderRadius.circular(16.r),
            ),
            child: Obx(() {
              return Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 添加预测方向按钮
                  Visibility(
                    visible: controller.isCanCustomDirection.value,
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        _buildAddDirectionBtn(),
                        SizedBox(height: 22.h),
                      ],
                    ),
                  ),
                  // 添加选项行
                  for (var optionConfig
                      in controller.directionOptionSelectConfigList)
                    _buildOptionRow(optionConfig),
                ],
              );
            }),
          ),
        ],
      ),
    );
  }

  /// 分析结果卡片
  Widget _buildAnalysisResultCard() {
    return Obx(() {
      Mode mode = Mode.preview;
      return StepCard(
        bgImageProvider: StepCardUtil.getCardBgImageProvider(
          itemCount: controller.uploadInfoList.length,
          sceneType: controller.uploadSceneType,
          mode: mode,
        ),
        topTitleWidget: StepTitleWidget(
          stepTitle: StringName.intimacyAnalyseAnalysisResult,
        ),
        topIconWidget: Assets.images.iconIntimacyAnalysisResultTop.image(
          height: 63.h,
          width: 103.w,
        ),
        // 顶部图标的位置
        topIconWidgetLocation: StepCardUtil.calculateTopIconWidgetLocation(
          itemCount: controller.uploadInfoList.length,
          sceneType: controller.uploadSceneType,
          mode: mode
        ),
        contentWidget: Column(
          children: [
            // 图片九宫格
            Container(
              margin: EdgeInsets.only(left: 12.w, right: 12.w),
              padding: EdgeInsets.only(
                left: 12.w,
                top: 12.h,
                right: 12.w,
                bottom: 12.h,
              ),
              decoration: BoxDecoration(
                color: ColorName.white,
                borderRadius: BorderRadius.circular(16.r),
              ),
              child: UploadNineGrid(
                mode: mode,
                // 上传的图片列表
                imageUploadInfoList: controller.uploadInfoList,
                spacing: 8.0,
              ),
            ),
            SizedBox(height: 10.h),
            Container(
              margin: EdgeInsets.symmetric(horizontal: 12.w),
              child: Row(
                children: [
                  // 预测方向
                  _buildDirectionResult(),
                  SizedBox(width: 12.w),
                  // 模型
                  _buildAiModelResult(),
                ],
              ),
            ),
          ],
        ),
      );
    });
  }

  /// 分析报告
  Widget _buildAnalysisReport() {
    return Obx(() {
      return Column(
        children: [
          SizedBox(height: 12.h),
          IntimacyAnalyseReportWidget(
            // 分析结果
            intimacyAnalyzeResult: controller.intimacyAnalyzeResult.value,
            unlock: controller.memberInfo.value?.isMember ?? false,
            isReportCreating: controller.isResultGenerating.value,
          ),
        ],
      );
    });
  }

  /// 预测方向结果
  Widget _buildDirectionResult() {
    return Obx(() {
      // 当前用户的头像
      String myAvatarUrl = controller.userInfo.value?.imageUrl ?? "";
      // 对方用户的头像
      String taAvatarUrl = controller.currentKeyboardInfo.value?.imageUrl ?? "";
      // 当前用户的性别
      GenderType? myGender = GenderType.fromType(
        controller.userInfo.value?.gender,
      );
      // 对方用户的性别
      GenderType? taGender = GenderType.fromType(
        controller.currentKeyboardInfo.value?.gender,
      );
      return Expanded(
        child: Container(
          padding: EdgeInsets.symmetric(vertical: 10.h, horizontal: 10.w),
          decoration: BoxDecoration(
            color: ColorName.white,
            borderRadius: BorderRadius.circular(14.r),
          ),
          child: Row(
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 标题
                  Text(
                    StringName.intimacyAnalysePredictionDirection,
                    style: TextStyle(
                      color: ColorName.black47,
                      fontSize: 12.sp,
                      fontWeight: FontWeight.w400,
                    ),
                  ),
                  SizedBox(height: 4.h),
                  // 结果
                  Row(
                    children: [
                      // 图标
                      Assets.images.iconDirectionResult.image(
                        height: 14.w,
                        width: 14.w,
                      ),
                      SizedBox(width: 2.w),
                      // 结果文字
                      Text(
                        controller.currentDirectionOption.value,
                        style: TextStyle(
                          color: ColorName.black80,
                          fontSize: 13.sp,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
              Expanded(child: SizedBox()),
              // 亲密关系头像
              IntimacyUserWidget(
                width: 60.w,
                height: 30.h,
                avatarSize: 30.0,
                myAvatar: myAvatarUrl,
                taAvatar: taAvatarUrl,
                myGender: myGender,
                taGender: taGender,
                avatarBorderWidth: 1.w,
                loveSize: 17.w,
              ),
            ],
          ),
        ),
      );
    });
  }

  /// Ai模型结果
  Widget _buildAiModelResult() {
    return Obx(() {
      return Expanded(
        child: Container(
          padding: EdgeInsets.symmetric(vertical: 10.h, horizontal: 10.w),
          decoration: BoxDecoration(
            color: ColorName.white,
            borderRadius: BorderRadius.circular(14.r),
          ),
          child: Row(
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 标题
                  Text(
                    StringName.intimacyAnalyseModel,
                    style: TextStyle(
                      color: ColorName.black47,
                      fontSize: 12.sp,
                      fontWeight: FontWeight.w400,
                    ),
                  ),
                  SizedBox(height: 4.h),
                  // 结果文字
                  Text(
                    controller.currentAiModel.value?.name ?? "",
                    style: TextStyle(
                      color: ColorName.black80,
                      fontSize: 13.sp,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ],
              ),
              Expanded(child: SizedBox()),
              // Ai模型图片
              Assets.images.iconAiModel.image(width: 38, height: 30),
            ],
          ),
        ),
      );
    });
  }

  /// 添加预测方向按钮
  Widget _buildAddDirectionBtn() {
    return Container(
      // 左侧对齐
      alignment: Alignment.centerLeft,
      child: GestureDetector(
        onTap: () {
          controller.addDirection();
        },
        child: DottedBorder(
          // 虚线颜色
          color: ColorName.bgAddPredictionDirection,
          // 虚线密集程度
          dashPattern: [5, 3],
          // 线条宽度
          strokeWidth: 1.0.w,
          // 圆角矩形，要使用 RRect 类型，才能有效
          borderType: BorderType.RRect,
          // 圆角半径
          radius: Radius.circular(31.r),
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
            child: Row(
              // 包裹内容
              mainAxisSize: MainAxisSize.min,
              // 文字和图标都居中
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                // 图标
                Assets.images.iconAddPredictionDirection.image(
                  width: 18.w,
                  height: 18.w,
                ),
                SizedBox(width: 2.w),
                // 文字
                Text(
                  StringName.intimacyAnalyseAddPredictionDirection,
                  style: TextStyle(
                    color: ColorName.uploadAddText,
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w400,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 构建一行选择选项行
  Widget _buildOptionRow(OptionSelectConfig config) {
    return Column(
      children: [
        // 选择项
        OptionSelectWidget(
          optionSelect: config,
          optionSelectCallback: (
            OptionSelectConfig rowConfig,
            OptionSelectItem optionItem,
          ) {
            controller.selectDirectionOption(rowConfig, optionItem);
          },
        ),
        SizedBox(height: 20.h),
      ],
    );
  }

  /// 推荐的亲密关系
  Widget _buildRecommendIntimacy() {
    return Obx(() {
      // 当前用户的头像
      String myAvatarUrl = controller.userInfo.value?.imageUrl ?? "";
      // 对方用户的头像
      String taAvatarUrl = controller.currentKeyboardInfo.value?.imageUrl ?? "";
      // 当前用户的性别
      GenderType? myGender = GenderType.fromType(
        controller.userInfo.value?.gender,
      );
      // 对方用户的性别
      GenderType? taGender = GenderType.fromType(
        controller.currentKeyboardInfo.value?.gender,
      );
      return Container(
        width: double.infinity,
        margin: EdgeInsets.only(left: 14.w, right: 14.w),
        // 圆角背景
        decoration: BoxDecoration(
          // 渐变背景
          gradient: LinearGradient(
            colors: [
              ColorName.bgIntimacyRelationColor1,
              ColorName.bgIntimacyRelationColor2,
            ],
            begin: Alignment.centerLeft,
            end: Alignment.centerRight,
          ),
          shape: BoxShape.rectangle,
          border: Border.all(color: ColorName.white80, width: 1.w),
          borderRadius: BorderRadius.all(Radius.circular(23.r)),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              children: [
                SizedBox(width: 6.w),
                // 用户亲密头像
                IntimacyUserWidget(
                  width: 68.w,
                  height: 34.h,
                  avatarSize: 34.0,
                  myAvatar: myAvatarUrl,
                  taAvatar: taAvatarUrl,
                  myGender: myGender,
                  taGender: taGender,
                  avatarBorderWidth: 1.w,
                  loveSize: 19.w,
                ),
                SizedBox(width: 4.w),
                Text(
                  StringName.mySelf,
                  style: TextStyle(
                    color: ColorName.black80,
                    fontSize: 11.sp,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                SizedBox(width: 4.w),
                Text(
                  StringName.and,
                  style: TextStyle(
                    color: ColorName.black41,
                    fontSize: 11.sp,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                SizedBox(width: 4.w),
                Text(
                  controller.currentKeyboardInfo.value?.name ?? "",
                  style: TextStyle(
                    color: ColorName.black80,
                    fontSize: 11.sp,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                SizedBox(width: 5.w),
                GradientText(
                  // 渐变颜色
                  colors: [
                    ColorName.intimacyRelationColor1,
                    ColorName.intimacyRelationColor2,
                  ],
                  child: Text(
                    StringName.intimacyRelation,
                    style: TextStyle(
                      fontSize: 11.sp,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
              ],
            ),
            // 切换按钮
            GestureDetector(
              onTap: () {
                controller.switchTaTest();
              },
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 9.w, vertical: 6.h),
                margin: EdgeInsets.only(right: 8.w, top: 8.h, bottom: 8.h),
                decoration: BoxDecoration(
                  color: ColorName.white,
                  borderRadius: BorderRadius.circular(22.r),
                ),
                child: Text(
                  StringName.intimacyAnalyseSwitchTaTest,
                  style: TextStyle(
                    color: ColorName.black80,
                    fontSize: 12.sp,
                    fontWeight: FontWeight.w400,
                  ),
                ),
              ),
            ),
          ],
        ),
      );
    });
  }

  /// 底部操作按钮
  Widget _buildBottomActionBtn() {
    // 上传页，显示Ai模型切换按钮和下一步按钮
    if (controller.isUploadPage.value) {
      return Container(
        width: double.maxFinite,
        margin: EdgeInsets.only(
          left: 13.w,
          top: 8.h,
          right: 13.w,
          bottom: 20.h,
        ),
        child: ActionBtn(
          leftBtn: _buildAiModelSwitchBtn(),
          spaceWidget: SizedBox(width: 10.w),
          rightBtn: _buildNextBtn(),
        ),
      );
    } else {
      // 结果页
      if (controller.isResultGenerating.value) {
        // 生成中，显示分析中的按钮
        return Container(
          width: double.maxFinite,
          margin: EdgeInsets.only(
            left: 13.w,
            top: 8.h,
            right: 13.w,
            bottom: 20.h,
          ),
          child: _buildAnalyseBtn(true),
        );
      } else {
        // 生成完成，判断是否已解锁
        bool isUnlock = controller.memberInfo.value?.isMember ?? false;
        if (!isUnlock) {
          // 未解锁，显示立即分析按钮
          return Container(
            width: double.maxFinite,
            margin: EdgeInsets.only(
              left: 13.w,
              top: 8.h,
              right: 13.w,
              bottom: 20.h,
            ),
            child: _buildAnalyseBtn(false),
          );
        } else {
          // 已解锁，生成定制人设按钮
          return Container(
            width: double.maxFinite,
            margin: EdgeInsets.only(
              left: 13.w,
              top: 8.h,
              right: 13.w,
              bottom: 20.h,
            ),
            child: _buildGenerateCharacterBtn(),
          );
        }
      }
    }
  }

  /// Ai模型切换按钮
  Widget _buildAiModelSwitchBtn() {
    return Builder(
      builder: (context) {
        return GestureDetector(
          key: _aiModelSwitchBtnAnchorKey,
          onTap: () {
            // 显示Ai模型切换Popup弹窗
            if (AiModelSelectPopup.isShowing()) {
              AiModelSelectPopup.dismiss();
              return;
            }
            // 切换模型
            AiModelSelectPopup.show(
              _aiModelSwitchBtnAnchorKey,
              context,
              aiModelList: controller.aiModelList.toList(),
              currentAiModel: controller.currentAiModel.value!,
              onChooseAiModelCallback: (AiModel newAiModel) {
                controller.switchAiModel(newAiModel);
              },
            );
          },
          child: Container(
            padding: EdgeInsets.symmetric(vertical: 12.h, horizontal: 14.w),
            decoration: BoxDecoration(
              color: ColorName.white,
              borderRadius: BorderRadius.all(Radius.circular(30.w)),
              border: Border.all(
                color: ColorName.bgAiModelSwitchBorderBtn,
                width: 1.w,
              ),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Obx(() {
                  return
                  // 文字
                  GradientText(
                    colors: [
                      ColorName.aiModelSwitchBtnColor1,
                      ColorName.aiModelSwitchBtnColor2,
                    ],
                    child: Text(
                      controller.currentAiModel.value?.name ?? "",
                      style: TextStyle(
                        fontSize: 14.sp,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  );
                }),
                SizedBox(width: 8.w),
                // 箭头
                Assets.images.iconModeSwitchArrow.image(
                  width: 15.w,
                  height: 15.w,
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  /// 下一步按钮
  Widget _buildNextBtn() {
    return Obx(() {
      return Container(
        padding: EdgeInsets.only(top: 13.h, bottom: 13.h),
        child: GradientTextBtn.withUnlock(
          controller.memberInfo.value?.isMember ?? false,
          text: StringName.nextStep,
          color: ColorName.colorBrand,
          onPressed: () {
            controller.clickNextBtn(false);
          },
        ),
      );
    });
  }

  /// 分析按钮
  /// [isAnalysing] 是否正在分析中
  Widget _buildAnalyseBtn(bool isAnalysing) {
    return Obx(() {
      // 是否vip
      bool isVip = controller.memberInfo.value?.isMember ?? false;
      // 如果正在分析中，不显示锁，否则按当前用户的vip状态来显示
      bool isUnlock = isAnalysing ? true : isVip;
      return Container(
        padding: EdgeInsets.only(top: 7.h, bottom: 6.h),
        child: GradientTextBtn.withUnlock(
          isUnlock,
          text:
              isAnalysing
                  ? StringName.intimacyAnalyseAnalysisIng
                  : StringName.intimacyAnalyseAnalysisNow,
          color: ColorName.colorBrand,
          desc: StringName.intimacyAnalyseAnalysisUseAiTip,
          radius: 30.r,
          padding: EdgeInsets.symmetric(vertical: 7.h),
          onPressed: () {
            if (isAnalysing) {
              controller.clickAnalysingBtn();
            } else {
              controller.clickNextBtn(true);
            }
          },
        ),
      );
    });
  }

  /// 生成定制人设按钮
  Widget _buildGenerateCharacterBtn() {
    return Container(
      padding: EdgeInsets.only(top: 7.h, bottom: 6.h),
      child: GradientTextBtn(
        StringName.intimacyGenerateCharacter,
        color: ColorName.colorBrand,
        onPressed: () {
          controller.clickGenerateCharacterBtn();
        },
      ),
    );
  }

  /// 构建卡片列表
  Widget _buildCardList() {
    return Obx(() {
      // 是否已解锁
      bool isUnlock = controller.memberInfo.value?.isMember ?? false;

      // 列表，距离底部的距离
      double listBottomSpace;
      // 上传阶段
      if (controller.isUploadPage.value) {
        listBottomSpace = 90.h;
      } else {
        // 报告已生成
        if (controller.intimacyAnalyzeResult.value != null) {
          listBottomSpace = 90.h;
        } else {
          // 未生成报告，未解锁
          if (isUnlock) {
            listBottomSpace = 20.h;
          } else {
            listBottomSpace = 90.h;
          }
        }
      }

      // 上传页
      if (controller.isUploadPage.value) {
        return Column(
          children: [
            // 上传卡片
            _buildUploadStepCard(),
            // 预测方向卡片
            _buildPredictionDirectionStepCard(),
            SizedBox(height: listBottomSpace),
          ],
        );
      } else {
        // 报告页
        return Column(
          children: [
            // 分析结果卡片
            _buildAnalysisResultCard(),
            // 报告结果卡片
            _buildAnalysisReport(),
            // 内容距离底部的距离
            SizedBox(height: listBottomSpace),
          ],
        );
      }
    });
  }

  /// 内容
  Widget _buildContent() {
    return Expanded(
      child: Stack(
        children: [
          // 卡片列表
          SingleChildScrollView(child: Column(children: [_buildCardList()])),
          // 底部操作按钮
          Positioned(
            left: 0,
            right: 0,
            bottom: 0,
            child: Obx(() {
              return _buildBottomActionBtn();
            }),
          ),
        ],
      ),
    );
  }
}
