package com.ms.biz.service.impl;

import com.alibaba.fastjson.JSON;
import com.ms.biz.consts.CommonConst;
import com.ms.biz.service.DsApiService;
import com.ms.biz.tool.DsJsonRequestTemplate;
import com.ms.biz.bo.ShopBO;
import com.ms.api.dto.dsapi.request.*;
import com.ms.api.dto.dsapi.response.*;
import com.ms.biz.tool.SecurityTool;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author elf
 */
@Service
@Slf4j
@AllArgsConstructor
public class DsApiServiceImpl implements DsApiService {
    private DsJsonRequestTemplate dsJsonRequestTemplate;

    @Override
    public GetPlatformShopPurchaseSettingResponseDTO getPlatformShopPurchaseSetting(String userId, String platform) {
        Map<String, Object> params = new HashMap<>();
        params.put("userId", SecurityTool.encodeByAES(userId));
        params.put("platform", platform);
        String resp = execute("/ds_setting/getPlatformShopPurchaseSetting", params);
        return JSON.parseObject(resp, GetPlatformShopPurchaseSettingResponseDTO.class);
    }

    @Override
    public BatchCreateDistributionOrdersResponseDTO batchCreateDistributionOrders(Long shopId, BatchCreateDistributionOrdersRequestDTO request) {
        request.setPlatform(CommonConst.PLATFORM);
        request.setOperateInfo(createOperateInfo(shopId));
        for (PlatformOrderDTO platformOrder: request.getPlatformOrders()) {
            platformOrder.setShopId(SecurityTool.encodeByAES(String.valueOf(shopId)));
            for (PlatformOrderItemDTO item: platformOrder.getItems()) {
                item.setPlatformItemId(SecurityTool.encodeByAES(item.getPlatformItemId()));
            }
        }
        String resp = execute("/order/batchCreateDistributionOrders", objectToMap(request));
        return JSON.parseObject(resp, BatchCreateDistributionOrdersResponseDTO.class);
    }

    @Override
    public CommonResponseDTO saveDsManualSelectedSku(SavePlatformManualSelectedSkuRequestDTO request) {
        String resp = execute("/order/savePlatformManualSelectedSku", objectToMap(request));
        return JSON.parseObject(resp, CommonResponseDTO.class);
    }

    @Override
    public GetPurchaseOrderItemsAndSourceItemsResponseDTO getPurchaseOrderItemsAndSourceItems(GetPurchaseOrderItemsAndSourceItemsRequestDTO request) {
        String resp = execute("/order/getPurchaseOrderItemsAndSourceItems", objectToMap(request));
        return JSON.parseObject(resp, GetPurchaseOrderItemsAndSourceItemsResponseDTO.class);
    }

    @Override
    public BatchAddDsPurchaseConfirmLogResponseDTO batchAddPurchaseConfirmLog(Long shopId, BatchAddPurchaseConfirmLogRequestDTO request) {
        request.setPlatform(CommonConst.PLATFORM);
        request.setUserId(SecurityTool.encodeByAES(String.valueOf(shopId)));
        request.setOperateInfo(createOperateInfo(shopId));
        for (PlatformOrderDTO platformOrder: request.getPlatformOrders()) {
            for (PlatformOrderItemDTO item: platformOrder.getItems()) {
                item.setPlatformItemId(SecurityTool.encodeByAES(item.getPlatformItemId()));
            }
        }
        String resp = execute("/order/batchAddPurchaseConfirmLog", objectToMap(request));
        return JSON.parseObject(resp, BatchAddDsPurchaseConfirmLogResponseDTO.class);
    }

    @Override
    public CommonResponseDTO cancelPurchaseOrderRelate(String platform, Long shopId, String orderId, List<Long> skuIds) {
        OperateInfoDTO operateInfo = createOperateInfo(shopId);
        Map<String, Object> params = new HashMap<>();
        params.put("platform", platform);
        params.put("shopId", SecurityTool.encodeByAES(String.valueOf(shopId)));
        params.put("platformOrderId", orderId);
        params.put("platformSkuId", skuIds);
        params.put("operateInfo", operateInfo);
        String resp = execute("/order/cancelPurchaseOrderRelate", params);
        return JSON.parseObject(resp, CommonResponseDTO.class);
    }

    @Override
    public CommonResponseDTO cancelPurchaseOrder(String platform, Long shopId, String orderId, String purchaseOrderSn) {
        OperateInfoDTO operateInfo = createOperateInfo(shopId);
        Map<String, Object> params = new HashMap<>();
        params.put("platform", platform);
        params.put("userId", SecurityTool.encodeByAES(String.valueOf(shopId)));
        params.put("platformOrderId", orderId);
        params.put("sourceOrderId", purchaseOrderSn);
        params.put("operateInfo", operateInfo);
        String resp = execute("/order/cancelPurchaseOrder", params);
        return JSON.parseObject(resp, CommonResponseDTO.class);
    }

