package com.cool.store.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cool.store.dao.BigRegionDAO;
import com.cool.store.dao.ShopInfoDAO;
import com.cool.store.dto.HqtTokenDTO;
import com.cool.store.entity.BigRegionDO;
import com.cool.store.entity.ShopInfoDO;
import com.cool.store.enums.*;
import com.cool.store.enums.HqtEnum.*;
import com.cool.store.exception.ServiceException;
import com.cool.store.request.ConfirmQuotationRequest;
import com.cool.store.request.HqtBuildRequest;
import com.cool.store.request.HqtPartnerAcceptanceRequest;
import com.cool.store.request.hqt.*;
import com.cool.store.response.HqtAPIResponse;
import com.cool.store.service.HqtAPIService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Author: WangShuo
 * @Date: 2025/07/23/14:05
 * @Version 1.0
 * @注释:
 */
@Service
@Slf4j
public class HqtAPIServiceImpl implements HqtAPIService {
    @Value("${hqt.token.url}")
    private String hqtTokenUrl;

    @Value("${hqt.token.username}")
    private String hqtUsername;

    @Value("${hqt.token.grant_type}")
    private String hqtGrantType;

    @Value("${hqt.token.client.id}")
    private String hqtClientId;
    @Value("${hqt.token.client.secret}")
    private String hqtClientSecret;

    @Resource
    OkHttpClient okHttpClient;
    @Resource
    private ShopInfoDAO shopInfoDAO;
    @Resource
    private BigRegionDAO bigRegionDAO;

    @Override
    //@Async
    public void pushHqtBuild(HqtBuildRequest request) {
        log.info("开始推送门店信息request:{}",JSONObject.toJSONString(request));
        Boolean check = request.check();
        if (!check) {
            throw new ServiceException(ErrorCodeEnum.HQT_PARAMS_ERROR);
        }
        HqtTokenDTO hqtToken = this.getHqtToken();
        //构建门店装修属性
        HqtBuildAPIRequest.Field13__c field13__c = getField13__c(request);
        //构建所属片区
        HqtBuildAPIRequest.Field124__c field124__c = getField124__c(request);
        //构建是否已收设计费
        HqtBuildAPIRequest.Field8__c field8__c = getField8__c(request);
        //构建加盟品牌
        HqtBuildAPIRequest.Field123__c field123__c = getField123__c(request);

        HqtBuildAPIRequest hqtBuildAPIRequest = new HqtBuildAPIRequest();
        getHqtBuildAPIRequest(request, hqtBuildAPIRequest, field13__c, field124__c, field8__c, field123__c);
        // 特殊情况说明
        hqtBuildAPIRequest.setField195__c(request.getSpecialInstruction());
        // 装修设计要求
        HqtDecorationReqEnum decorationRequirement = HqtDecorationReqEnum.getByColumnCode(request.getDecorationRequirement());
        if (Objects.nonNull(decorationRequirement)) {
            hqtBuildAPIRequest.setField194__c(new HqtBuildAPIRequest.Field8__c(decorationRequirement.getCode(), decorationRequirement.getMsg()));
        }
        // 装修等级
        HqtDecorationLevelEnum decorationLevel = HqtDecorationLevelEnum.getByColumnCode(request.getDecorationLevel());
        if (Objects.nonNull(decorationLevel)) {
            hqtBuildAPIRequest.setField193__c(new HqtBuildAPIRequest.Field8__c(decorationLevel.getCode(), decorationLevel.getMsg()));
        }
        // 门店类型
        HqtStoreTypeEnum storeType = HqtStoreTypeEnum.getByStoreType(request.getStoreType());
        if (Objects.nonNull(storeType)) {
            hqtBuildAPIRequest.setField192__c(new HqtBuildAPIRequest.Field8__c(storeType.getCode(), storeType.getMsg()));
        }
        //资源服务URL
        String url = hqtToken.getEndPoint();
        String requestUrl = url + "/v1/data/objects/project3X";
        HqtAPIResponse hqtAPIResponse = sendPostRequest(JSONObject.toJSONString(hqtBuildAPIRequest), requestUrl, hqtToken);
        shopInfoDAO.updateHqtShopId(request.getShopId(), hqtAPIResponse.getData());
    }


