/*
 * @Author: LiOS
 * @Date: 2020-06-17 11:42:05
 * @LastEditors  : WuWei
 * @LastEditTime : 2023-07-11 13:58:54
 * @Description: 发布通知页面，保存后进入草稿预览页面；若发布成功跳回通知列表
 */

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../src/view_models/notice_add_store.dart';
import 'package:wisdom_cli/wisdom_cli.dart';

class AddNoticePage extends StatelessWidget {
  const AddNoticePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return _PageView();
  }
}

class _PageView extends StatefulWidget {
  _PageView({Key? key}) : super(key: key);
  @override
  _PageViewState createState() => _PageViewState();
}

class _PageViewState extends State<_PageView> {
  @override
  void dispose() {
    Get.delete<NoticeAddStore>();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final NoticeAddStore store = Get.isRegistered<NoticeAddStore>()
        ? Get.find<NoticeAddStore>()
        : Get.put(NoticeAddStore());
    final colorScheme = WTheme.of(context).colorScheme;
    return Scaffold(
      appBar: WAppBar(
        brightness: Brightness.light,
        title: WisText(
          '编辑公告',
          size: 19.pt,
          weight: FontWeight.w600,
          color: colorScheme.mainTitle,
        ),
        iconTheme: IconThemeData(
          color: colorScheme.mainTitle,
          size: 19.pt,
        ),
        backgroundColor: Colors.white,
      ),
      body: ListView(
        children: <Widget>[
          _BuildPage(store: store),
        ],
      ),
    );
  }
}

class _BuildPage extends GetView<NoticeAddStore> {
  const _BuildPage({Key? key, this.store}) : super(key: key);
  final NoticeAddStore? store;

