package com.zfire.jiasm.syncdata.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.zfire.jiasm.syncdata.api.OrderAddBeanDTO;
import com.zfire.jiasm.syncdata.constant.Constant;
import com.zfire.jiasm.syncdata.plus.entity.AdminUser;
import com.zfire.jiasm.syncdata.plus.service.AdminUserService;
import com.zfire.jiasm.syncdata.service.JiasmApi;
import com.zfire.jiasm.syncdata.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

@Slf4j
@Service
public class JiasmApiImpl implements JiasmApi {
    @Value("${jiasmorderurl}")
    private String jiasmorderurl = "";
    @Autowired
    AdminUserService adminUserService;
    @Autowired
    RedisUtil redis;



    @Override
    public ResponseHelper orderAdd(@RequestBody OrderAddBeanDTO orderAddBeanDTO){
        ResponseHelper response=null;

        try {
            String token = getAccessToken();
            if(StringUtil.isEmpty(token)){
                response = new ResponseHelper(-1,"生成token失败【admin】用户不存在");
                redis.del(Constant.RedisPrefix.TOKEN_JIASM_ORDER);
                return response;
            }
            String dataStr = HttpUtil.httpRequestPostJiasm(jiasmorderurl, "POST", token,
                    JSONObject.toJSONString(orderAddBeanDTO));
            response = JSONObject.parseObject(dataStr, ResponseHelper.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

    //生成token
    private String getAccessToken() {
        String token = "";
        String redisKey = Constant.RedisPrefix.TOKEN_JIASM_ORDER;
        token = (String)redis.get(redisKey);
        if(StringUtil.isEmpty(token)){
            AdminUser adminUser = adminUserService.lambdaQuery()
                    .eq(AdminUser::getNickName, "admin").one();
            if (adminUser==null){
                return token;
            }
            token = JwtUtils.createJWT(adminUser.getAdminUserId(), adminUser.getNickName(), adminUser.getUserName(), 20 * 60 * 60 * 1000);
            //写入缓存
            redis.set(Constant.RedisPrefix.TOKEN_JIASM_ORDER, token,20 * 60 * 50 * 1000);
        }
        return token;
    }





}
