import 'dart:convert';
import 'dart:io';
import 'package:path/path.dart';
import 'package:zhiying_base_widget/pages/upload_wechat_page/model/upload_wechat_model.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

class UploadWeChatRepository {
  /// 获取数据
  Future<UploadWeChatModel> fetchInitData() async {
    try {
      var result = await NetUtil.post('/api/v1/user/info/wx', method: NetMethod.GET);
      if (NetUtil.isSuccess(result) && !EmptyUtil.isEmpty(result[GlobalConfig.HTTP_RESPONSE_KEY_DATA])) {
        return UploadWeChatModel.fromJson(result[GlobalConfig.HTTP_RESPONSE_KEY_DATA]);
      }
    } catch (e, s) {
      Logger.error(e, s);
    }
    return null;
  }

  /// 上传信息
  Future<UploadWeChatModel> fetchUpdateWeChatInfo(final File file, final String wxAccount) async {
    try {
      if (!EmptyUtil.isEmpty(file) && !EmptyUtil.isEmpty(wxAccount)) {
        String uploadUrl = await uploadFile(file);
        if (EmptyUtil.isEmpty(uploadUrl)) return null;
        var result = await NetUtil.post('/api/v1/user/info/wx', params: {'wx_account': wxAccount, 'wx_qrcode': uploadUrl}, method: NetMethod.POST);
        if (NetUtil.isSuccess(result) && !EmptyUtil.isEmpty(result[GlobalConfig.HTTP_RESPONSE_KEY_DATA])) {
          return UploadWeChatModel.fromJson(result[GlobalConfig.HTTP_RESPONSE_KEY_DATA]);
        }
      }
    } catch (e, s) {
      Logger.error(e, s);
    }
    return null;
  }

  /// 上传图片
  Future<String> uploadFile(final File imageFile) async {
    try {
      List<int> originBytes = await imageFile.readAsBytes();
      var result1 = await NetUtil.post('/api/v1/img/upload', params: {'dir': 'qrcode', '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;
  }
}
