import 'dart:convert' show json;
import 'dart:io';

import 'package:amos_flutter_ui/message/index.dart';
import 'package:base/model/APIResponse.dart';
import 'package:base/model/PageDto.dart';
import 'package:base/services/api_address.dart';
import 'package:base/utils/HttpUtil.dart';
import 'package:base/utils/request.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

import '../model/Hidden_Danger/hidden_danger_model.dart';
import '../model/Task/TaskAddModel.dart';
import '../view/hidedanger_manage/hidden_danger_found.dart';

//列表查询
Future<PageDto> getHiddenDangerList(HiddenDangerFilter filter) async {
  try {
    // 根据输入参数拼接请求body
    var datas = {
      'dangerLevel': filter.dangerLevel,
      'pageSize': filter.pageSize,
      'pageNumber': filter.pageIndex,
      'isHandle': filter.isHandle,
      'dangerState': filter.dangerState,
      'belongType': filter.belongType,
      'dangerId': filter.dangerId,
    };
    var data = await HttpUtil().post(ApiAddress.HIDDEN_DANGER_LIST, data: json.encode(datas));
    PageDto pageDto;
    //具体实现函数待编写
    if (data['result'] == 'SUCCESS') {
      pageDto = PageDto.fromJson(data['dataList']);
    } else {
      pageDto = PageDto.fromJson({});
    }
    return pageDto;
  } catch (e) {
    rethrow;
  }
}

//模糊查询
Future<PageDto> getHiddenDangerByLikeName(HiddenDangerFilter filter) async {
  try {
    // 根据输入参数拼接请求body
    var datas = {
      'dangerLevel': filter.dangerLevel,
      'pageSize': filter.pageSize,
      'pageNumber': filter.pageIndex,
      'dangerName': filter.dangerName,
      'dangerState': filter.dangerState,
      'belongType': filter.belongType,
      'isHandle': filter.isHandle
    };
    var data = await HttpUtil().post(ApiAddress.HIDDEN_DANGER_LIST, data: json.encode(datas));
    // var data=await HttpUtil().get('/api/latent/danger/detail?id=14');
    PageDto pageDto;
    //具体实现函数待编写
    if (data['result'] == 'SUCCESS') {
      pageDto = PageDto.fromJson(data['dataList']);
    } else {
      pageDto = PageDto.fromJson({});
    }
    return pageDto;
  } catch (e) {
    rethrow;
  }
}

//获取隐患信息
Future<HideDangerInfoModel> getHiddenDangerModel(BuildContext context, int dangerId, String taskId,
    {bool isFinish = false}) async {
  try {
    var data = await HttpUtil().get(ApiAddress.HIDDEN_DANGER_DETAIL + '?id=$taskId&isFinish=$isFinish');
    if (data == null || data.isEmpty) {
      MsgBox.showConfirmDialog(context, () {
        Navigator.pop(context);
      }, content: '无操作权限');
    }
    if (data['result'] == 'SUCCESS' && data['dataList'] != null) {
      var infoModels = HideDangerInfoModel.fromJson(data['dataList']);
      return infoModels;
    } else {
      return null;
    }
  } catch (e) {
    rethrow;
  }
}

//保存普通隐患信息
Future<bool> saveHideDangerInfo(HideDanger hidedanger) async {
  try {
    // 根据输入参数拼接请求body
    var jsonData = {
      'bizOrgCode':hidedanger.bizOrgCode,
      'dangerLevel': hidedanger.dangerLevel,
      'dangerName': hidedanger.dangerName.text,
      'dangerPosition': hidedanger.dangerPlacedetal.text,
      'structureId': hidedanger.dangerPlaceId,
      'structureName': hidedanger.dangerPlace.text,
      'limitDate': hidedanger.limitDate.text,
      'photoUrls': hidedanger.photoUrls,
      'remark': hidedanger.remark.text,
      'reviewUserIds': hidedanger.reviewUserIds
    };

    var data = await HttpUtil().post(ApiAddress.HIDDEN_DANGER_CREATE_NORMAL, data: json.encode(jsonData));
    if (data['result'] == 'SUCCESS') {
      return true;
    }
    HiddenDangerFound.popUpMsg(data['message'].toString());
    return false;
  } catch (e) {
    HiddenDangerFound.popUpMsg('重新确认');
    rethrow;
  }
}

