package org.dromara.zhishu.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.json.ObjectMapper;
import com.alibaba.fastjson.JSONObject;
import com.pdd.pop.sdk.common.util.JsonUtil;
import com.pdd.pop.sdk.http.PopAccessTokenClient;
import com.pdd.pop.sdk.http.api.pop.response.PddMallInfoGetResponse;
import com.pdd.pop.sdk.http.token.AccessTokenResponse;
import io.swagger.v3.core.util.Json;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.dromara.common.core.config.RuoYiConfig;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.common.mybatis.core.domain.BaseEntity;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.sse.dto.SseMessageDto;
import org.dromara.common.sse.utils.SseMessageUtils;
import org.dromara.system.service.ISysConfigService;
import org.dromara.zhishu.domain.TUserPlatform;
import org.dromara.zhishu.domain.ZhishuShopGoods;
import org.dromara.zhishu.domain.bo.ShopBo;
import org.dromara.zhishu.domain.bo.ShopGoodsPublishedBo;
import org.dromara.zhishu.domain.vo.*;
import org.dromara.zhishu.service.*;
import org.dromara.zhishu.util.InterfaceUtils;
import org.dromara.zhishu.util.JsonObjUtil;
import org.dromara.zhishu.util.MapUtils;
import org.dromara.zhishu.util.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.AbstractView;
import org.springframework.web.servlet.view.RedirectView;

import java.io.IOException;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import static cn.dev33.satoken.SaManager.log;
import static org.dromara.zhishu.util.InterfaceUtils.getInterface;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/kongfz")
public class KongfzController {

    private final RuoYiConfig ruoYiConfig;

    private final IShopService shopService;

    private final IShopDetailService shopDetailService;

    private final ISysConfigService configService;

    private final IKongFzService kongFzService;

    private final IZhishuShopGoodsService zhishuShopGoodsService;

    private final IShopGoodsPublishedService shopGoodsPublishedService;


    @GetMapping("/toKongfzGetCode")
    @SaIgnore
    public String toKongfzGetCode(@RequestParam String id) {

        String phpUrl = configService.selectConfigByKey("php.url");

        String appId= "576";
        String state = id;
        String redirectUri = phpUrl + "/auth/callback";

        String authorizationUrl ="https://open.kongfz.com/v1/oauth2/authorize?" +
                "appId="+appId +
                "&responseType=code" +
                "&state="+state +
                "&redirectUri="+redirectUri;

        return authorizationUrl;
    }

    @SaIgnore
    @GetMapping("/phpCallBack")
    public ModelAndView phpCallBack() {
        return new ModelAndView(new RedirectView("http://" + ruoYiConfig.getIpurl() + "/shop/shop"));
    }

//    /**
//     * 孔夫子授权
//     */
//    @SaIgnore
//    @GetMapping("/toKongfzGetCode")
//    public R<Void> getAuthUrl(@RequestParam String id) {
//        ShopVo shopVo = shopService.queryById(Long.parseLong(id));
//
//        String account = shopVo.getAccount();
//        String password = shopVo.getPassword();
//        //获取php服务地址
//        String phpUrl = configService.selectConfigByKey("php.url");
//
//        try {
//            InterfaceUtils.getInterface(phpUrl, "/auth/getKongfuziAuthUrl/"+id+"/"+account+"/"+password);
//            Thread.sleep(2000); // 停止2秒
//        } catch (InterruptedException e) {
//            System.out.println("授权停止2秒异常");
//        } catch (Exception e) {
//            System.out.println("授权接口返回500异常");
//        }
//
//        return R.ok();
//    }



    /**
     * 获取运费模板
     */
    @GetMapping("/getTemplateSimpleList/{shopId}")
    public List getTemplateSimpleList(@PathVariable("shopId") String shopId){
        ShopVo shopVo = shopService.queryById(Long.parseLong(shopId));
        String kongfzIp = configService.selectConfigByKey("kongfz.ip");
        String templateSimpleListStr = getInterface(kongfzIp, "/api/kfz/getTemplateSimpleList/" + shopVo.getToken());
        List templateSimpleList  = JsonUtil.transferToObj(templateSimpleListStr, ArrayList.class);
        return templateSimpleList;
    }

    @GetMapping("/getCategory")
    @SaIgnore
    public String getCategory(String token){
        String content = RedisUtils.getCacheObject("categoryListStr");
        if (content == null || StringUtils.isEmpty(content)) {
            String kongfzIp = configService.selectConfigByKey("kongfz.ip");
            content = getInterface(kongfzIp, "/api/kfz/getCategory/" + token);
            RedisUtils.setCacheObject("categoryListStr", content);
        }
        return content;
    }
//
//    /**
//     * 商品发布
//     * @param shopId
//     * @param goodId
//     * @return
//     */
//    @SaIgnore
//    @GetMapping("/goodAdd/{shopId}/{goodId}")
//    public String goodAdd(@PathVariable("shopId") String shopId,@PathVariable("goodId") String goodId){
//
//        ShopDetailVo shopDetailVo = shopDetailService.queryByShopId(Long.parseLong(shopId));
//
//        ZhishuShopGoodsVo zhishuShopGoodsVo = zhishuShopGoodsService.queryById(goodId);
//
//        ZhishuShopGoods zhishuShopGoods = new ZhishuShopGoods();
//        zhishuShopGoods.setId(zhishuShopGoodsVo.getId());
//        zhishuShopGoods.setIsbn(zhishuShopGoodsVo.getIsbn());
//        zhishuShopGoods.setGoodsName(zhishuShopGoodsVo.getGoodsName());
//        zhishuShopGoods.setPrice(zhishuShopGoodsVo.getPrice());
//        zhishuShopGoods.setInventory(Long.parseLong(zhishuShopGoodsVo.getInventory()));
//        zhishuShopGoods.setArtNo(zhishuShopGoodsVo.getArtNo());
//        zhishuShopGoods.setConditionCode("L");
//        zhishuShopGoods.setUserId(1L);
//
//
//        kongFzService.goodAdd(shopId,zhishuShopGoods,shopDetailVo);
//
//        return "添加成功";
//    }

    /**
     * 增加接口
     * @param map
     * @return
     */
    @SaIgnore
    @PostMapping("/goodAddCallBack")
    public void goodAddCallBack(@RequestBody Map map){
//        System.out.println("erp调用新增已发布商品数据："+ JsonUtil.transferToJson(map));
        ShopGoodsPublishedBo bo = new ShopGoodsPublishedBo();
        bo.setShopGoodsId(map.get("goodId").toString());
        bo.setShopId(map.get("shopId").toString());
        bo.setPlatformId(map.get("itemId").toString());
        bo.setCreateBy(Long.parseLong(map.get("userId").toString()));
        bo.setCreateTime(DateUtils.parseDate(DateUtils.getTime()));
        bo.setUpdateTime(DateUtils.parseDate(DateUtils.getTime()));
//        System.out.println("封装数据:"+bo);
        shopGoodsPublishedService.insertByBo(bo);
    }
}
