/*
 * @Author: LiOS
 * @Date: 2020-06-17 22:07:00
 * @LastEditors  : WuWei
 * @LastEditTime : 2023-07-11 13:46:58
 * @Description:
 */

import 'package:get/get.dart';
import 'package:app_package/app_package.dart';
import 'package:flutter/widgets.dart';
import '../../src/service/impl/notice_service_impl.dart';
import '../../src/service/notice_service.dart';
//import '../../src/models/notice_model.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
import '../../src/models/notice_type_model.dart';

class NoticeAddStore extends GetxController {
  final formKey = GlobalKey<FormState>();

  final NoticeService _noticeService = NoticeServiceImpl();

  static const int SINGLE_LINE_TEXT_LENGTH = 32;

  String? _title;
  set title(value) => _title = value;
  get title => _title;
  String? _theme;
  set theme(value) => _theme = value;
  get theme => _theme;

  var _type = NoticeTypeModel(name: '', code: '').obs;
  get type => _type.value;

  String? _content = '';
  set content(value) => _content = value;

  final communityGlobalStore = GetIt.I.get<CommunityGlobalStore>();

  List<NoticeTypeModel> typeList = [
    NoticeTypeModel.fromJson({'label': '温馨提示', 'value': 'prompt'}),
    NoticeTypeModel.fromJson({'label': '普通通知', 'value': 'general'}),
    NoticeTypeModel.fromJson({'label': '重要通知', 'value': 'importance'}),
    NoticeTypeModel.fromJson({'label': '紧急通知', 'value': 'urgency'}),
  ];

  Future<List<NoticeTypeModel>> getTypeList() async {
    var res = await _noticeService.getTypeList();
    return res.data ?? [];
  }

  // 类型
  typePicker() async {
    final res = await WPickerUtil.single<NoticeTypeModel>(
      Get.context!,
      title: WisText('通知类型'),
      getData: () => getTypeList(),
      initialValue: _type.value,
    );
    if (res != null) {
      _type.value = res;
      _type.refresh();
    }
  }

  ///从储存中取出的当前小区 拿出来可能是空
  CommunityModel? get currentCommunity => communityGlobalStore.data;

  String? draftNoticeId;

// 表格校验
  tableVerification() {
    final errorList = [
      () => WValidatorUtil.isRequired('请输入标题').validate(_title),
      () => WValidatorUtil.isOutOfRange('标题长度不能超过32', SINGLE_LINE_TEXT_LENGTH)
          .validate(_title?.length),
      () => WValidatorUtil.isRequired('请输入主题词').validate(_theme),
      () => WValidatorUtil.isOutOfRange('主题词长度不能超过32', SINGLE_LINE_TEXT_LENGTH)
          .validate(_theme?.length),
      () => WValidatorUtil.isRequired('请选择类型').validate(_type.value.code),
      () => WValidatorUtil.isRequired('请输入正文').validate(_content),
    ];
    for (var item in errorList) {
      final text = item();
      if (text != null) {
        WToastUtil.show(text);
        return false;
      }
    }

    if (!formKey.currentState!.validate()) {
      return false;
    }

    return true;
  }

  ///详情
  Future saveDraft() async {
    if (!formKey.currentState!.validate()) {
      return;
    }
    _content = _content!.replaceAll(RegExp('<'), '&lt;');
    _content = _content!.replaceAll(RegExp('\n'), '<br>');
    _content = _content!.replaceAllMapped(RegExp(r'\n'), (match) => ' ');
    _content = _content!.replaceAll(RegExp(' '), '&nbsp;');

    Map<String, String?> postParams = {
      'title': _title,
      'content': '<p>' + _content! + '</p>',
      'theme': _theme,
      'type': _type.value.code,
      'communityId': currentCommunity!.id,
    };

    String? noticeId;
    if (draftNoticeId == null) {
      // postParams['type'] = 'general';
      draftNoticeId = await _noticeService.saveToDraft(postParams);
      noticeId = draftNoticeId;
    } else {
      postParams['id'] = draftNoticeId;
      noticeId = await _noticeService.editDraft(postParams);
    }

    if (noticeId != null) {
      postParams['id'] = noticeId;
      postParams['status'] = 'statusDraft';
      Get.toNamed('notice/detail', arguments: postParams);
    } else {
      WToastUtil.show('保存失败');
    }
  }
}
