/*
 * @Author: XianKaiQun
 * @Date: 2020-07-16 18:09:39
 * @LastEditors  : WuWei
 * @LastEditTime : 2023-05-16 10:10:43
 * @Description: 
 */
import 'dart:convert';

import 'package:app_package/app_package.dart';
import 'package:app_package/src/api/root.dart';
import 'package:app_package/src/models/form_menu_id_detail.dart';
import 'package:app_package/src/models/hgj_menu.dart';
import 'package:app_package/src/models/menu_detail.dart';
import 'package:app_package/src/models/person.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart' show DateFormat;
import 'package:wisdom_cli/new/utils/month_picker/date_period.dart';
import 'package:wisdom_cli/wisdom_cli.dart';

class MessageAddStore with ChangeNotifier {
  final BuildContext context, providerContext;
  late Map<String, dynamic> routingArgs;
  MessageAddStore(this.context, this.providerContext) {
    routingArgs = (ModalRoute.of(context)?.settings.arguments ??
            new Map<String, dynamic>()) as Map<String, dynamic>? ??
        {};
  }
  String get id => routingArgs['id'];
  String get fid => routingArgs['fid'];
  String? get title => routingArgs['appBarTitle'] ?? '新建表单';
  get formHtml => routingArgs['formHtml'] ?? null;
  get formValue => routingArgs['formValue'] ?? null;
  final appGlobalStore = GetIt.I.get<AppGlobalStore>();

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

  final formKey = GlobalKey<FormState>();

  PersonModel? person;
  List<HgjMenuModel>? menuList = [];

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

  final scrollViewKey = GlobalKey<WisScrollViewState>();

  final entCode = WisStorageUtil.get(key: 'storage-user-entCode');
  String? barTitle = '新建表单';

  onInit() async {
    if (formHtml != null) {
      onSetTitle(title);
    }
    await onInitform();
  }

  /// 表单详情
  FormMenuIdDetailModel? formDetail;
  Future getFormDetail() async {
    var res = await RootApi.getFormIdDetail(id);
    formDetail = res.data;
    if (res.data?.formHtml != null) {
      if (formHtml == null) {
        formList = jsonDecode(res.data!.formHtml!)['fields'];
        oninitialFormValue();
      }
    }
    if (formDetail!.type == 'community') {
      await getCommunityList();
    }
    notifyListeners();
  }

  MenuDetail? detail;

  /// 获取表单填报详情
  Future onGetFormDetail() async {
    var res = await RootApi.getMenuFormDetail(fid);
    detail = res.data;
    setCommunity(detail!.communityId);
    if (res.data?.fillPeriodType != 'single' &&
        res.data?.fillPeriodType != 'unlimited') {
      fillPeriodExclusiveYear = detail!.fillPeriodExclusiveYear!;
      fillPeriodYear = (detail!.fillPeriodYear != null
          ? int.parse(detail!.fillPeriodYear!)
          : null)!;
      fillPeriodOrderValue = (detail!.fillPeriodOrderValue != null
          ? int.parse(detail!.fillPeriodOrderValue!)
          : null)!;
      switch (detail?.fillPeriodType) {
        // case 'day':

        //   break;
        case 'week':
          List arr = detail!.fillPeriodExclusiveYear!.split('-');
          period = DatePeriod(
              DateTime(int.parse(detail!.fillPeriodYear!), int.parse(arr[0]),
                  int.parse(arr[1])),
              DateTime(int.parse(detail!.fillPeriodYear!), int.parse(arr[0]),
                  int.parse(arr[1]) + 6));
          break;
        case 'month':
          List arr = detail!.fillPeriodExclusiveYear!.split('-');
          period = '${detail!.fillPeriodYear}-${arr[0]}';
          break;
        case 'year':
          period = detail!.fillPeriodYear;
          break;
        // case 'quarter':
        //   break;
        default:
          period =
              '${detail!.fillPeriodYear}-${detail!.fillPeriodExclusiveYear}';
          break;
      }
    }
    notifyListeners();
  }

  /// 初始化表单初始值
  void oninitialFormValue() {
    for (int i = 0; i < formList.length; i++) {
      var item = {
        'id': formList[i]['__config__']['formId'],
        'name': formList[i]['__config__']['label'],
        'tag': formList[i]['__config__']['tag'] == 'el-upload'
            ? formList[i]['__config__']['tagIcon']
            : formList[i]['__config__']['tag'],
        'required': formList[i]['__config__']['required'],
        'value': null,
        'valueText': null,
      };
      postFormPrs.add(item);
      notifyListeners();
    }
  }

  List communityList = [];

