package cn.pluss.platform.AppletStoreUser.impl;

import cn.pluss.platform.AppletStoreUser.AppletStoreUserService;
import cn.pluss.platform.appletInfo.AppletInfoService;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.enums.MccAndStore;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.mapper.AppletInfoMapper;
import cn.pluss.platform.mapper.AppletStoreMapper;
import cn.pluss.platform.mapper.AppletStoreUserMapper;
import cn.pluss.platform.mapper.MerchantStoreMapper;
import cn.pluss.platform.merchant.MerchantBaseInfoService;
import cn.pluss.platform.userInfo.UserInfoService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.BodyInserters;
import cn.pluss.platform.enums.MccAndStore;

import reactor.core.publisher.Mono;


import javax.annotation.Resource;
import java.util.Date;

/**
 * @author lyf
 */
@Service
public class AppletStoreUserServiceImpl extends ServiceImpl<AppletStoreUserMapper, AppletStoreUser> implements AppletStoreUserService {
    @Resource
    private AppletStoreUserMapper appletStoreUserMapper;
    @Resource
    private AppletStoreMapper appletStoreMapper;
    @Resource
    private MerchantBaseInfoService merchantBaseInfoService;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private MerchantStoreMapper merchantStoreMapper;
    @Override
    @Transactional(rollbackFor=Exception.class)
    public Integer addAppletStoreUser(AppletStoreUser appletStoreUser) {
        AppletStoreUser appletByUserStore = appletStoreUserMapper.getAppletByUserStore(appletStoreUser.getUserId(), appletStoreUser.getAppleStoreId());
        if (appletByUserStore != null){
            throw new MsgException("请勿重复绑定");
        }
        QueryWrapper<AppletStore> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", appletStoreUser.getAppleStoreId());
        AppletStore appletStore = appletStoreMapper.selectOne(queryWrapper);
        if (appletStore == null || appletStore.getType() == 0){
            throw new MsgException("未找到店铺号");
        }
        appletStoreUser.setCreateTime(new Date());



        int insert = baseMapper.insert(appletStoreUser);
        if (insert>0){
            MerchantBaseInfo merchantBaseInfo = merchantBaseInfoService.getMerchantBaseInfoByUserId(String.valueOf(appletStoreUser.getUserId()));
            if (merchantBaseInfo == null){
                throw new MsgException("未找到商户");
            }
            // 设置请求地址
            String url = "https://door.sxczgkj.cn/api/javaapp/apple/registeredstore";

            // 创建WebClient对象
            WebClient webClient = WebClient.builder().build();

            // 构造请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            // 构造请求参数
            StringBuilder params = new StringBuilder();

            params.append("title=").append(merchantBaseInfo.getAlias());
            //判断mcc码
            params.append("&mcc=").append(MccAndStore.findValueByStoreId(appletStoreUser.getAppleStoreId()));

            UserInfo userInfo = userInfoService.getMainUserInfo(Long.valueOf(merchantBaseInfo.getUserId()));
            params.append("&mobile=").append(userInfo.getPhone());

            QueryWrapper storQueryWrapper=  new QueryWrapper<>();
            storQueryWrapper.eq("merchantCode",merchantBaseInfo.getMerchantCode());
            MerchantStore merchantStore = merchantStoreMapper.selectOne(storQueryWrapper);
            params.append("&syb_m_id=").append(merchantStore.getId());
            params.append("&type=1");


            // 发送POST请求并获取响应
            Mono<String> response = webClient.post()
                    .uri(url)
                    .headers(httpHeaders -> httpHeaders.addAll(headers))
                    .body(BodyInserters.fromObject(params.toString()))
                    .retrieve()
                    .bodyToMono(String.class);
            // 响应结果判断
            String responseMsg = response.block();
            if (responseMsg.contains("\"code\":1")) {
                // 返回1
                return 1;
            }else {
                throw new MsgException("添加失败");
            }
        }

        throw new MsgException("店铺开通有误");
    }

    public static void main(String[] args) {
        // 设置请求地址
        String url = "http://47.122.2.126/notify/demo";

        // 创建WebClient对象
        WebClient webClient = WebClient.builder().build();

        // 构造请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        // 构造请求参数
        StringBuilder params = new StringBuilder();
        params.append("order_id=G1010317389703418481");
        params.append("&status=2");

        // 发送POST请求并获取响应
        Mono<String> response = webClient.post()
                .uri(url)
                .body(BodyInserters.fromObject(params.toString()))
                .headers(httpHeaders -> httpHeaders.addAll(headers))
                .retrieve()
                .bodyToMono(String.class);

        // 打印响应结果
        System.out.println(response.block());
    }
}
