package com.ruoyi.interfaces.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.common.utils.RedisOperator;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.interfaces.domain.PtService;
import com.ruoyi.interfaces.domain.PtServiceLog;
import com.ruoyi.interfaces.domain.PtServiceParam;
import com.ruoyi.interfaces.domain.vo.MdModelInfoVo;
import com.ruoyi.interfaces.mapper.PtServiceMapper;
import com.ruoyi.interfaces.mapper.PtServiceParamMapper;
import com.ruoyi.interfaces.service.IMdModelInfoService;
import com.ruoyi.interfaces.service.PtServiceService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author LinQiLong
 * @date 2021/12/21 15:55
 */
@Service
public class PtServiceServiceImpl extends ServiceImpl<PtServiceMapper, PtService> implements PtServiceService {

    private final PtServiceMapper ptServiceMapper;

    private final RedisOperator redisOperator;
    @Autowired
    private IMdModelInfoService mdModelInfoService;

    @Autowired
    private PtServiceParamMapper ptServiceParamMapper;

    public PtServiceServiceImpl(PtServiceMapper ptServiceMapper, RedisOperator redisOperator) {
        this.ptServiceMapper = ptServiceMapper;
        this.redisOperator = redisOperator;
    }

    @Override
    public PtService insert(PtService ptService) {
        ptService.setSrvId(IdUtils.simpleUUID());
        ptService.setUserId(String.valueOf(SecurityUtils.getUserId()));
        int initNumber = 0;
        ptService.setCnt(initNumber);
        ptService.setViewNum(initNumber);
        ptService.setDataNum(initNumber);
        ptService.setApplyNum(initNumber);
        Date now = DateUtils.getNowDate();
        ptService.setTm(now);
        ptService.setRlstm(now);
        ptService.setReleaseTime(now);
        ptService.setUptm(now);
        ptServiceMapper.insert(ptService);
        if (CollectionUtils.isNotEmpty(ptService.getParams())) {
            ptService.getParams().forEach(ptServiceParamMapper::insert);
        }
        return ptService;
    }

    @Override
    public PtService update(PtService ptService) {
        ptServiceMapper.updateByPrimaryKeySelective(ptService);
        return ptServiceMapper.selectByPrimaryKey(ptService.getSrvId());
    }

    @Override
    public boolean saveOrUpdate(PtService ptService) {
        if (StringUtils.isNotBlank(ptService.getSrvId())) {
            update(ptService);
            return true;
        }
        insert(ptService);
        return true;
    }

    @Override
    public List<PtService> listOfCntTop10() {
        return ptServiceMapper.listOfCntTop10();
    }

    @Override
    public List<PtService> listOfTmTop20() {
        return ptServiceMapper.listOfTmTop20();
    }

    @Override
    public void refreshRankingList() {
        List<PtService> cntTop10 = listOfCntTop10();
        redisOperator.set("cntTop10", JSON.toJSONString(cntTop10));
        List<PtService> tmTop20 = listOfTmTop20();
        redisOperator.set("tmTop20", JSON.toJSONString(tmTop20));
    }

    @Override
    public Map<String, List<PtService>> getRankingList() {
        Map<String, List<PtService>> ret = new HashMap<>(2);
        String cntTop10Json = redisOperator.get("cntTop10");
        String tmTop20Json = redisOperator.get("tmTop20");
        List<PtService> cntTop10List = JsonUtils.jsonToList(cntTop10Json, PtService.class);
        List<PtService> tmTop20List = JsonUtils.jsonToList(tmTop20Json, PtService.class);
        ret.put("cntTop10", cntTop10List);
        ret.put("tmTop20", tmTop20List);
        return ret;
    }

    @Override
    public PtService get(String srvId) {
        return ptServiceMapper.selectByPrimaryKey(srvId);
    }

    /**
     * 获取模型关联服务
     *
     * @param par
     * @return
     */
    @Override
    public MdModelInfoVo modelService(MdModelInfoVo par) {

        return ptServiceMapper.selectModelService(par);
    }

    @Override
    public List<PtService> selectAllColumns(PtService ptService) {
        return ptServiceMapper.selectAllColumns(ptService);
    }

    @Override
    public int put(PtService ptService) {
        return ptServiceMapper.updateByPrimaryKeySelective(ptService);
    }


    @Override
    public String testRun(PtService ptService) throws IOException {

    /*    String tokenUrl = "http://localhost:9002/sh-api/login";
        String bodyPar = "{\n" +
                "  \"username\": \"admin\",\n" +
                "  \"password\": \"Gw#$1601\"\n" +
                "}";
        String token = "";

        try {
            token =  HttpUtils.sendBodyPostTest(tokenUrl,bodyPar,null);
            System.out.println(token);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        HashMap hashMap = JsonUtils.jsonToPojo(token, HashMap.class);
        String token1 = hashMap.get("token").toString();*/
        HashMap<String, String> headers = new HashMap<>();
        //List<PtServiceParam> ptServiceParams = ptServiceParamMapper.selectAll(ptService.getSrvId());
        //String paramString = ptServiceParams.stream().map(p -> p.getParamCode() + "=" + p.getParamValue()).collect(Collectors.joining());
        List<PtServiceParam> params = ptService.getParams();
        String paramString = "";
        switch (ptService.getRqtype()) {
            case "POST":
                HashMap<String, Object> parMap = new HashMap<>();
                for (PtServiceParam param : params) {
                    parMap.put(param.getParamCode(),param.getParamObject());
                }
               return HttpUtils.sendBodyPost(ptService.getUrl(),parMap,headers);
            case "GET":

                for (PtServiceParam param : params) {
                    paramString+=(param.getParamCode()+"="+param.getParamValue())+"&";
                }
                return HttpUtils.sendGet(ptService.getUrl(),paramString,headers);
        }
        return null;
    }

    @Override
    public int audit(String[] srvIds, String audit) {

        return ptServiceMapper.audit(srvIds,audit);
    }

    public void senServiceLog(){


    }
}