  /// 获取项目列表
  Future<void> getCommunityList() async {
    var res = await RootApi.getAuthCompanyCommunity();
    communityList = jsonDecode(jsonEncode(res.data)) ?? [];
    notifyListeners();
  }

  /// 提交审批表单初始化
  Future<void> onInitform() async {
    setBarTitle();
    if (formValue == null) {
      await Future.wait([getFormDetail()]);
    } else {
      await Future.wait([
        getFormDetail(),
        onGetFormDetail(),
      ]);
      formList = json.decode(formHtml)['fields'];
      var value = json.decode(formValue);
      if (value != null && formList.length == value.length) {
        for (int i = 0; i < value.length; i++) {
          var item = value[i];
          if (item['id'] != 1 && item['id'] != 2 && item['id'] != 3) {
            postFormPrs.add(item);
          }
          if (item['id'] == 2) {
            setCommunityName(item['valueText']);
          }
          if (item['id'] == 3) {
            switch (detail!.fillPeriodType) {
              case 'week':
                weekStr = item['valueText'];
                break;
              case 'quarter':
                seasonStr = item['valueText'];
                break;
              default:
            }
            notifyListeners();
          }
        }
      } else {
        if (value.length > 0) {
          for (int i = 0; i < formList.length; i++) {
            var fitem = formList[i];
            bool isFind = false;
            for (int j = 0; j < value.length; j++) {
              var vitem = value[j];
              if (vitem['id'] == 2) {
                setCommunityName(vitem['valueText']);
              }
              if (vitem['id'] == 3) {
                switch (detail!.fillPeriodType) {
                  case 'week':
                    weekStr = vitem['valueText'];
                    break;
                  case 'quarter':
                    seasonStr = vitem['valueText'];
                    break;
                  default:
                }
                notifyListeners();
              }
              if (fitem['__config__']['formId'] == vitem['id']) {
                isFind = true;
                postFormPrs.add(vitem);
              }
            }
            if (isFind == false) {
              var item = {
                'id': fitem['__config__']['formId'],
                'name': fitem['__config__']['label'],
                'tag': fitem['__config__']['tag'] == 'el-upload'
                    ? fitem['__config__']['tagIcon']
                    : fitem['__config__']['tag'],
                'required': fitem['__config__']['required'],
                'value': null,
                'valueText': null,
              };
              postFormPrs.add(item);
            }
          }
        } else {
          for (int i = 0; i < formList.length; i++) {
            var fitem = formList[i];
            var item = {
              'id': fitem['__config__']['formId'],
              'name': fitem['__config__']['label'],
              'tag': fitem['__config__']['tag'] == 'el-upload'
                  ? fitem['__config__']['tagIcon']
                  : fitem['__config__']['tag'],
              'required': fitem['__config__']['required'],
              'value': null,
              'valueText': null,
            };
            postFormPrs.add(item);
            notifyListeners();
          }
        }
      }
      notifyListeners();
    }
  }

  void setBarTitle() {
    barTitle = '$title';
  }

  List postFormPrs = [];

  Future<void> onFilesChanged(List<FileEntity> files, index) async {
    final futures =
        files.map((e) => GlobalApi.postUploadImageObject(e.file!)).toList();
    List imageArr = postFormPrs[index]['value'] ?? [];
    try {
      WLoadingUtil.show();
      final res = await Future.wait(futures);
      imageArr.addAll(res.map((e) => e).toList());
      onSetFormPrs(index, imageArr);
    } finally {
      WLoadingUtil.hide();
    }
  }

  void onImageRemoveAt(index, i) {
    List imageArr = postFormPrs[index]['value'] ?? [];
    imageArr.removeAt(i);
    onSetFormPrs(index, imageArr);
  }

  /// 表单标题
  String? formTitle;

  /// 表单填报标题
  onSetTitle(value) {
    formTitle = value;
    notifyListeners();
  }

  dynamic period;
  String? weekStr;
  String? seasonStr;
  int? fillPeriodYear;
  int? fillPeriodOrderValue;
  String? fillPeriodExclusiveYear;
  String? community;
  String? communityName;

  /// 设置项目小区
  setCommunity(value) async {
    community = value;
    communityList.forEach((element) {
      if (element['list'] != null && element['list'].length > 0) {
        element['list'].forEach((item) => {
              if (item['communityId'] == value)
                {
                  setCommunityName(item['communityName']),
                }
            });
      }
    });
    notifyListeners();
  }

  setCommunityName(value) async {
    communityName = value;
    notifyListeners();
  }

  /// 设置周
  void onSetWeek(value, weekStrs, weekNum) {
    weekStr = weekStrs;
    fillPeriodOrderValue = weekNum;
    onSetPeroid(value, 'week');
    notifyListeners();
  }