    @Override
    // @Async
    public void confirmQuotation(ConfirmQuotationRequest request) {
        log.info("开始推送加盟商确认报价单信息request:{}",JSONObject.toJSONString(request));
        Boolean check = request.check();
        if (!check) {
            log.info("参数错误");
            throw new ServiceException(ErrorCodeEnum.HQT_PARAMS_ERROR);
        }
        //构建CRM系统门店编码（红圈通门店id）
        HqtQuotationSheetAPIRequest.Field1__c field1__c = new HqtQuotationSheetAPIRequest.Field1__c();
        field1__c.setCode(request.getHqtShopId());

        HqtTokenDTO hqtToken = this.getHqtToken();
        String requestUrl = hqtToken.getEndPoint() + "/v1/data/objects/CustomObject638__c";

        HqtQuotationSheetAPIRequest apiRequest = new HqtQuotationSheetAPIRequest();
        apiRequest.setField1__c(field1__c);
        apiRequest.setName__c(request.getQuotationSheetId());

        sendPostRequest(JSONObject.toJSONString(apiRequest), requestUrl, hqtToken);
    }

    //@Async
    @Override
    public void hqtPartnerAcceptance(HqtPartnerAcceptanceRequest request) {
        log.info("开始推送加盟商验收信息request:{}",JSONObject.toJSONString(request));
        if (!request.check()){
            log.info("参数错误");
            throw new ServiceException(ErrorCodeEnum.HQT_PARAMS_ERROR);
        }
        SatisfactionEnum satisfactionEnum = SatisfactionEnum.getEnumByCode(request.getSatisfaction());

        HqtTokenDTO hqtToken = this.getHqtToken();
        String requestUrl = hqtToken.getEndPoint() + "/v1/data/objects/CustomObject138__c";

        HqtPartnerAcceptanceAPIRequest apiRequest = getHqtPartnerAcceptanceAPIRequest(request, satisfactionEnum);

        sendPostRequest(JSONObject.toJSONString(apiRequest), requestUrl, hqtToken);
    }

    private static @NotNull HqtPartnerAcceptanceAPIRequest getHqtPartnerAcceptanceAPIRequest(HqtPartnerAcceptanceRequest request, SatisfactionEnum satisfactionEnum) {
        HqtPartnerAcceptanceAPIRequest apiRequest = new HqtPartnerAcceptanceAPIRequest();

        //加盟商满意度
        HqtPartnerAcceptanceAPIRequest.Field1__c field1__c = new HqtPartnerAcceptanceAPIRequest.Field1__c();
        if (satisfactionEnum != null){
            field1__c.setId(satisfactionEnum.getHqtCode());
            field1__c.setLabel(satisfactionEnum.getName());
            field1__c.setName(satisfactionEnum.getHqtCode());
        }
        //红圈通门店id
        HqtPartnerAcceptanceAPIRequest.Field13__c field13__c = new HqtPartnerAcceptanceAPIRequest.Field13__c();
        field13__c.setCode(request.getHqtShopId());

        apiRequest.setField1__c(field1__c);
        apiRequest.setField13__c(field13__c);
        apiRequest.setField14__c(request.getComment());
        return apiRequest;
    }

