import 'dart:convert';
import 'dart:io';
import 'package:path/path.dart';
import 'package:zhiying_base_widget/pages/feedback_page/model/feedback_model.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

class FeedBackRepository {
  /// 获取缓存样式数据
  Future<FeedbackModel> fetchCachedData(final Map<String, dynamic> data) async {
    try {
      String skipIdentifier =
          !EmptyUtil.isEmpty(data) && data.containsKey('skip_identifier') && !EmptyUtil.isEmpty(data['skip_identifier']) ? data['skip_identifier'] : 'pub.flutter.feedback';
      var result = await NetUtil.getRequestCachedData('/api/v1/mod/$skipIdentifier');
      if (!EmptyUtil.isEmpty(result)) {
        var modListData = result['mod_list'][0]['data'];
        if (!EmptyUtil.isEmpty(modListData)) {
          FeedbackModel model = FeedbackModel.fromJson(jsonDecode(modListData));
          model.feedbackTypes.last.isSelect = true;
          return model;
        }
      }
    } catch (e, s) {
      Logger.error(e, s);
    }
    return null;
  }

  /// 获取网络样式数据
  Future<FeedbackModel> fetchData(final Map<String, dynamic> data) async {
    try {
      String skipIdentifier =
          !EmptyUtil.isEmpty(data) && data.containsKey('skip_identifier') && !EmptyUtil.isEmpty(data['skip_identifier']) ? data['skip_identifier'] : 'pub.flutter.feedback';

      var result = await NetUtil.post('/api/v1/mod/$skipIdentifier', method: NetMethod.GET, cache: true);
      if (NetUtil.isSuccess(result) && !EmptyUtil.isEmpty(result[GlobalConfig.HTTP_RESPONSE_KEY_DATA])) {
        var modListData = result[GlobalConfig.HTTP_RESPONSE_KEY_DATA]['mod_list'][0]['data'];
        if (!EmptyUtil.isEmpty(modListData)) {
          FeedbackModel model = FeedbackModel.fromJson(jsonDecode(modListData));
          model.feedbackTypes.last.isSelect = true;
          return model;
        }
      }
    } catch (e, s) {
      Logger.error(e, s);
    }
    return null;
  }

  /// 提交反馈
  Future<dynamic> saveFeedback(final Map<String, dynamic> data) async {
    try {
      List<File> files = data['files'];
      List<String> imageList = [];
      if(!EmptyUtil.isEmpty(files)) {
        // files.forEach((element) async {
        //   String fileName = await updateFile(element);
        //   if (!EmptyUtil.isEmpty(fileName)) {
        //     imageList.add(fileName);
        //   }
        // });

        for(int i = 0 ; i < files.length; i++){
          String imgName = await updateFile(files[i]);
          if(!EmptyUtil.isEmpty(imgName)){
            imageList.add(imgName);
          }
        }

        if (imageList.length != files.length) {
          return null;
        }
      }

      var result = await NetUtil.post('/api/v1/feedback/save', method: NetMethod.POST, params: {
        'type': data['type']?.toString(),
        'title': data['title']?.toString(),
        'content': data['content']?.toString(),
        'image_list': imageList,
      });
      if (NetUtil.isSuccess(result) && !EmptyUtil.isEmpty(result[GlobalConfig.HTTP_RESPONSE_KEY_DATA])) {
        return result[GlobalConfig.HTTP_RESPONSE_KEY_DATA];
      }
    } catch (e, s) {
      Logger.error(e, s);
    }
    return null;
  }

  /// 上传图片
  Future<String> updateFile(final File imageFile) async {
    try {
      List<int> originBytes = await imageFile.readAsBytes();
      var result1 = await NetUtil.post('/api/v1/img/upload', params: {'dir': 'feedback', 'file_size': originBytes.length, 'file_name': basename(imageFile.path)}, method: NetMethod.PUT);
      if (NetUtil.isSuccess(result1) && !EmptyUtil.isEmpty(result1[GlobalConfig.HTTP_RESPONSE_KEY_DATA]) && !EmptyUtil.isEmpty(result1[GlobalConfig.HTTP_RESPONSE_KEY_DATA]['token'])) {
        String token = result1[GlobalConfig.HTTP_RESPONSE_KEY_DATA]['token'];
        String host = result1[GlobalConfig.HTTP_RESPONSE_KEY_DATA]['host'];
        String key = result1[GlobalConfig.HTTP_RESPONSE_KEY_DATA]['key'];
        String method = result1[GlobalConfig.HTTP_RESPONSE_KEY_DATA]['method'];

        var result2 = await NetUtil.uploadFile(host, imageFile, params: {'key': key, 'token': token}, method: method);
        Map<String, dynamic> json = jsonDecode(result2.toString());
        if (NetUtil.isSuccess(json) && !EmptyUtil.isEmpty(json[GlobalConfig.HTTP_RESPONSE_KEY_DATA])) {
          String filename = json['data']['fname'] ?? '';
          print(filename);
          // filename += '?${DateTime.now().millisecondsSinceEpoch.toString()}';
          // print(filename);
          // ⚠️ 这里返回key是因为fname是带有域名的，所以直接用key即可
          return !EmptyUtil.isEmpty(filename) ? key : null;
        }
      }
    } catch (e, s) {
      Logger.error(e, s);
    }
    return null;
  }
}
