import 'dart:convert';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'package:zhiying_comm/util/turn_chain/turn_chain_util.dart';

class GoodsDetailsPageRepository {
  // 商品详情的封面图片
  String _parentGoodsCoverImg;

  // 优惠券
  String _couponPrice;

  // 佣金
  String _commission;

  // 商品类型
  String _providerName;

  // 商品ID
  String _goodsId;

  /// 缓存详情跳转app样式
  Future<void> cacheTurnChainStyleData() async {
    if (!EmptyUtil.isEmpty(_providerName)) {
      bool result = await TurnChainUtil.cacheTurnChainDialogStyle(_goodsId, _providerName, _commission, _couponPrice);
      Logger.debug('cache result = $result');
    }
  }

  /// 获取上个页面传进来的数据
  Future<List<Map<String, dynamic>>> fetchParentPageData(final Map<String, dynamic> model) async {
    try {
      if (!EmptyUtil.isEmpty(model) && model.containsKey('detail_data') && !EmptyUtil.isEmpty(model['detail_data'])) {
        String provider = model['provider']?.toString();
        String goodId = model['good_id']?.toString();
        if (!EmptyUtil.isEmpty(provider) && !EmptyUtil.isEmpty(goodId)) {
          Map<String, dynamic> detailData = model['detail_data'];
          String goodImage = model['good_image'];
          return _baseDataProcess(true, goodId, provider, detailData, goodImage);
        }
      }
    } catch (e, s) {
      Logger.error(e, s);
    }
    return null;
  }

  /// 获取网络数据
  Future<List<Map<String, dynamic>>> fetchInitModData(final Map<String, dynamic> model) async {
    try {
      String provider = model['provider'];
      String goodId = model['good_id'];
      if (!EmptyUtil.isEmpty(provider) && !EmptyUtil.isEmpty(goodId)) {
        Logger.log('商品类型 = $provider, 商品ID = $goodId');
        var result = await NetUtil.post('/api/v1/detail/$provider/$goodId', method: NetMethod.GET);
        if (NetUtil.isSuccess(result) && !EmptyUtil.isEmpty(result[GlobalConfig.HTTP_RESPONSE_KEY_DATA])) {
          return _baseDataProcess(false, goodId, provider, result[GlobalConfig.HTTP_RESPONSE_KEY_DATA], null);
        }
      }
    } catch (e, s) {
      Logger.error(e, s);
    }
    return null;
  }

  /// 数据处理
  List<Map<String, dynamic>> _baseDataProcess(bool parentInput, String goodId, String provider, final Map<String, dynamic> model, String coverImage) {
    if (!EmptyUtil.isEmpty(provider) && !EmptyUtil.isEmpty(goodId) && !EmptyUtil.isEmpty(model)) {
      try {
        _couponPrice = model['coupon_price'];
        _commission = model['commission'];
        _providerName = model['provider_name'];
        _goodsId = model['good_id'];
        List<Map<String, dynamic>> _pageData = [];
        Map<String, dynamic> baseData = {'provider': provider, 'good_id': _goodsId, 'commission': _commission, 'coupon_price': _couponPrice};
        List<dynamic> modLists = model['mod_list'];

        for (int i = 0; i < modLists.length; i++) {
          Map<String, dynamic> item = modLists[i];
          // ⚠️ 这里之所以要判断是否是String类型，是因为修改的是父亲页面传进来的model -> data 类型了。把dynamic变成了String
          Map<String, dynamic> data = !EmptyUtil.isEmpty(item['data']) ? item['data'] is String ? jsonDecode(item['data']) : item['data'] : new Map<String, dynamic>();

          // ⚠️ 为了商品详情的轮播图能够快速加载，故把上一个页面传进来的第一张图片插入到轮播图集合的第一个图片中
          if (item['mod_name'] == 'product_detail_carousel') {
            if (parentInput) {
              try {
                var imageList = data['image_list'];
                if (!EmptyUtil.isEmpty(imageList)) {
                  _parentGoodsCoverImg = imageList[0];
                } else if (!EmptyUtil.isEmpty(coverImage)) {
                  _parentGoodsCoverImg = coverImage;
                  data['image_list'] = [coverImage];
                }
              } catch (e, s) {
                Logger.error(e, s);
              }
            } else {
              try {
                if (!EmptyUtil.isEmpty(_parentGoodsCoverImg) && !EmptyUtil.isEmpty(data) && !EmptyUtil.isEmpty(data['image_list'])) {
                  if (data['image_list'][0] != _parentGoodsCoverImg) {
                    data['image_list'].insert(0, _parentGoodsCoverImg);
                  }
                } else if (!EmptyUtil.isEmpty(_parentGoodsCoverImg) && !EmptyUtil.isEmpty(data) && EmptyUtil.isEmpty(data['image_list'])) {
                  data['image_list'] = [_parentGoodsCoverImg];
                }
              } catch (e, s) {
                Logger.error(e, s);
              }
            }
          }

          Map<String, dynamic> style = !EmptyUtil.isEmpty(item['style']) ? jsonDecode(item['style']) : new Map<String, dynamic>();
          style.addAll(baseData);

          if (!EmptyUtil.isEmpty(data)) {
            style.addAll(data);
            item['data'] = jsonEncode(style);
            _pageData.add(item);
          } else {
            item['data'] = jsonEncode(style);
            _pageData.add(item);
          }
        }
        return _pageData;
      } catch (e, s) {
        Logger.error(e, s);
      }
    }
    return null;
  }
}
