import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../../common/api/index.dart';
import '../../../../common/models/index.dart';
import '../../../../common/routers/index.dart';
import '../../../../common/style/index.dart';
import '../../../../common/utils/index.dart';
import '../../../../common/widgets/index.dart';
import 'index.dart';

class PublishSubjectPage extends GetView<PublishSubjectController> {
  const PublishSubjectPage({Key? key}) : super(key: key);

  /// 发帖
  static Future<void> toPublishSubject(SectionInfoList sectionInfo) async {
    await Get.toNamed(O2OARoutes.appBBSSubjectPublish,
        arguments: {"sectionInfo": sectionInfo});
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<PublishSubjectController>(
      builder: (_) {
        return Scaffold(
          appBar: AppBar(
            title: Text('bbs_subject_publish'.tr),
            actions: [
              TextButton(
                  onPressed: () => controller.postSubject(),
                  child: Text('bbs_subject_publish_send'.tr,
                      style: AppTheme.whitePrimaryTextStyle))
            ],
          ),
          body: SafeArea(
            child: _buildView(context),
          ),
        );
      },
    );
  }

  // 主视图
  Widget _buildView(BuildContext context) {
    return Column(
      children: [
        subjectTitleView(context),
        const SizedBox(height: 10),
        Expanded(flex: 1, child: subjectContentView(context)),
        _bottomBarView(context)
      ],
    );
  }

  /// 帖子标题
  Widget subjectTitleView(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(10),
      child: TextField(
        autofocus: true,
        focusNode: controller.subjectTitleInputNode,
        controller: controller.subjectTitleInputController,
        decoration: InputDecoration(
            isDense: true,
            hintText: 'bbs_subject_publish_title_label'.tr,
            filled: true,
            fillColor: Theme.of(context).colorScheme.background,
            border: InputBorder.none),
        style: Theme.of(context).textTheme.bodyLarge,
        textInputAction: TextInputAction.next,
      ),
    );
  }

  /// 帖子摘要
  Widget subjectSummaryView(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(10),
      child: TextField(
        autofocus: true,
        focusNode: controller.subjectSummaryInputNode,
        controller: controller.subjectSummaryInputController,
        decoration: InputDecoration(
            isDense: true,
            hintText: 'bbs_subject_publish_summary_label'.tr,
            filled: true,
            fillColor: Theme.of(context).colorScheme.background,
            border: InputBorder.none),
        style: Theme.of(context).textTheme.bodyMedium,
        textInputAction: TextInputAction.done,
      ),
    );
  }

  /// 帖子内容
  Widget subjectContentView(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(10),
      child: Container(
          decoration:
              BoxDecoration(color: Theme.of(context).colorScheme.background),
          child: TextField(
            focusNode: controller.subjectContentInputNode,
            controller: controller.subjectContentInputController,
            maxLines: null,
            decoration: InputDecoration(
                isDense: true,
                hintText: 'bbs_subject_publish_content_label'.tr,
                hintStyle: Theme.of(context).textTheme.bodySmall,
                filled: true,
                fillColor: Theme.of(context).colorScheme.background,
                border: InputBorder.none),
            style: Theme.of(context).textTheme.bodyMedium,
            textInputAction: TextInputAction.newline,
          )),
    );
  }

  Widget _bottomBarView(BuildContext context) {
    return Container(
        color: Theme.of(context).colorScheme.background,
        child: Column(
          children: [
            const Divider(height: 1, color: AppColor.borderColor),
            const SizedBox(height: 5),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Expanded(
                    child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    IconButton(
                        onPressed: controller.showMoreSubjectInfoView,
                        icon: const Icon(Icons.control_point, size: 36))
                  ],
                )),
                const SizedBox(width: 8),
                IconButton(
                    onPressed: controller.takePhoto,
                    icon: const Icon(Icons.camera_alt, size: 36)),
                const SizedBox(width: 8),
                IconButton(
                    onPressed: controller.addImage,
                    icon: const Icon(Icons.image, size: 36)),
                const SizedBox(width: 8),
              ],
            ),
            _imageListView(context),
            _moreSubjectInfoView(context),
            const SizedBox(height: 5),
          ],
        ));
  }

  /// 更多内容
  /// 匿名、摘要、类型等
  Widget _moreSubjectInfoView(BuildContext context) {
    return Obx(() => controller.state.openMore
        ? Column(
            children: [
              const SizedBox(height: 5),
              O2UI.sectionOutBox(
                  O2UI.lineWidget(controller.state.category, const Text(''),
                      ontap: controller.changeCategory),
                  context),
              const Divider(height: 1),
              O2UI.sectionOutBox(
                  O2UI.lineWidget(controller.state.subjectType, const Text(''),
                      ontap: controller.changeSubjectType),
                  context),
              const Divider(height: 1),
              subjectSummaryView(context),
              const Divider(height: 1),
              Row(
                children: [
                  Checkbox(
                    value: controller.state.anonymousSubject,
                    onChanged: (value) =>
                        controller.changeAnonymousSubject(value ?? false),
                  ),
                  const SizedBox(width: 5),
                  Text('bbs_subject_publish_anonymous_label'.tr)
                ],
              )
            ],
          )
        : Container());
  }

  /// 显示图片区域
  Widget _imageListView(BuildContext context) {
    return Obx(() {
      if (controller.state.imageMap.isNotEmpty) {
        return SizedBox(
            height: 108,
            child: GridView.count(
              shrinkWrap: true,
              crossAxisCount: 4,
              mainAxisSpacing: 10.0, //设置上下之间的间距(Axis.horizontal设置左右之间的间距)
              crossAxisSpacing: 10.0, //设置左右之间的间距(Axis.horizontal设置上下之间的间距)
              childAspectRatio: 0.8, //设置宽高比
              children: controller.state.imageMap.values.map((element) {
                return GestureDetector(
                    onTap: () => controller.clickImageItem(element),
                    child: imageItemView(context, element));
              }).toList(),
            ));
      }
      return Container();
    });
  }

  Widget imageItemView(BuildContext context, ReplyImageItem item) {
    Image imageView;
    Map<String, String> headers = {};
    headers[O2ApiManager.instance.tokenName] =
        O2ApiManager.instance.o2User?.token ?? '';
    Align loadingOrDelete;
    if (item.fileId != null && item.fileId!.isNotEmpty) {
      String imageUrl =
          BBSAssembleControlService.to.getBBSAttachmentURL(item.fileId!);
      imageView = Image(
          image: NetworkImage(imageUrl, headers: headers),
          height: 64,
          fit: BoxFit.fill);
      loadingOrDelete = const Align(
          alignment: Alignment.topRight,
          child: Padding(
              padding: EdgeInsets.all(5),
              child: Icon(Icons.do_not_disturb_on,
                  color: Colors.red, size: 36)));
    } else {
      imageView = Image(
          image: FileImage(File(item.fileLocalPath!)),
          height: 64,
          fit: BoxFit.fill);
      loadingOrDelete = const Align(
        alignment: Alignment.center,
        child: CircularProgressIndicator(),
      );
    }
    return Stack(children: [
      Align(alignment: Alignment.center, child: imageView),
      loadingOrDelete
    ]);
  }
}