  @override
  Widget build(BuildContext context) {
    final FocusNode titleNode = FocusNode();
    final FocusNode themeNode = FocusNode();
    final FocusNode contentNode = FocusNode();

    const double MARGIN = 10.0;
    const double PADDING = 20.0;
    const double LABEL_FONT_SIZE = 15.0;
    const double HINTEXT_FONT_SIZE = 14.0;
    const double CORNER_RADIUS = 0.0;
    const double PRIMARY_BUTTON_HEIGHT = 44.0;
    const Color BORDER_COLOR = Color.fromARGB(255, 240, 240, 240);
    final TextStyle hintStyle =
        TextStyle(fontSize: HINTEXT_FONT_SIZE, fontWeight: FontWeight.w400);
    final TextEditingController titleController = TextEditingController();
    final TextEditingController themeController = TextEditingController();

    var _title = ''.obs;
    var _theme = ''.obs;

    Widget _buildPrimaryButton(
        String title, double height, Function()? onPressed) {
      final style = WTheme.of(context);
      final colorScheme = style.colorScheme;
      return WisCard(
        margin: EdgeInsets.only(
          bottom: 10.pt,
          left: 15.pt,
          right: 15.pt,
        ),
        child: Container(
          child: WButton(
            onPressed: onPressed!,
            color: colorScheme.primary,
            height: 44.pt,
            child: WisText(
              title,
              size: 16.pt,
            ),
            shape: StadiumBorder(),
          ),
        ),
      );
    }

    Widget _buildTextFieldWithInlineLabel(String labelText,
        {InputDecoration? inputDecoration,
        FocusNode? focusNode,
        bool? readOnly,
        GestureTapCallback? onTap,
        TextEditingController? controller,
        String? input}) {
      return WisCard(
        margin: EdgeInsets.only(
          left: 15.pt,
          right: 15.pt,
          top: 10.pt,
        ),
        child: Container(
          height: 44.pt,
          padding: EdgeInsets.fromLTRB(PADDING, 0, PADDING, 0),
          decoration: BoxDecoration(
            color: Colors.white,
            border: Border.all(color: BORDER_COLOR),
            borderRadius: BorderRadius.circular(CORNER_RADIUS),
            boxShadow: [
              BoxShadow(
                offset: Offset(1, 1),
                blurRadius: 3,
                color: Colors.grey[200]!,
              ),
            ],
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Container(
                width: 70,
                child: Text(
                  labelText,
                  style: TextStyle(fontSize: LABEL_FONT_SIZE),
                ),
              ),
              Expanded(
                child: TextField(
                  controller: controller,
                  textAlign: TextAlign.left,
                  style: TextStyle(
                      fontSize: LABEL_FONT_SIZE, fontWeight: FontWeight.w700),
                  focusNode: focusNode,
                  readOnly: readOnly ?? false,
                  onTap: onTap,
                  decoration: inputDecoration,
                  scrollPadding: EdgeInsets.zero,
                  onChanged: (value) {
                    String trimmedValue = value.trim();
                    if (focusNode == titleNode) {
                      store!.title = trimmedValue;
                      _title.value = value;
                    } else if (focusNode == themeNode) {
                      store!.theme = trimmedValue;
                      _theme.value = value;
                    }
                  },
                ),
              ),
              Offstage(
                offstage: input!.isEmpty,
                child: GestureDetector(
                  onTap: () {
                    if (focusNode == titleNode) {
                      _title.value = '';
                    } else if (focusNode == themeNode) {
                      _theme.value = '';
                    }
                    controller!.clear();
                  },
                  child: Container(
                    child: Icon(
                      Icons.cancel,
                      color: Colors.grey,
                      size: 17,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      );
    }

    Widget _buildNoticeContent() {
      return WisCard(
        margin: EdgeInsets.only(
          top: 10.pt,
          left: 15.pt,
          right: 15.pt,
        ),
        child: Container(
          height: 240.pt,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Container(
                margin: EdgeInsets.fromLTRB(MARGIN * 2, MARGIN, MARGIN, 0),
                child: Text(
                  '正文',
                  style: TextStyle(fontSize: LABEL_FONT_SIZE),
                  textAlign: TextAlign.left,
                ),
              ),
              Expanded(
                child: Container(
                  padding: EdgeInsets.fromLTRB(
                      PADDING / 2, 0, PADDING / 2, PADDING / 2),
                  child: TextFormField(
                    maxLength: 1000,
                    maxLines: 9, //需要设置maxLines长度提示才会移到右下角
                    scrollPadding: EdgeInsets.zero,
                    style: TextStyle(
                        fontSize: LABEL_FONT_SIZE, fontWeight: FontWeight.w700),
                    focusNode: contentNode,
                    validator: (value) {
                      if (value == null || value.trim().length == 0) {
                        return '通知正文不能为空';
                      } else if (value.length < 10) {
                        return '通知正文不得低于10个字';
                      }

                      return null;
                    },
                    onChanged: (value) {
                      store!.content = value;
                    },
                    decoration: InputDecoration(
                      hintText: '请输入正文',
                      hintStyle: TextStyle(
                        fontSize: HINTEXT_FONT_SIZE,
                        fontWeight: FontWeight.w400,
                      ),
                      labelStyle: TextStyle(),
                      fillColor: Colors.transparent,
                      enabledBorder: InputBorder.none,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      );
    }

    //使用GestureDetactor实现点击空白处收起键盘
    return GestureDetector(
      onTap: () {
        if (titleNode.hasFocus) {
          titleNode.unfocus();
        }
        if (themeNode.hasFocus) {
          themeNode.unfocus();
        }
        if (contentNode.hasFocus) {
          contentNode.unfocus();
        }
      },
      child: Form(
        key: store!.formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch, //子元素横向拉伸铺满整个容器
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            _buildTextFieldWithInlineLabel(
              '标题',
              inputDecoration: InputDecoration(
                fillColor: Colors.transparent,
                hintStyle: hintStyle,
                hintText: "请输入标题",
              ),
              focusNode: titleNode,
              controller: titleController,
              input: _title.value,
            ),
            _buildTextFieldWithInlineLabel(
              '主题词',
              inputDecoration: InputDecoration(
                hintText: "请输入主题词",
                hintStyle: hintStyle,
                fillColor: Colors.transparent,
              ),
              focusNode: themeNode,
              controller: themeController,
              input: _theme.value,
            ),
            Obx(() {
              return _buildTextFieldWithInlineLabel(
                '类型',
                inputDecoration: InputDecoration(
                  hintText: "请选择类型",
                  fillColor: Colors.transparent,
                  hintStyle: hintStyle,
                  suffixIcon: Icon(
                    Icons.chevron_right,
                  ),
                  suffixIconConstraints: BoxConstraints(),
                ),
                onTap: () => store!.typePicker(),
                readOnly: true,
                // controller: TextEditingController(text: store?.type),
                controller: TextEditingController(text: store!.type?.name),
                input: '',
              );
            }),
            _buildNoticeContent(),
            Container(
              margin: EdgeInsets.fromLTRB(15.0, 30.0, 15.0, 30),
              child: Text(
                '*点击保存并预览之后系统将会把公告存入草稿箱。若未保存直接退出应用，编辑内容将不会保存，请谨慎操作。',
                style: TextStyle(color: Colors.grey[400], fontSize: 13.0),
              ),
            ),
            Container(height: MARGIN),
            _buildPrimaryButton('保存并预览', PRIMARY_BUTTON_HEIGHT, () {
              //store.saveDraft();
              bool isCorrect = store!.tableVerification();
              if (isCorrect) {
                store!.saveDraft();
              }
            }),
          ],
        ),
      ),
    );
  }
}