    @Override
    public BigRegionDO pushHqtRegion(BigRegionDO bigRegionDO) {
        HqtTokenDTO hqtToken = this.getHqtToken();
        String requestUrl = hqtToken.getEndPoint() + "/v1/data/objects/CustomObject494__c";

        Map<String, String> requestBody = new HashMap<>();
        requestBody.put("name",bigRegionDO.getRegionName());
        HqtAPIResponse responseBody = sendPostRequest(JSONObject.toJSONString(requestBody), requestUrl, hqtToken);
        String hqtRegionCode = responseBody.getData();

        bigRegionDO.setHqtRegionCode(hqtRegionCode);
        bigRegionDO.setHqtRegionName(bigRegionDO.getRegionName());
        bigRegionDAO.updateHqtDate(bigRegionDO);
        return bigRegionDO;
    }

    private  HqtAPIResponse  sendPostRequest(String requestBody, String requestUrl,HqtTokenDTO hqtToken ){
        log.info("开始发送请求,url:{},requestBody:{}",requestUrl,requestBody);
        Request request = new Request.Builder()
                .url(requestUrl)
                .post(RequestBody.create(MediaType.parse( "application/json"),requestBody))
                .addHeader("Authorization", "Bearer " + hqtToken.getAccess_token())
                .addHeader("Content-Type", "application/json")
                .build();
        try (Response response = okHttpClient.newCall(request).execute()) {
            log.info("发起请求 time：{}",System.currentTimeMillis());
            if (!response.isSuccessful()) {
                log.info("HTTP请求失败，msg: " + response.message());
                throw new ServiceException(ErrorCodeEnum.THIRD_API_ERROR,
                        "HTTP请求失败，状态码: " + response.code());
            }
            String responseBody = response.body().string();
            log.info("请求成功responseBody:{}",JSONObject.toJSONString(responseBody));
            HqtAPIResponse hqtAPIResponse = JSONObject.parseObject(responseBody, HqtAPIResponse.class);
            return hqtAPIResponse;
        } catch (ServiceException e) {
            throw e;
        } catch (Exception e) {
            log.error("API调用异常 - URL: {}, 错误: {}", requestUrl, e.getMessage(), e);
            throw new ServiceException(ErrorCodeEnum.THIRD_API_ERROR, "接口调用异常: " + e.getMessage());
        }
    }


    private static void getHqtBuildAPIRequest(HqtBuildRequest request, HqtBuildAPIRequest hqtBuildAPIRequest,  HqtBuildAPIRequest.Field13__c field13__c, HqtBuildAPIRequest.Field124__c field124__c, HqtBuildAPIRequest.Field8__c field8__c, HqtBuildAPIRequest.Field123__c field123__c) {
        hqtBuildAPIRequest.setProjectNo(request.getShopId().toString());
        hqtBuildAPIRequest.setName(request.getShopName());
        hqtBuildAPIRequest.setField13__c(field13__c);
        hqtBuildAPIRequest.setField124__c(field124__c);
        hqtBuildAPIRequest.setField94__c(request.getSupervisorName());
        hqtBuildAPIRequest.setField4__c(request.getSupervisorMobile());
        hqtBuildAPIRequest.setField5__c(request.getPartnershipSignatoryFirst());
        hqtBuildAPIRequest.setField6__c(request.getPartnershipSignatoryFirstMobile());
        hqtBuildAPIRequest.setStreet(request.getShopAddress());
        hqtBuildAPIRequest.setField8__c(field8__c);
        hqtBuildAPIRequest.setField123__c(field123__c);
        hqtBuildAPIRequest.setField4__c(request.getSupervisorMobile());
        hqtBuildAPIRequest.setField190__c(request.getOperationsConsultant());
        hqtBuildAPIRequest.setField188__c(request.getInvestRegionName());
        hqtBuildAPIRequest.setField191__c(request.getEmail());
        hqtBuildAPIRequest.setField197__c(request.getInvestRegionEmail());
    }

