/*
 * @Author: WuWei
 * @Date: 2020-07-14 15:05:05
 * @LastEditors: ChenYaJin
 * @LastEditTime: 2023-03-31 09:39:47
 * @Description:
 */
import 'dart:convert';
import 'package:app_package/app_package.dart';
import 'package:flutter/widgets.dart';
import 'package:repair_package/src/models/repair_person_list.dart';
import 'package:repair_package/src/models/score_detail.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
import '../service/impl/repair_service_impl.dart';
import '../service/repair_service.dart';
import '../models/repair_detail.dart';
import '../models/repair_dialog.dart';
import '../components/deal_person_picker.dart';

class RepairDetailStore with ChangeNotifier {
  final BuildContext context;
  late Map args;
  RepairDetailStore(this.context) {
    args = (ModalRoute.of(context)?.settings.arguments ??
            new Map<String, dynamic>()) as Map<String, dynamic>? ??
        {};
    initTab();
  }
  final communityGlobalStore = GetIt.I.get<CommunityGlobalStore>();

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

  final repairdetailKey = GlobalKey<WisScrollViewState>();
  final repairConsultKey = GlobalKey<WisScrollViewState>();
  final repairScoreKey = GlobalKey<WisScrollViewState>();

  final RepairService _repairService = RepairServiceImpl();

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

  RepairDialogModel? repairDialog;
  RepairDetailModel? repairDetail;

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

  /// 受理人
  String? dealPersonId;

  ///备注
  String? remark;

  /// 解决说明
  String? solveRemark;

  /// 挂起说明
  String? hangUpRemark;

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

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

  /// 开启说明
  String? reopenRemark;

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

  RepairPersonListModel? dealPerson;

  String? dialogText;

  String? businessTypeId;
  String? sortId;
  String? internalSortId;

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

  /// 抄送人
  List? mailToIds;

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

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

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

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

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

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

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

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

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

  List dealPersonList = [];
  List dealAllPersonList = [];

  /// 获取处理人列表
  Future getPersonList() async {
    var res = await _repairService
        .getDealPerson({'communityId': repairDetail!.communityId});
    var res1 = await _repairService.getDealPerson({
      'communityId': repairDetail!.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 getRepairDetail() async {
    var res = await _repairService.getRepairDetail({'id': args['id']});

    repairDetail = 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 _repairService.getScoreDetail(repairDetail?.linkId);
    scoreDetail = res.data!;
    notifyListeners();
  }

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

  /// 报修对话列表
  Future getRepairDialog() async {
    getRepairDetail();
    var res = await _repairService.getRepairDialog({'id': args['id']});
    repairDialog = 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;
      }
    }

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

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

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

  /// 报修解决
  /// 挂起 hangUp ，受理 accept、 已解决 solve、驳回 reject
  Future putSolve() async {
    if (solveRemark == null || solveRemark == '') {
      return;
    } else if (solveRemark!.length < 5) {
      WToastUtil.show("解决说明不得少于5字", location: WToastLoction.center);
      return;
    }
    WLoadingUtil.show();
    var res;
    try {
      res = await _repairService.putRepair({
        'status': 'solve',
        'id': args['id'],
        'solveRemark': solveRemark,
        'solvePhotos': solvePhotos,
      });
    } finally {
      WLoadingUtil.hide();
      if (res == 1) {
        WToastUtil.show(
          '任务解决成功！',
        );
        Navigator.pop(this.context, true);
        setBackLstRefresh();
        notifyListeners();
      }
    }
  }

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

  ///解决图片删除
  void removeImageSolve(int index) {
    solvePhotos!.remove(solvePhotos![index]);
    notifyListeners();
  }

  /// 报修解决图片上传
  Future<void> pickImageSolve(List<FileEntity> assets) async {
    final futures =
        assets.map((e) => GlobalApi.postUploadImage(e.file)).toList();
    try {
      WLoadingUtil.show();
      final res = await Future.wait(futures);
      solvePhotos!.addAll(res.map((e) => e!.data).toList());
      notifyListeners();
    } finally {
      WLoadingUtil.hide();
    }
  }

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

  /// 报修挂起
  Future putHandup() async {
    if (hangUpRemark == null || hangUpRemark == '') {
      WToastUtil.show("请输入挂起说明~", location: WToastLoction.center);
      return;
    } else if (hangUpRemark!.length < 5) {
      WToastUtil.show("挂起说明不得少于5字", location: WToastLoction.center);
      return;
    }

    if (hangUpPhotos == null || hangUpPhotos!.length == 0) {
      WToastUtil.show("需上传挂起图片哦~", location: WToastLoction.center);
      return;
    }
    WLoadingUtil.show();
    var res;
    try {
      res = await _repairService.putRepair({
        '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, 'repair/handup',
        arguments: {'id': repairDetail?.id});
    if (res is bool && res) {
      repairdetailKey.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(int index) {
    reopenPhotos!.remove(reopenPhotos![index]);
    notifyListeners();
  }

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

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

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

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

    notifyListeners();
  }

  /// 选择受理人
  showChooseperson() async {
    var value = await HandleChoosePerson.show(context, dealPerson);
    if (value?.id != null) {
      dealPerson = 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 _repairService.postDialog({
        'dialogType': 'picture',
        'id': args['id'],
        'dialog': imgs[0],
      });
    } finally {
      WLoadingUtil.hide();
      if (res == 1) {
        WToastUtil.show(
          '发送成功',
        );
        repairConsultKey.currentState?.refreshTrigger();
        notifyListeners();
      }
    }
  }

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

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

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

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

  dynamic appointedTime;

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

  ///选择处理人
  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 == repairDetail!.dealPersonId) {
      WToastUtil.show('不能选择当前处理人！');
      route2assigner();
      return;
    }
    var res = await _repairService
        .postTransfer({'id': repairDetail?.id, 'dealPersonId': item.unique});
    if (res == 1) {
      WToastUtil.show('任务转派成功');
      repairdetailKey.currentState?.refreshTrigger();
    }
  }

  /// 费用
  /// 跳转服务费用详情
  route2RepairCost(RepairDetailModel? item) async {
    await Navigator.pushNamed(context, 'repair/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) {
      repairdetailKey.currentState?.refreshTrigger();
    }
  }

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

  /// 预览详情图片
  void onShowImage(image) {
    List<ImageProvider> images = [];
    images.add(CachedNetworkImageProvider(AppParseUtil.image(image)));
    WisPhotoViewUtil.show(images, 0);
  }

  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 _repairService.setRepairTime(repairDetail?.id,
          {'appointedTime': res.toFormat('{YYYY}-{MM}-{DD} {hh}:{mm}:00')});
      if (isSuccess.data != 0) {
        WToastUtil.show('预约时间成功');
        repairdetailKey.currentState?.refreshTrigger();
      }
    }
  }
}
