package com.cool.store.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cool.store.dao.ShopStageInfoDAO;
import com.cool.store.enums.ErrorCodeEnum;
import com.cool.store.enums.point.ShopSubStageStatusEnum;
import com.cool.store.exception.ServiceException;
import com.cool.store.mq.util.HttpRestTemplateService;
import com.cool.store.request.FranchiseAgreementRequest;
import com.cool.store.request.NewStoreRequest;
import com.cool.store.request.xfsgFirstOrderListRequest;
import com.cool.store.response.GetStoreInfoByCodeResponse;
import com.cool.store.response.InitiatingResponse;
import com.cool.store.response.ResponseResult;
import com.cool.store.response.xfsgFirstOderListResponse;
import com.cool.store.service.CoolStoreStartFlowService;
import com.cool.store.utils.SecureUtil;
import com.cool.store.utils.poi.StringUtils;
import com.cool.store.utils.poi.constant.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
@Slf4j
public class CoolStoreStartFlowServiceImpl implements CoolStoreStartFlowService {


    @Value("${xfsg.url}")
    private String xfsgUrl;

    @Resource
    ShopStageInfoDAO shopStageInfoDAO;

    @Resource
    private HttpRestTemplateService httpRestTemplateService;

    @Override
    public ResponseResult newStore(NewStoreRequest request, Long shopId) {
        log.info("newStore param:{}", JSONObject.toJSONString(request));
        if (Objects.isNull(request)) {
            throw new ServiceException(ErrorCodeEnum.PARAMS_VALIDATE_ERROR);
        }
        Map<String, Object> requestMap = new HashMap<>();
        fillSignatureInfo(requestMap);
        String url = xfsgUrl + Constants.NEW_STORE_URL + "?timestamp=" + requestMap.get("timestamp") + "&signature=" + requestMap.get("signature");
        InitiatingResponse initiatingResponse = httpRestTemplateService.postForObject(url, request, InitiatingResponse.class);
        log.info("newStore API response:{}", JSONObject.toJSONString(initiatingResponse));
        if (initiatingResponse.getCode() != 0L) {
            throw new ServiceException(ErrorCodeEnum.FRANCHISE_AGREEMENT_FALSE, initiatingResponse.getMsg(),initiatingResponse.getData());
        } else {
            //更新阶段信息
            return new ResponseResult(200000, initiatingResponse.getMsg(), initiatingResponse.getData());
        }
    }

    @Override
    public ResponseResult franchiseAgreement(FranchiseAgreementRequest request, Integer type) {
        log.info("newStore param:{}", JSONObject.toJSONString(request));
        if (Objects.isNull(request)) {
            throw new ServiceException(ErrorCodeEnum.PARAMS_VALIDATE_ERROR);
        }
        Map<String, Object> requestMap = new HashMap<>();
        fillSignatureInfo(requestMap);
        String url = null;
        if (Constants.TWO_INTEGER == type) {
            url = xfsgUrl + Constants.FRANCHISE_AGREEMENT_COMPANY + "?timestamp=" + requestMap.get("timestamp") + "&signature=" + requestMap.get("signature");
            request.setZxhtywfl("3121375929356587766");
        } else if (Constants.ONE_INTEGER == type) {
            url = xfsgUrl + Constants.FRANCHISE_AGREEMENT_PERSON + "?timestamp=" + requestMap.get("timestamp") + "&signature=" + requestMap.get("signature");
        }
        InitiatingResponse initiatingResponse = httpRestTemplateService.postForObject(url, request, InitiatingResponse.class);
        log.info("franchiseAgreement API response:{}", JSONObject.toJSONString(initiatingResponse));
        if (initiatingResponse.getCode() != 0L) {
            throw new ServiceException(ErrorCodeEnum.FRANCHISE_AGREEMENT_FALSE, initiatingResponse.getMsg(),initiatingResponse.getData());
        } else {
            return new ResponseResult(200000, initiatingResponse.getMsg(), initiatingResponse.getData());
        }
    }


    @Override
    public Boolean getFirstOrder(String shopNum) {
        log.info("getFirstOrder shopNum:{}", shopNum);
        if (Objects.isNull(shopNum)) {
            throw new ServiceException(ErrorCodeEnum.PARAMS_VALIDATE_ERROR);
        }
        Map<String, Object> requestMap = new HashMap<>();
        fillSignatureInfo(requestMap);
        try {
            String url = xfsgUrl + Constants.FIRST_ORDER +
                    "?timestamp=" + requestMap.get("timestamp") + "&signature=" + requestMap.get("signature") +
                    "&storeCode=" + shopNum;
            Long start = System.currentTimeMillis();
            JSONObject jsonObject = httpRestTemplateService.getForObject(url, JSONObject.class, new HashMap<>());
            log.info("get url:{},jsonObject:{},耗时：{}", url, jsonObject,System.currentTimeMillis() - start);
            Boolean flag = (Boolean) jsonObject.get("data");
            return flag;
        } catch (Exception e) {
            log.error("获取鲜丰订货金异常", e);
            throw new ServiceException(ErrorCodeEnum.GET_FIRST_ORDER);
        }
    }

    @Override
    public xfsgFirstOderListResponse getFirstOrderList(xfsgFirstOrderListRequest storeCodeList) {
        log.info("getFirstOrderList storeCodeList:{}", storeCodeList);
        if (Objects.isNull(storeCodeList)) {
            throw new ServiceException(ErrorCodeEnum.PARAMS_VALIDATE_ERROR);
        }
        Map<String, Object> requestMap = new HashMap<>();
        fillSignatureInfo(requestMap);
        try {
            String url = xfsgUrl + Constants.BATCH_FIRST_ORDER +
                    "?timestamp=" + requestMap.get("timestamp") + "&signature=" + requestMap.get("signature");
            xfsgFirstOderListResponse xfsgFirstOderListResponse = httpRestTemplateService.postForObject(url, storeCodeList, xfsgFirstOderListResponse.class);
            return xfsgFirstOderListResponse;
        } catch (Exception e) {
            log.error("获取鲜丰订货金异常", e);
        }
        return null;
    }


    @Override
    public GetStoreInfoByCodeResponse getStoreInfoCode(String storeNum) {
        log.info("getStoreInfoCode storeNum:{}", storeNum);
        if (StringUtils.isBlank(storeNum)) {
            throw new ServiceException(ErrorCodeEnum.STORE_NUM_NOT_FOUND);
        }
        Map<String, Object> requestMap = new HashMap<>();
        fillSignatureInfo(requestMap);
        requestMap.put("storeCode", storeNum);
        String url = xfsgUrl + Constants.GET_STORE_INFO_BY_CODE + "?timestamp=" + requestMap.get("timestamp") + "&signature=" + requestMap.get("signature");
        GetStoreInfoByCodeResponse response = httpRestTemplateService.getForObject(url, GetStoreInfoByCodeResponse.class, requestMap);
        return response;
    }


    private void fillSignatureInfo(Map<String, Object> requestMap) {
        long timestamp = System.currentTimeMillis();
        String signature = SecureUtil.getSignature(timestamp);
        requestMap.put("timestamp", timestamp);
        requestMap.put("signature", signature);
    }

}