    private HqtBuildAPIRequest.Field123__c getField123__c(HqtBuildRequest request) {
        FranchiseBrandEnum franchiseBrand = FranchiseBrandEnum.getEnumByCode(request.getFranchiseBrand());
        if (franchiseBrand != null) {
            HqtBuildAPIRequest.Field123__c field123__c = new HqtBuildAPIRequest.Field123__c();
            field123__c.setId(field123__c.getId() + franchiseBrand.getHqtCode());
            field123__c.setLabel(franchiseBrand.getDesc());
            field123__c.setName(franchiseBrand.getHqtCode());
            field123__c.setPath(field123__c.getPath() + franchiseBrand.getHqtCode());
            return field123__c;
        }
        return new HqtBuildAPIRequest.Field123__c();
    }

    private  HqtBuildAPIRequest.Field13__c getField13__c(HqtBuildRequest request) {
        HqtBuildAPIRequest.Field13__c field13__c = new  HqtBuildAPIRequest.Field13__c();
        //获取门店装修属性
        ShopDecorationAttributesEnum shopDecorationAttributesEnum = ShopDecorationAttributesEnum.getShopDecorationAttributesEnumByCode(request.getShopDecorationAttributes());
        HqtShopDecorationAttributesEnum hqtShopDecorationAttributesEnum = HqtShopDecorationAttributesEnum.getHqtShopDecorationAttributesEnumByShopDecorationAttributesEnum(shopDecorationAttributesEnum);
        if (hqtShopDecorationAttributesEnum == null) {
            throw new ServiceException(ErrorCodeEnum.HQT_SHOP_DECORATION_ATTRIBUTES);
        }
        field13__c.setId(hqtShopDecorationAttributesEnum.getCode());
        field13__c.setLabel(hqtShopDecorationAttributesEnum.getMsg());
        field13__c.setName(hqtShopDecorationAttributesEnum.getCode());
        return field13__c;
    }

    private HqtBuildAPIRequest.Field124__c getField124__c(HqtBuildRequest request) {
        HqtBuildAPIRequest.Field124__c field124__c = new HqtBuildAPIRequest.Field124__c();
        field124__c.setCode(request.getHqtRegionCode());
        field124__c.setName(request.getHqtRegionName());
        return field124__c;
    }

    private HqtBuildAPIRequest.Field8__c getField8__c(HqtBuildRequest request) {
        HqtSignFeeEnum hqtSignFee = HqtSignFeeEnum.getCodeByValue(request.getIsPayDesignFee());
        if (hqtSignFee != null) {
            HqtBuildAPIRequest.Field8__c field8__c = new HqtBuildAPIRequest.Field8__c();
            field8__c.setId(hqtSignFee.getCode());
            field8__c.setLabel(hqtSignFee.getMsg());
            field8__c.setName(hqtSignFee.getCode());
            return field8__c;
        }
        return new HqtBuildAPIRequest.Field8__c();

    }
    public HqtTokenDTO getHqtToken() {
        String url = hqtTokenUrl + "/hecom-tenancy/oauth/token";
        String auth = hqtClientId + ":" + hqtClientSecret;
        String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
        RequestBody formBody = new FormBody.Builder()
                .add("grant_type", hqtGrantType)
                .add("username", hqtUsername)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .addHeader("Authorization", "Basic " + encodedAuth)
                .addHeader("Host", "tc.cloud.hecom.cn")
                .build();
        try (Response response = okHttpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                log.info("HTTP请求失败，msg: " + response.message());
                throw new ServiceException(ErrorCodeEnum.THIRD_API_ERROR,
                        "HTTP请求失败，状态码: " + response.code());
            }
            String responseBody = response.body().string();
            HqtTokenDTO hqtTokenDTO = JSONObject.parseObject(responseBody, HqtTokenDTO.class);
            return hqtTokenDTO;
        } catch (ServiceException e) {
            throw e;
        } catch (Exception e) {
            log.error("API调用异常 - URL: {}, 错误: {}", url, e.getMessage(), e);
            throw new ServiceException(ErrorCodeEnum.THIRD_API_ERROR, "接口调用异常: " + e.getMessage());
        }
    }
}
