package org.jeecg.modules.okki.site.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.okki.site.entity.OkkiSite;
import org.jeecg.modules.okki.site.entity.OkkiSiteStatusChangeLog;
import org.jeecg.modules.okki.site.mapper.OkkiSiteMapper;
import org.jeecg.modules.okki.site.param.ChangeSiteStatusParam;
import org.jeecg.modules.okki.site.service.IOkkiSiteService;
import org.jeecg.modules.okki.site.service.IOkkiSiteStatusChangeLogService;
import org.jeecg.modules.okki.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * @Description: 站点
 * @Author: jeecg-boot
 * @Date:   2024-04-29
 * @Version: V1.0
 */
@Slf4j
@Service
public class OkkiSiteServiceImpl extends ServiceImpl<OkkiSiteMapper, OkkiSite> implements IOkkiSiteService {

    @Value("${OKKI.BASE_URL}")
    private String URL;

    @Value("${OKKI.CLIENT_SECRET}")
    private String CLIENT_SECRET;

    @Resource
    private OkkiSiteMapper okkiSiteMapper;

    @Resource
    private IOkkiSiteStatusChangeLogService okkiSiteStatusChangeLogService;

    @Override
    public boolean updateBySiteId(OkkiSite okkiSite) {
        QueryWrapper<OkkiSite> okkiSiteQueryWrapper = new QueryWrapper<>();
        okkiSiteQueryWrapper.eq("site_id", okkiSite.getSite_id());
        okkiSiteQueryWrapper.last("limit 1");
        OkkiSite okkiSite1 = okkiSiteMapper.selectOne(okkiSiteQueryWrapper);
        okkiSite.setId(okkiSite1.getId());
        int result = okkiSiteMapper.updateById(okkiSite);
        if (result == 0) {
            return false;
        }else {
            return true;
        }
    }

    @Override
    public boolean changeStatus(OkkiSite okkiSite) {
        // 请求okki平台接口
        Map<String, String> query = new TreeMap<>();
        query.put("sign_method", "hmac-md5");
        query.put("timestamp", String.valueOf(System.currentTimeMillis()));
        query.put("site_id", String.valueOf(okkiSite.getSite_id()));
        query.put("method", "update_service_node");
        // 通过site_id获取当前站点数据status的值 +1
        QueryWrapper<OkkiSite> okkiSiteQueryWrapper = new QueryWrapper<>();
        okkiSiteQueryWrapper.eq("site_id", okkiSite.getSite_id());
        okkiSiteQueryWrapper.last("limit 1");
        OkkiSite okkiSite1 = okkiSiteMapper.selectOne(okkiSiteQueryWrapper);
        okkiSite.setId(okkiSite1.getId());
        okkiSite.setStatus(okkiSite1.getStatus()+1);
        Map<String, Object> postData = new HashMap<>();
        postData.put("status", okkiSite1.getStatus()+1);
        try {
            String queryStr = HttpClientUtils.buildQueryString(query);
            String body = HttpClientUtils.toJsonString(postData);
            String signStr = queryStr + body;
            query.put("signature", HttpClientUtils.generateHmacMD5(signStr, CLIENT_SECRET));
            String okkiUrl = URL + "?" + HttpClientUtils.buildQueryString(query);
            log.info("url:" + okkiUrl + ",body:" + body);
            String res = HttpClientUtils.doPost(okkiUrl, body);
            log.info(res);
            // {"code":0,"msg":"success","now":"2024-05-06 15:34:54","data":[]}
            JSONObject jsonObject= JSONObject.parseObject(res);
            if (jsonObject.get("code").equals(0)) {
                int result = okkiSiteMapper.updateById(okkiSite);
                if (result == 0) {
                    return false;
                }else {
                    OkkiSiteStatusChangeLog okkiSiteStatusChangeLog = new OkkiSiteStatusChangeLog();
                    okkiSiteStatusChangeLog.setOkkiSiteId(okkiSite.getSite_id());
                    okkiSiteStatusChangeLog.setOldStatus(okkiSite1.getStatus());
                    okkiSiteStatusChangeLog.setNewStatus(okkiSite.getStatus());
                    okkiSiteStatusChangeLogService.save(okkiSiteStatusChangeLog);
                    return true;
                }
            }else {
                throw new RuntimeException(jsonObject.get("msg").toString());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean okkiChangeStatus(ChangeSiteStatusParam param) {
        OkkiSite okkiSite = new OkkiSite();
        QueryWrapper<OkkiSite> okkiSiteQueryWrapper = new QueryWrapper<>();
        okkiSiteQueryWrapper.eq("site_id", param.getSite_id());
        okkiSiteQueryWrapper.last("limit 1");
        OkkiSite okkiSite1 = okkiSiteMapper.selectOne(okkiSiteQueryWrapper);
        okkiSite.setId(okkiSite1.getId());
        okkiSite.setStatus(param.getStatus());
        int result = okkiSiteMapper.updateById(okkiSite);
        if (result == 0) {
            return false;
        }else {
            OkkiSiteStatusChangeLog okkiSiteStatusChangeLog = new OkkiSiteStatusChangeLog();
            okkiSiteStatusChangeLog.setOkkiSiteId(param.getSite_id());
            okkiSiteStatusChangeLog.setOldStatus(okkiSite1.getStatus());
            okkiSiteStatusChangeLog.setNewStatus(param.getStatus());
            okkiSiteStatusChangeLogService.save(okkiSiteStatusChangeLog);
            return true;
        }
    }

    @Override
    public boolean insertSite(OkkiSite okkiSite) {
        OkkiSite okkiSite1 = okkiSiteMapper.selectOne(new LambdaQueryWrapper<OkkiSite>().eq(OkkiSite::getSite_id, okkiSite.getSite_id()));
        if (okkiSite1 != null) {
            throw new RuntimeException("site_id already exist");
        }else {
            return super.save(okkiSite);
        }
    }
}
