import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:keyboard/base/base_view.dart';
import 'package:keyboard/widget/markdown/markdown_viewer.dart';

import '../../../../data/bean/option_select_config.dart';
import '../../../../data/bean/option_select_item.dart';
import '../../../../resource/assets.gen.dart';
import '../../../../resource/colors.gen.dart';
import '../../../../resource/string.gen.dart';
import '../../../../utils/step_card_util.dart';
import '../../../../widget/gradient_btn.dart';
import '../../intimacy_analyse_upload/widget/upload_nine_grid.dart';
import '../../widget/creating_loading_widget.dart';
import '../../widget/option_select_widget.dart';
import '../../widget/step/upload_step_card.dart';
import '../../widget/step_card.dart';
import 'conversation_analysis_controller.dart';

/// 对话分析Tab页
class ConversationAnalysisView
    extends BaseView<ConversationAnalysisController> {
  const ConversationAnalysisView({super.key});

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

  @override
  Widget buildBody(BuildContext context) {
    return Stack(
      children: [
        // 内容列表
        _buildContentList(),
        // 上传截图按钮
        Positioned.fill(
          child: Align(
            alignment: Alignment.bottomCenter,
            child: Obx(() {
              return _buildBottomLayout(context);
            }),
          ),
        ),
      ],
    );
  }

  /// 内容列表
  Widget _buildContentList() {
    return Obx(() {
      Widget contentWidget;
      // 是否例子阶段
      bool isSample = controller.uploadInfoList.isEmpty;
      if (isSample) {
        // 例子列表
        contentWidget = Column(
          children: [
            // 上传聊天记录例子卡片
            _buildChatRecordSampleCard(),
          ],
        );
      } else {
        // 上传页
        if (controller.isUploadPage.value) {
          contentWidget = Column(
            children: [
              // 上传聊天记录卡片
              _buildUploadCard(),
              SizedBox(height: 14.h),
              // 选项卡片
              _buildOptionCard(),
              // 距离底部有一定间距
              SizedBox(height: 90.h),
            ],
          );
        } else {
          // 已出结果
          contentWidget = Column(
            children: [
              // 分析结果卡片
              _buildAnalysisResultCard(),
              SizedBox(height: 12.h),
              // 分析结果Markdown卡片
              _buildMarkdownAnalysisResultCard(),
              // 距离底部有一定间距
              SizedBox(height: 90.h),
            ],
          );
        }
      }
      return SingleChildScrollView(child: contentWidget);
    });
  }

  /// 上传步骤卡片
  Widget _buildUploadCard() {
    return Obx(() {
      return UploadStepCard(
        sceneType: controller.uploadSceneType,
        topTitleWidget: StepTitleWidget(
          stepTitle: StringName.intimacyConversationAnalysis,
          stepDesc: StringName.intimacyConversationAnalysisCardTip,
        ),
        onClickAddCallback: () {
          if (Get.context != null) {
            controller.clickUploadBtn(Get.context!);
          }
        },
        imageUploadInfoList: controller.uploadInfoList.value,
        onClickDeleteCallback: (uploadInfo) {
          controller.deleteUploadInfo(uploadInfo);
        },
      );
    });
  }

  /// 选项卡片
  Widget _buildOptionCard() {
    return Container(
      width: double.maxFinite,
      margin: EdgeInsets.only(left: 14.w, right: 14.w),
      // 圆角背景
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [Color(0xFFEFE9FF), Color(0xFFFBFAFF)],
          begin: Alignment.topCenter,
          end: Alignment.bottomRight,
        ),
        shape: BoxShape.rectangle,
        border: Border.all(color: ColorName.white80, width: 1.w),
        borderRadius: BorderRadius.all(Radius.circular(20.r)),
      ),
      child: Column(
        children: [
          Container(
            margin: EdgeInsets.only(
              left: 12.w,
              top: 17.h,
              right: 12.w,
              bottom: 12.h,
            ),
            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(
                children: [
                  // 添加选项行
                  for (var optionConfig in controller.optionSelectConfigList)
                    _buildOptionRow(optionConfig),
                ],
              );
            }),
          ),
        ],
      ),
    );
  }

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

  /// 分析结果卡片
  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.value,
                spacing: 8.0,
              ),
            ),
            SizedBox(height: 10.h),
          ],
        ),
      );
    });
  }

  /// 分析结果，Markdown文档卡片
  Widget _buildMarkdownAnalysisResultCard() {
    return Container(
      width: double.maxFinite,
      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: Column(
        // 左对齐
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题
          Container(
            width: double.maxFinite,
            height: 20.h,
            margin: EdgeInsets.only(top: 16.h),
            child: Stack(
              clipBehavior: Clip.none,
              children: [
                // 底部的横线
                Positioned(
                  left: 15.w,
                  bottom: 0,
                  child: Container(
                    width: 96.w,
                    height: 7.h,
                    color: Color(0xFFCEB6FF),
                  ),
                ),
                Positioned(
                  left: 0,
                  bottom: -2.h,
                  child: Container(
                    margin: EdgeInsets.only(left: 14.w, top: 16.h),
                    child: Text(
                      StringName.intimacyAnalyseTaDemand,
                      style: TextStyle(
                        color: ColorName.black80,
                        fontSize: 16.sp,
                        fontWeight: FontWeight.w700,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          // Markdown内容
          Container(
            margin: EdgeInsets.only(
              left: 12.w,
              top: 14.h,
              right: 12.w,
              bottom: 12.h,
            ),
            // 圆角背景
            decoration: BoxDecoration(
              color: ColorName.white,
              borderRadius: BorderRadius.circular(20.r),
            ),
            child: Obx(() {
              // 开始分析中的状态
              if (controller.isResultGenerating.value &&
                  controller.reportData.value.isEmpty) {
                return Container(
                  padding: EdgeInsets.only(top: 33.h, bottom: 52.h),
                  child: CreatingLoadingWidget(
                    tipTextWidget: Text(
                      StringName.intimacyAnalyseIng2,
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: ColorName.black60,
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                  ),
                );
              } else {
                // 分析进行中
                return MarkdownViewer(
                  content: controller.reportData.value,
                  enableContentScroll: false,
                );
              }
            }),
          ),
        ],
      ),
    );
  }

  /// 上传截图例子卡片
  Widget _buildChatRecordSampleCard() {
    Mode mode = controller.uploadInfoList.isEmpty ? Mode.preview : Mode.edit;
    return StepCard(
      bgImageProvider: StepCardUtil.getCardBgImageProvider(
        itemCount: controller.uploadInfoList.length,
        sceneType: controller.uploadSceneType,
        mode: mode,
      ),
      topTitleWidget: StepTitleWidget(
        stepTitle: StringName.intimacyConversationAnalysis,
        stepDesc: StringName.intimacyConversationAnalysisCardTip,
      ),
      topIconWidget: Assets.images.iconIntimacyAnalyseUploadTop.image(
        height: 63.h,
        width: 103.w,
      ),
      // 顶部图标的位置
      topIconWidgetLocation: StepCardUtil.calculateTopIconWidgetLocation(
        itemCount: controller.uploadInfoList.length,
        sceneType: controller.uploadSceneType,
        mode: mode,
      ),
      contentWidget: Column(
        children: [
          Container(
            width: 312.w,
            height: 314.h,
            margin: EdgeInsets.only(left: 12.w, top: 17.h, right: 12.w),
            padding: EdgeInsets.all(12.w),
            decoration: BoxDecoration(
              color: ColorName.white,
              borderRadius: BorderRadius.circular(16.r),
            ),
            child: Stack(
              children: [
                Positioned.fill(
                  child: Container(
                    padding: EdgeInsets.all(12.w),
                    child: ClipRRect(
                      // 图片裁切成圆角
                      borderRadius: BorderRadius.circular(16.r),
                      child: Assets.images.iconConversationAnalysisSampleImage
                          .image(
                            width: 288.w,
                            height: 290.h,
                            fit: BoxFit.fitWidth,
                          ),
                    ),
                  ),
                ),
                Positioned(
                  right: 0,
                  bottom: 0,
                  child: Container(
                    padding: EdgeInsets.all(6.w),
                    decoration: BoxDecoration(
                      color: ColorName.black28,
                      borderRadius: BorderRadius.circular(9.r),
                    ),
                    child: Text(
                      StringName.intimacyAnalyseSampleImage,
                      style: TextStyle(
                        color: ColorName.white,
                        fontSize: 12.sp,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 解锁按钮
  Widget _buildUnlockBtn(BuildContext context) {
    return Obx(() {
      return Container(
        margin: EdgeInsets.symmetric(horizontal: 16.w),
        width: double.maxFinite,
        child: GradientTextBtn.withUnlock(
          controller.userInfo.value?.isMember ?? false,
          onPressed: () {
            controller.clickUnlockBtn(context);
          },
        ),
      );
    });
  }

  /// 上传截图按钮
  Widget _buildUploadScreenshotBtn(BuildContext context) {
    return _buildGradientBtn(
      btnText: StringName.intimacyUploadScreenshot,
      onPressed: () {
        controller.clickUploadBtn(context);
      },
    );
  }

  /// 查看分析按钮
  Widget _buildLookAnalyseBtn(BuildContext context) {
    return _buildGradientBtn(
      btnText: StringName.intimacyAnalyseLookAnalyse,
      onPressed: () {
        controller.clickLookAnalyseBtn(context);
      },
    );
  }

  /// 渐变按钮
  Widget _buildGradientBtn({
    required String btnText,
    required VoidCallback onPressed,
  }) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      width: double.infinity,
      child: GradientTextBtn(btnText, onPressed: onPressed),
    );
  }

  /// 底部布局
  Widget _buildBottomLayout(BuildContext context) {
    Widget btn;
    // 是否例子阶段
    bool isSample = controller.uploadInfoList.isEmpty;
    // 例子阶段，则显示上传截图按钮
    if (isSample) {
      btn = _buildUploadScreenshotBtn(context);
    } else {
      // 已解锁，显示分析按钮
      if (controller.userInfo.value?.isMember ?? false) {
        // 如果正在生成中，则不显示按钮
        if (controller.isResultGenerating.value) {
          return SizedBox.shrink();
        } else if (controller.reportData.value.isNotEmpty) {
          // 已生成报告，隐藏按钮
          btn = SizedBox.shrink();
        } else {
          btn = _buildLookAnalyseBtn(context);
        }
      } else {
        // 未解锁，显示带锁的按钮
        btn = _buildUnlockBtn(context);
      }
    }
    return Column(
      // 高度包裹内容
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 操作按钮
        btn,
        SizedBox(height: 20.h),
      ],
    );
  }
}
