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

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.okki.account.entity.OkkiAccount;
import org.jeecg.modules.okki.account.mapper.OkkiAccountMapper;
import org.jeecg.modules.okki.account.service.IOkkiAccountService;
import org.jeecg.modules.okki.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * @Description: 小二账号
 * @Author: jeecg-boot
 * @Date:   2024-05-22
 * @Version: V1.0
 */
@Slf4j
@Service
public class OkkiAccountServiceImpl extends ServiceImpl<OkkiAccountMapper, OkkiAccount> implements IOkkiAccountService {

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

    @Value("${OKKI.CLIENT_SECRET}")
    private String CLIENT_SECRET;
    @Override
    public void insertAccount(OkkiAccount okkiAccount) {
        //创建小二账号
        // 请求okki平台接口
        Map<String, String> query = new TreeMap<>();
        query.put("sign_method", "hmac-md5");
        query.put("timestamp", String.valueOf(System.currentTimeMillis()));
        query.put("site_id", "sp_weichi");
        query.put("method", "dumpUser");
        Map<String, Object> postData = new HashMap<>();
        try {
            String queryStr = HttpClientUtils.buildQueryString(query);
            postData.put("email", okkiAccount.getAccount());
            postData.put("pwd", okkiAccount.getPassword());

            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)) {
                Object data = jsonObject.get("data");
                JSONObject jsonObject1 = JSONObject.parseObject(data.toString());
                Integer userId = (Integer) jsonObject1.get("user_id");
                Integer userStatus = (Integer) jsonObject1.get("user_status");
                okkiAccount.setUserId(userId);
                okkiAccount.setStatus(userStatus);
                //关联站点
                if (!okkiAccount.getSiteIds().equals("")) {
                    bindSites(okkiAccount);
                }
            }else {
                throw new RuntimeException(jsonObject.get("msg").toString());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateAccount(OkkiAccount okkiAccount) {
        // 站点关联
        // 请求okki平台接口
        Map<String, String> query = new TreeMap<>();
        query.put("sign_method", "hmac-md5");
        query.put("timestamp", String.valueOf(System.currentTimeMillis()));
        query.put("site_id", "sp_weichi");
        query.put("method", "bindSite");
        Map<String, Object> postData = new HashMap<>();
        try {
            String queryStr = HttpClientUtils.buildQueryString(query);
            postData.put("user_id", this.getById(okkiAccount.getId()).getUserId());
            // 字符串转数组
            String siteIds = okkiAccount.getSiteIds();
            String[] split = siteIds.split(",");
            postData.put("site_ids", split);
            postData.put("type", "update");

            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)) {
                this.updateById(okkiAccount);
            }else {
                throw new RuntimeException(jsonObject.get("msg").toString());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void bindSites(OkkiAccount okkiAccount) {
        // 请求okki平台接口
        Map<String, String> query = new TreeMap<>();
        query.put("sign_method", "hmac-md5");
        query.put("timestamp", String.valueOf(System.currentTimeMillis()));
        query.put("site_id", "sp_weichi");
        query.put("method", "bindSite");
        Map<String, Object> postData = new HashMap<>();
        try {
            String queryStr = HttpClientUtils.buildQueryString(query);
            postData.put("user_id", okkiAccount.getUserId());
            // 字符串转数组
            String siteIds = okkiAccount.getSiteIds();
            String[] split = siteIds.split(",");
            postData.put("site_ids", split);
            postData.put("type", "update");

            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)) {
                this.save(okkiAccount);
            }else {
                throw new RuntimeException(jsonObject.get("msg").toString());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
