/*
 * @Author: WuWei
 * @Date: 2020-07-21 15:41:21
 * @LastEditors: ChenYaJin
 * @LastEditTime: 2023-03-31 09:37:14
 * @Description:
 */
import 'dart:convert';
import 'package:app_package/app_package.dart';
import 'package:flutter/widgets.dart';
import 'package:report_package/src/components/deal_classify_picker.dart';
import 'package:report_package/src/components/deal_person_picker.dart';
import 'package:report_package/src/models/report_classify.dart';
import 'package:report_package/src/models/report_detail.dart';
import 'package:report_package/src/models/report_dialog.dart';
import 'package:report_package/src/models/report_person_list.dart';
import 'package:report_package/src/models/score_detail.dart';
import 'package:report_package/src/service/impl/report_service_impl.dart';
import 'package:report_package/src/service/report_service.dart';
import 'package:report_package/src/models/status.dart';
import 'package:wisdom_cli/wisdom_cli.dart';

class PrivateReportDetailStore with ChangeNotifier {
  final BuildContext context;
  late Map args;
  PrivateReportDetailStore(this.context) {
    args =
        ModalRoute.of(context)!.settings.arguments as Map<dynamic, dynamic>? ??
            {};

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

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

  final reportDetailKey = GlobalKey<WisScrollViewState>();
  final reportConsultKey = GlobalKey<WisScrollViewState>();
  final reportScoreKey = GlobalKey<WisScrollViewState>();

  final ReportService _reportService = ReportServiceImpl();

  final List dispatchStatus = ['accept', 'solve', 'evaluate'];

  ReportDetailModel? reportDetail;
  ReportDialogModel? reportDialog;

  /// tab索引
  int tabIndex = 0;
  String? dealPersonId;

  ///备注
  String? remark;

  /// 解决说明
  String? solveRemark;

  /// 挂起说明
  String? hangUpRemark;

  /// 解决图片
  List<FileEntity>? solvePhotos = [];

  /// 挂起图片
  List? hangUpPhotos = [];

  /// 开启说明
  String? reopenRemark;

  /// 开启图片
  List<FileEntity>? reopenPhotos = [];

  ReportPersonListModel? dealPerson;
  ReportClassifyModel? dealClassify;

  String? dialogText;

  String? businessTypeId;
  String? sortId;

  /// 抄送人
  List? mailToIds;

  List? typeList;
  List? sortList;
  List? innerSortList = [];
  String? internalSortId;

  setMailPerson(value) {
    mailToIds = value;
    notifyListeners();
  }

  setType(value) async {
    businessTypeId = value;
    notifyListeners();
    await getSortList();
  }

  setSort(value) {
    sortId = value;
    notifyListeners();
  }

  setInnerSort(value) {
    internalSortId = value;
    notifyListeners();
  }

  Future getTypeList() async {
    var res = await _reportService.getTypeList();
    typeList = jsonDecode(jsonEncode(res.data)) ?? [];
    notifyListeners();
  }

  Future getSortList() async {
    var res =
        await _reportService.getSortList({'businessTypeId': businessTypeId});
    sortList = jsonDecode(jsonEncode(res.data)) ?? [];
    notifyListeners();
  }

  /// 内部分类枚举
  Future getInnerSortList() async {
    var res = await _reportService.getInnerSortList();
    innerSortList = jsonDecode(jsonEncode(res.data)) ?? [];
    notifyListeners();
  }

  setTabIndex(index) async {
    tabIndex = index;
    notifyListeners();
    if (tabIndex == 1) {
      var res = await _reportService.getReportDialog({'id': args['id']});
      reportDialog = res.data;
      notifyListeners();
    }
  }

  Future<void> initTab() async {
    if (args['index'] != null) {
      setTabIndex(args['index']);
    }
  }

  dynamic appointedTime;

  Future setTime(value) async {
    appointedTime = value;
    notifyListeners();
  }

  List dealPersonList = [];

  /// 获取处理人列表
  Future getPersonList() async {
    var res = await _reportService.getDealPerson({
      'communityId': reportDetail!.communityId,
    });
    var res1 = await _reportService.getDealPerson({
      'communityId': reportDetail!.communityId,
      'openHris': true,
    });
    List ids = [];
    res1.data!.forEach((item) {
          item.child!.forEach((item1) {
                ids.add(item1.id);
              });
        });
    res.data?.forEach((item) {
          item.child!.forEach((item1) {
                if (ids.contains(item1.id))
                  {
                    item1.name = '【排班人员】' + item1.name!;
                  };
              });
        });
    dealPersonList = jsonDecode(jsonEncode(res.data)) ?? [];
    notifyListeners();
  }

  setDealPerson(v) {
    dealPersonId = v;
    notifyListeners();
  }

  /// 获取报修详情
  Future getReportDetail() async {
    var res = await _reportService.getReportDetail({'id': args['id']});
    reportDetail = res.data;
    if (res.data?.status == 'waitAccept') {
      Future.wait([
        getTypeList(),
        getInnerSortList(),
      ]);
    }
    if (res.data?.linkId != null && res.data?.linkId != '') {
      getScoreDetail();
    }

    if (res.data?.businessTypeId != null) {
      businessTypeId = res.data?.businessTypeId;
      await getSortList();
    }

    if (res.data?.appointedTime != null) {
      appointedTime = res.data?.appointedTime;
    }

    if (res.data?.sortId != null) {
      sortId = res.data?.sortId;
    }
    if (res.data?.communityId != null) {
      getPersonList();
    }
    notifyListeners();
  }

  ScoreDetailModel? scoreDetail;

  /// 获取服务评分
  Future getScoreDetail() async {
    var res = await _reportService.getScoreDetail(reportDetail?.linkId);
    scoreDetail = res.data!;
  }

  setBackLstRefresh() {
    WisStorageUtil.set(key: 'report_list_refresh', data: true);
  }

  /// 报修对话列表
  Future getReportDialog() async {
    getReportDetail();
    var res = await _reportService.getReportDialog({'id': args['id']});
    reportDialog = res.data;
    notifyListeners();
  }

  /// 报修受理
  /// 挂起 hangUp ，受理 accept、 已解决 solve、驳回 reject
  Future putAccept() async {
    final values = formKey.currentState?.values;
    final entCode = WisStorageUtil.get(key: 'storage-user-entCode');
    final errorList = [
      () => WValidatorUtil.isRequired('请选择业主提报类型').validate(businessTypeId),
      () => WValidatorUtil.isRequired('请选择处理人').validate(dealPersonId),
    ];
    if (entCode == 460102 || entCode == 460101) {
      if (internalSortId == null || internalSortId == '') {
        WToastUtil.show('请选择内部分类');
        return null;
      }
    }
    for (var item in errorList) {
      final text = item();
      if (text != null) {
        WToastUtil.show(text);
        return null;
      }
    }

    if (dealPersonId == null || businessTypeId == null) {
      return;
    }
    var res = await _reportService.putReport({
      'status': 'accept',
      'id': args['id'],
      'dealPersonId': dealPersonId,
      'remark': values!['remark'],
      'sortId': sortId,
      'businessTypeId': businessTypeId,
      'mailToIds': mailToIds,
      'appointedTime': appointedTime != null ? '$appointedTime:00' : null,
      'internalSortId': internalSortId ?? null,
    });

    if (res == 1) {
      WToastUtil.show('任务受理成功！');
      reportDetailKey.currentState?.refreshTrigger();
      setBackLstRefresh();
      notifyListeners();
    } else {
      WToastUtil.show('任务受理失败！');
    }
  }

  ///输入受理备注
  remarkChange(data) {
    remark = data;
    notifyListeners();
  }

  /// 报修解决
  /// 挂起 hangUp ，受理 accept、 已解决 solve、驳回 reject
  Future putSolve() async {
    if (solveRemark == null || solveRemark == '') {
      return;
    }
    if (solveRemark!.length < 5) {
      WToastUtil.show(
        '解决说明不得少于5字',
      );
      return;
    }
    WLoadingUtil.show();
    var res;
    try {
      ///图片上传 拼成future  一次性提交
      final futures = solvePhotos!.map((f) async {
        return GlobalApi.postUploadImage(f.file);
      }).toList();
      var imgres = await Future.wait(futures);
      var imgs = imgres.map((f) => f!.data).toList();

      res = await _reportService.putReport({
        'status': 'solve',
        'id': args['id'],
        'solveRemark': solveRemark,
        'solvePhotos': imgs,
      });
    } finally {
      WLoadingUtil.hide();
      if (res == 1) {
        WToastUtil.show(
          '反馈解决成功！',
        );
        Navigator.pop(this.context, true);
        setBackLstRefresh();
        notifyListeners();
      }
    }
  }

  void solveRemarkChange(data) {
    solveRemark = data;
    notifyListeners();
  }

  ///解决图片删除
  void removeImageSolve(item) {
    solvePhotos!.remove(item);
    notifyListeners();
  }

  /// 报修解决图片上传
  void pickImageSolve() async {
    final assets = await WAssetPickerUtil.image(
      maxCount: 6 - solvePhotos!.length,
    );
    if (assets.isNotEmpty == true) {
      solvePhotos!.addAll(assets);
    }
    notifyListeners();
  }

  /// 跳转到报修解决
  void route2RepairSolve() async {
    final res = await Navigator.pushNamed(context, 'report/solve',
        arguments: {'id': reportDetail?.id});
    if (res is bool && res) {
      reportDetailKey.currentState?.refreshTrigger();
    }
  }

  /// 报修挂起
  Future putHandup() async {
    if (hangUpRemark == null || hangUpRemark == '') {
      WToastUtil.show("请输入挂起说明~", location: WToastLoction.center);
      return;
    }

    if (hangUpRemark!.length < 5) {
      WToastUtil.show(
        "挂起说明不得少于5字",
      );
      return;
    }

    if (hangUpPhotos == null || hangUpPhotos!.length == 0) {
      WToastUtil.show(
        "需上传挂起图片哦~",
      );
      return;
    }

    WLoadingUtil.show();
    var res;
    try {
      res = await _reportService.putReport({
        'status': 'hangUp',
        'id': args['id'],
        'hangUpRemark': hangUpRemark,
        'hangUpPhotos': hangUpPhotos,
      });
    } finally {
      WLoadingUtil.hide();
      if (res == 1) {
        WToastUtil.show(
          '反馈挂起成功！',
        );
        Navigator.pop(this.context, true);
        setBackLstRefresh();
        notifyListeners();
      }
    }
  }

  /// 跳转到报事挂起
  void route2RepairHandup() async {
    final res = await Navigator.pushNamed(context, 'report/handup',
        arguments: {'id': reportDetail?.id});
    if (res is bool && res) {
      reportDetailKey.currentState?.refreshTrigger();
    }
  }

  ///图片删除
  void removeImageHandup(int index) {
    hangUpPhotos!.remove(hangUpPhotos![index]);
    notifyListeners();
  }

  ///图片选择
  ///图片选择
  Future<void> pickImageHandup(List<FileEntity> assets) async {
    final futures =
        assets.map((e) => GlobalApi.postUploadImage(e.file)).toList();
    try {
      WLoadingUtil.show();
      final res = await Future.wait(futures);
      hangUpPhotos!.addAll(res.map((e) => e!.data).toList());
      notifyListeners();
    } finally {
      WLoadingUtil.hide();
    }
  }

  handupRemarkChange(data) {
    hangUpRemark = data;
    notifyListeners();
  }

  /// 输入开启说明
  void onReopenRemarkChange(data) {
    reopenRemark = data;
    notifyListeners();
  }

  ///重启图片删除
  void removeImageReopen(item) {
    reopenPhotos!.remove(item);
    notifyListeners();
  }

  /// 确认重启
  Future putReopen() async {
    if (reopenRemark == null || reopenRemark == '') {
      return;
    }

    if (reopenRemark!.length < 5) {
      WToastUtil.show(
        "重新开启说明不得少于5字",
      );
      return;
    }

    WLoadingUtil.show();
    var res;
    try {
      ///图片上传 拼成future  一次性提交
      var futures = reopenPhotos!.map((f) async {
        return GlobalApi.postUploadImage(f.file);
      }).toList();
      var imgres = await Future.wait(futures);
      var imgs = imgres.map((f) => f!.data).toList();

      res = await _reportService.putReport({
        'status': 'reopen',
        'id': args['id'],
        'reopenRemark': reopenRemark,
        'reopenPhotos': imgs,
      });
    } finally {
      WLoadingUtil.hide();
      if (res == 1) {
        WToastUtil.show(
          '重新开启成功！',
        );
        Navigator.pop(this.context, true);
        setBackLstRefresh();
        notifyListeners();
      }
    }
  }

  ///重启图片选择
  void pickImageReopen() async {
    final assets = await WAssetPickerUtil.image(
      maxCount: 6 - reopenPhotos!.length,
    );
    if (assets.isNotEmpty == true) {
      reopenPhotos!.addAll(assets);
    }

    notifyListeners();
  }

  /// 选择受理人
  showChooseperson() async {
    var value = await HandleChoosePerson.show(context, dealPerson);
    if (value?.id != null) {
      dealPerson = value;
    }
    notifyListeners();
  }

  /// 选择受理分类
  showChooseClassify() async {
    var value = await HandleChooseClassify.show(context, dealClassify);
    if (value?.id != null) {
      dealClassify = value;
    }
    notifyListeners();
  }

  /// 输入对话
  inputDialog(value) {
    dialogText = value;
    // notifyListeners();
  }

  /// 发送照片
  void onTakePic() async {
    final newAssets = await WAssetPickerUtil.image();
    if (newAssets.isNotEmpty != true) {
      return;
    }
    WLoadingUtil.show();
    var res;
    try {
      ///图片上传 拼成future  一次性提交
      var futures = newAssets.map((f) async {
        return GlobalApi.postUploadImage(f.file);
      }).toList();
      var imgres = await Future.wait(futures);
      var imgs = imgres.map((f) => f!.data).toList();
      res = await _reportService.postDialog({
        'dialogType': 'picture',
        'id': args['id'],
        'dialog': imgs[0],
      });
    } finally {
      WLoadingUtil.hide();
      if (res == 1) {
        WToastUtil.show(
          '发送成功',
        );
        reportConsultKey.currentState?.refreshTrigger();
        notifyListeners();
      }
    }
  }

  /// 发送对话
  void sendDialogText() async {
    if (dialogText == null || dialogText == '') {
      return;
    }
    WLoadingUtil.show();
    var res;
    try {
      res = await _reportService.postDialog({
        'dialogType': 'text',
        'id': args['id'],
        'dialog': dialogText,
      });
    } finally {
      WLoadingUtil.hide();
      if (res == 1) {
        WToastUtil.show(
          '发送成功！',
        );
        dialogText = '';
        reportConsultKey.currentState?.refreshTrigger();
        notifyListeners();
      }
    }
  }

  ///受理人列表
  List empList = []; // 自定义下拉选
  List<ReportPersonListModel> selectEmpList = []; // 表单下拉选
  final formKey = GlobalKey<WFormState>();
  Map<String, dynamic>? formValue = {};

  formChange() {
    formValue = formKey.currentState?.values;
    notifyListeners();
  }

  /// 业务类型（问题分类）列表
  List<StatusModel> statusMap = [];
  Future<List<StatusModel>> getReportSortList() async {
    if (statusMap.isNotEmpty && statusMap.length > 1) {
      return statusMap;
    } else {
      var res = await _reportService.getReportSortList();
      statusMap = res.data ?? [];
      return res.data ?? [];
    }
  }

  ///获取受理人列表
  Future<List<ReportPersonListModel>> getStaffList() async {
    if (selectEmpList.isNotEmpty && selectEmpList.length > 1) {
      return selectEmpList;
    } else {
      var res = await _reportService
          .getPersonList({'communityId': reportDetail!.communityId});
      selectEmpList = res.data ?? [];
      empList = jsonDecode(jsonEncode(res.data)) ?? [];
      notifyListeners();
      return selectEmpList;
    }
  }

  ///选择处理人
  route2assigner() async {
    var res = await WPickerUtil.tree<SinglePickerEntity>(
      context,
      title: Text('选择处理人'),
      initialValue: null,
      data: dealPersonList,
      isSearch: true,
      isMulti: false,
      label: 'name',
      value: 'id',
      child: 'child',
      firstName: 'name',
      firstValue: 'id',
    );
    if (res != null) {
      onPickTransifer(res[0]);
    }
  }

  /// 转派
  onPickTransifer(item) async {
    if (item.unique == reportDetail!.dealPersonId) {
      WToastUtil.show('不能选择当前处理人！');
      route2assigner();
      return;
    }
    var res = await _reportService
        .postTransfer({'id': reportDetail?.id, 'dealPersonId': item.unique});
    if (res == 1) {
      WToastUtil.show('任务转派成功');
      reportDetailKey.currentState?.refreshTrigger();
    }
  }

  /// 费用
  /// 跳转服务费用详情
  route2RepairCost(ReportDetailModel? item) async {
    await Navigator.pushNamed(context, 'report/fee/detail', arguments: {
      'id': item?.id,
      'serviceFeeId': item?.serviceFeeId,
      'communityId': item?.communityId,
    });
    refreshPage();
  }

  refreshPage() {
    final bool? refresh = WisStorageUtil.get(key: 'report_list_refresh');
    if (refresh == true) {
      reportDetailKey.currentState?.refreshTrigger();
    }
  }

  /// 重新开启
  route2ReportOpen(ReportDetailModel item) async {
    await Navigator.pushNamed(context, 'report/reopen', arguments: {
      'id': item.id,
    });
    refreshPage();
  }

  void setPreTime() async {
    final res = await WPickerUtil.dateAndTime(
      context,
      title: WisText('预约时间'),
      firstDate: DateTime(
        DateTime.now().year,
        DateTime.now().month,
        DateTime.now().day,
        DateTime.now().hour,
        DateTime.now().minute - (DateTime.now().minute % 10) + 10,
      ),
      minuteInterval: 10,
    );

    if (res != null) {
      var isSuccess = await _reportService.setReportTime(reportDetail?.id,
          {'appointedTime': res.toFormat('{YYYY}-{MM}-{DD} {hh}:{mm}:00')});
      if (isSuccess.data != 0) {
        WToastUtil.show('预约时间成功');
        reportDetailKey.currentState?.refreshTrigger();
      }
    }
  }
}