Future<APIResponse> saveInspectionDangerInfo(int checkedId, List<TaskDetailForAdd> details) async {
  try {
    var itemListStr = [];
    var checkId = checkedId;
    for (TaskDetailForAdd item in details) {
      var itemStr = {
        'dangerLevel': item.dangerLevel,
        'itemId': item.itemId,
        'limitDate': item.limitDate,
        'routePointItemId': item.routePointItemId,
        'name': item.name,
        'remark': item.remark
      };
      itemListStr.add(itemStr);
    }
    var jsonStr = {'checkId': checkId, 'itemList': itemListStr};
    var data = await HttpUtil().post(ApiAddress.HIDDEN_DANGER_CREATE_PATROL, data: json.encode(jsonStr));
    return APIResponse.fromJson(data);
  } catch (e) {
    rethrow;
  }
}

//保存图片
Future<APIResponse> updataImg(List fileList) async {
  try {
    List<String> imgUrls = List();
    // 循环上传
    for (int i = 0; i < fileList.length; i++) {
      File file = fileList[i];
      String path = file.path;
      var name = path.substring(path.lastIndexOf('/') + 1, path.length);
      FormData formData = FormData.fromMap({'files': await MultipartFile.fromFile(path, filename: name)});
      var data = await HttpRequest.uploadImage(data: formData);
      if (data['status'] == 200) {
        //拼接文件路径名
        imgUrls.add(data['result']['url']);
      } else {
        return APIResponse.error('图片上传失败');
      }
    }
    if (imgUrls.length == 1) {
      return APIResponse.success(imgUrls[0]);
    }
    return APIResponse.success(imgUrls.join(','));
  } catch (e) {
    return APIResponse.error('图片上传失败');
    //throw e;
  }
}

//保存评审、治理、验证 流程结果
Future<APIResponse> saveReviewResult(HideDanger hd, result, flowId, flowJson, taskId, dangerId, {gradeValue}) async {
  try {
    var jsonData = {
      'excuteType': result,
      'flowJson': flowJson,
      'flowRecordId': flowId,
      'delayLimitDate': hd.delayLimitDate.text,
      'nextCanActionUser': hd.reviewUserIds.toString(),
      'needCompanyVerify': hd.needCompanyVerify,
      'reformLimitDate': hd.limitDate.text,
      'remark': hd.remark.text,
      'dangerId': dangerId,
      'taskId': taskId,
      'dangerLevel': gradeValue,
      'reasonAnalysis': hd.wentimiaoshu.text,
      'inferOtherThings': hd.juyifansan.text,
      'reviewUserIds': hd.reviewUserIds
    };
    var data = await HttpUtil().post(ApiAddress.HIDDEN_DANGER_EXECUTE, data: json.encode(jsonData));
    if (data['result'] == 'SUCCESS') {
      return APIResponse.success('执行成功！');
    } else {
      return APIResponse.error(data['message']);
    }
  } catch (e) {
    rethrow;
  }
}

// 巡检记录不合格项（从不合格记录中添加任务时，调用查询不合格项）
Future<List<TaskErrorItem>> queryUnqualifiedInputItem(num checkId) async {
  var data = await HttpUtil().get(ApiAddress.QUERY_UNQUALIFIED_INPUT_ITEM, data: {'checkId': checkId});
  List<TaskErrorItem> rst = List();
  if (data['result'] == 'SUCCESS') {
    var dataList = data['dataList'];
    if (dataList.toString() != '[]') {
      for (final item in dataList) {
        rst.add(TaskErrorItem.fromJson(item));
      }
    }
  }
  return rst;
}

//获取隐患执行日志
Future<HideDangerInfoModel> getDangerFlowRrecord(int dangerId) async {
  try {
    var data = await HttpUtil().get(ApiAddress.HIDDEN_DANGER_FLOWRECORDS + '?id=$dangerId');
    if (data['result'] == 'SUCCESS' && data['dataList'] != null) {
      var infoModels = HideDangerInfoModel.fromJson(data['dataList']);
      return infoModels;
    } else {
      HiddenDangerFound.popUpMsg(data['message'] ?? '获取失败！');
      return null;
    }
  } catch (e) {
    rethrow;
  }
}

Future<List<DangerLevelModel>> GetAllDangerLevel() async {
  List<DangerLevelModel> dlList = [];
  var data = await HttpUtil().get(ApiAddress.ALL_DANGERLEVEL);
  var response = APIResponse.fromJson(data);
  if (response.success) {
    for (final item in response.dataList) {
      if (item['lockStatus'] != 'UNLOCK') continue;
      dlList.add(DangerLevelModel.fromJson(item));
    }
  }
  return dlList;
}