  /// 设置季度
  void onSetSeason(
    value,
    strs,
  ) {
    seasonStr = strs;
    onSetPeroid(value, 'quarter');
    notifyListeners();
  }

  /// 设置当前周期
  void onSetPeroid(value, type) {
    period = value;
    switch (type) {
      /// PC 格式: 2023第4周 (01月23日 ~ 01月29日)
      case 'week':
        var arr = DateFormat("yyyy-MM-dd").format(value.start).split('-');
        fillPeriodYear = int.parse(arr[0]);
        fillPeriodExclusiveYear = '${arr[1]}' + '-' + '${arr[2]}';
        break;
      case 'day':
        var arr = value.split('-');
        fillPeriodYear = int.parse(arr[0]);
        fillPeriodExclusiveYear = '${arr[1]}' + '-' + '${arr[2]}';
        break;
      case 'month':
        var arr = value.split('-');
        fillPeriodOrderValue = int.parse(arr[1]);
        fillPeriodExclusiveYear = '${arr[1]}-01';
        fillPeriodYear = int.parse(arr[0]);
        break;
      case 'year':
        fillPeriodExclusiveYear = '01-01';
        fillPeriodYear = int.parse(period);
        break;
      case 'quarter':
        var arr = value.split('-');
        fillPeriodOrderValue = getQuater(int.parse(arr[1]))!;
        fillPeriodExclusiveYear = '${arr[1]}-01';
        fillPeriodYear = int.parse(arr[0]);
        break;
      default:
        break;
    }
    notifyListeners();
  }

  /// 获取季度顺序
  int? getQuater(date) {
    int? quater;
    switch (date) {
      case 1:
        quater = 1;
        break;
      case 4:
        quater = 2;
        break;
      case 7:
        quater = 3;
        break;
      case 10:
        quater = 4;
        break;
      default:
    }
    return quater;
  }

  /// 表单赋值
  /// @index 表单序号；
  /// @value 填写的表单内容；
  void onSetFormPrs(index, value) {
    postFormPrs[index]['value'] = value;
    postFormPrs[index]['valueText'] = value;
    notifyListeners();
  }

  void onSetFormRadioPrs(index, value, data) {
    postFormPrs[index]['value'] = value;
    if (value == null) {
      return;
    }
    data.forEach((item) {
      if (item['value'] == value) {
        postFormPrs[index]['valueText'] = item['label'];
      }
    });
  }

  void onSetFormCheckGroupPrs(index, value, data) {
    postFormPrs[index]['value'] = value;
    String? checkName;
    if (value == null || value == []) {
      return;
    }
    data.forEach((item) {
      value.forEach((item2) {
        if (item['value'] == item2) {
          checkName = checkName != null ? '${checkName}、${item['label']}' : item['label'];
        }
      });
    });
    postFormPrs[index]['valueText'] = checkName;
  }

  void onSetFormSelectPrs(index, value, data) {
    postFormPrs[index]['value'] = value;
    if (value == null) {
      return;
    }
    data.forEach((item) {
      if (item['value'] == value) {
        postFormPrs[index]['valueText'] = item['label'];
      }
    });
  }

  List formList = [];

  /// 整个表单认证
  bool onValidateForm() {
    if (formTitle == null || formTitle == '') {
      WToastUtil.show('请填写标题');
      return false;
    }
    if (formDetail!.type == 'enterprise' &&
        formDetail!.fillPeriodType != 'single' &&
        formDetail!.fillPeriodType != 'unlimited' &&
        (period == null || period == '')) {
      WToastUtil.show('请选择周期');
      return false;
    }
    if (formDetail!.type == 'community' &&
        formDetail!.fillPeriodType != 'single' &&
        formDetail!.fillPeriodType != 'unlimited' &&
        (period == null || period == '')) {
      WToastUtil.show('请选择所属项目');
      return false;
    }
    final List resultList = [];
    for (int i = 0; i < formList.length; i++) {
      var formItem = formList[i];
      if (!formItem['__config__']['required']) {
        resultList.add(true);
        break;
      }

      /// 富文本跳过
      if ((postFormPrs[i]['value'] == null ||
              postFormPrs[i]['value'] == '' ||
              (postFormPrs[i]['value'] is List &&
                  postFormPrs[i]['value'].length == 0)) &&
          postFormPrs[i]['tag'] != 'quillEditor') {
        resultList.add(false);
        WToastUtil.show('请填写${formItem['__config__']['label']}');
        break;
      }
      if (postFormPrs[i]['tag'] != 'quillEditor' &&
          onValidateFormItem(postFormPrs[i]['value'],
                  formItem['__config__']['regList'], formItem) !=
              null) {
        resultList.add(false);
        WToastUtil.show(onValidateFormItem(postFormPrs[i]['value'],
                formItem['__config__']['regList'], formItem) ??
            '');
        break;
      }
      resultList.add(true);
    }

    if (resultList.where((element) => !element).toList().length > 0)
      return false;
    else
      return true;
  }