    @Override
    public GetPurchaseOrderPayUrlResponseDTO getPurchaseOrderPayUrl(Long shopId, List<String> sourceOrderIds, String payPlatformType) {
        OperateInfoDTO operateInfo = createOperateInfo(shopId);
        Map<String, Object> params = new HashMap<>();
        params.put("sourceOrderId", sourceOrderIds);
        params.put("operateInfo", operateInfo);
        params.put("payPlatformType", payPlatformType);
        String resp = execute("/order/getPurchaseOrderPayUrl", params);
        return JSON.parseObject(resp, GetPurchaseOrderPayUrlResponseDTO.class);
    }

    @Override
    public GetPlatformAuthUrlResponseDTO getPlatformAuthUrl(ShopBO shopInfo) {
        Map<String, Object> params = new HashMap<>();
        params.put("userId", SecurityTool.encodeByAES(String.valueOf(shopInfo.getShopId())));
        params.put("platform", CommonConst.PLATFORM);
        params.put("shopName",shopInfo.getShopName());
        params.put("gmtExpire", "2024-08-30 00:00:00");
        params.put("version","3");
        String resp = execute("/platform_shop/get_platform_auth_url", params);
        return JSON.parseObject(resp, GetPlatformAuthUrlResponseDTO.class);
    }

    @Override
    public GetSourceItemInfosResponseDTO getSourceItemInfos(Long shopId, List<String> sourceItemIds) {
        Map<String, Object> params = new HashMap<>();
        params.put("platform", CommonConst.PLATFORM);
        params.put("userId", SecurityTool.encodeByAES(String.valueOf(shopId)));
        params.put("sourceItemIds", sourceItemIds);
        String resp = execute("/order/getSourceItemInfos", params);
        return JSON.parseObject(resp, GetSourceItemInfosResponseDTO.class);
    }

    @Override
    public GetAuthInfoResponseDTO getAuthInfo(Long shopId) {
        Map<String, Object> params = new HashMap<>();
        params.put("userId", SecurityTool.encodeByAES(String.valueOf(shopId)));
        params.put("platform", CommonConst.PLATFORM);
        String resp = execute("/micro_move/get_auth_info", params);
        return JSON.parseObject(resp, GetAuthInfoResponseDTO.class);
    }

    @Override
    public CheckDsAppAuthExpireResponseDTO checkDsAppAuthExpire(Long shopId, String memberId, String authCode) {
        HashMap<String, Object> params = new HashMap<>();
        List<String> userIds = new ArrayList<>();
        userIds.add(SecurityTool.encodeByAES(String.valueOf(shopId)));
        params.put("userIds", userIds);
        params.put("memberId", memberId);
        params.put("authCode", authCode);
        params.put("platform", CommonConst.PLATFORM);
        String resp = execute("/platform_shop/checkDsAppAuthExpire", params);
        return JSON.parseObject(resp, CheckDsAppAuthExpireResponseDTO.class);
    }

    @Override
    public GetAuthShopMemberInfosResponseDTO getAuthShopMemberInfos(Long shopId) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("shopId", SecurityTool.encodeByAES(String.valueOf(shopId)));
        params.put("platform", CommonConst.PLATFORM);
        String resp = execute("/order/getAuthShopMemberInfos", params);
        return JSON.parseObject(resp, GetAuthShopMemberInfosResponseDTO.class);
    }

    private Map<String, Object> objectToMap(Object obj) {
        Map<String, Object> map = new HashMap<>();
        Class<?> clazz = obj.getClass();
        System.out.println(clazz);
        try {
            for (Field field : clazz.getDeclaredFields()) {
                field.setAccessible(true);
                String fieldName = field.getName();
                Object value = field.get(obj);
                map.put(fieldName, value);
            }
        } catch (Exception e) {
            throw new RuntimeException("参数解析错误");
        }
        return map;
    }

    private String execute(String url, Map<String, Object> params) {
        log.info("DsApiURL:" + url);
        log.info("DsApiRequest:" + params);
        try {
            String response = dsJsonRequestTemplate.execute(url, params);
            log.info("DsApiResponse:" + response);
            return response;
        } catch (Exception e) {
            log.error("DsApiException", e);
            throw new RuntimeException("请求异常" + e.getMessage());
        }
    }

    private OperateInfoDTO createOperateInfo(Long shopId) {
        return new OperateInfoDTO(SecurityTool.encodeByAES(String.valueOf(shopId)));
    }
}