  /// 填写验证
  /// @value 表单填写内容；
  /// @regList 校验规则列表；
  /// @formItem 当前表单；
  String? onValidateFormItem(dynamic value, List regList, formItem) {
    if (regList.length == 0) return null;

    List notMatchList = [];
    regList.forEach((regItem) {
      /// 去除js正则斜杠
      List<String> list = regItem['pattern'].split('');
      List<String> arr = [];
      for (int i = 0; i < list.length; i++) {
        if (list[i] != '/' && (i != 0 && i != (list.length - 1)))
          arr.add(list[i]);
      }
      final reg = new RegExp(ListFunc.list2String(arr), multiLine: true);
      if (!reg.hasMatch(value)) {
        notMatchList.add(regItem);
      }
    });

    if (notMatchList.length > 0) {
      return notMatchList[0]['message'];
    } else {
      return null;
    }
  }

  /// 重置表单
  void onResetPostprs() {
    postFormPrs.clear();
  }

  getWeekNum() {}

  Future<void> onSubmitForm() async {
    final res = onValidateForm();
    var titleItem = {
      'id': 1,
      'name': '标题',
      'tag': 'el-input',
      'required': true,
      'value': formTitle,
      'valueText': formTitle,
    };
    var periodItem = {
      'id': 3,
      'name': '填报周期',
      'tag': 'el-input',
      'required': true,
      'value': null,
      'valueText': null,
    };
    var communityItem = {
      'id': 2,
      'name': '所属项目',
      'tag': 'el-input',
      'required': true,
      'value': community,
      'valueText': communityName,
    };
    if (formDetail!.type == 'enterprise' &&
        formDetail!.fillPeriodType != 'single' &&
        formDetail!.fillPeriodType != 'unlimited') {
      switch (formDetail!.fillPeriodType) {
        case 'day':
          periodItem['value'] = period;
          periodItem['valueText'] = period;
          break;
        case 'week':
          periodItem['value'] = weekStr;
          periodItem['valueText'] = weekStr;
          break;
        case 'month':
          periodItem['value'] = period;
          periodItem['valueText'] = period;
          break;
        case 'year':
          periodItem['value'] = period;
          periodItem['valueText'] = period;
          break;
        case 'quarter':
          periodItem['value'] = seasonStr;
          periodItem['valueText'] = seasonStr;
          break;
        default:
      }
    }
    final arr = [];
    if (formDetail!.type == 'enterprise' &&
        formDetail!.fillPeriodType != 'single' &&
        formDetail!.fillPeriodType != 'unlimited') {
      [titleItem, periodItem, ...postFormPrs]
          .forEach((item) => arr.add(jsonEncode(item)));
    } else if (formDetail!.type == 'community') {
      [titleItem, communityItem, ...postFormPrs]
          .forEach((item) => arr.add(jsonEncode(item)));
    } else {
      [titleItem, ...postFormPrs].forEach((item) {
        arr.add(jsonEncode(item));
      });
    }

    if (res) {
      if (formHtml == null) {
        final fid = await RootApi.postIntelligentForm(
          {
            'formId': formDetail!.id,
            'communityId': community,
            'title': formTitle,
            'fillPeriodYear': fillPeriodYear,
            'fillPeriodExclusiveYear': fillPeriodExclusiveYear,
            'fillPeriodOrderValue': fillPeriodOrderValue,
            'fillContent': arr.toString(),
          },
        );
        if (fid.data != null) {
          WToastUtil.show('$title新建表单提交成功！');
          onResetPostprs();
          Navigator.pop(context);
        }
      } else {
        final isSuccess = await RootApi.putIntelligentForm(
          fid,
          {
            'communityId': community,
            'title': formTitle,
            'fillPeriodYear': fillPeriodYear,
            'fillPeriodExclusiveYear': fillPeriodExclusiveYear,
            'fillPeriodOrderValue': fillPeriodOrderValue,
            'fillContent': arr.toString(),
          },
        );
        if (isSuccess.data != null && isSuccess.data! > 0) {
          WToastUtil.show('$title表单修改成功！');
          onResetPostprs();
          Navigator.pop(context);
        }
      }
    }
  }
}
