package com.citygis.web.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.citygis.common.core.domain.AjaxResult;
import com.citygis.common.core.domain.entity.SysUser;
import com.citygis.system.service.ISysUserService;
import com.citygis.web.domain.TabUser;
import com.citygis.web.mapper.TabUserMapper;
import com.citygis.web.service.ITabUserService;
import com.citygis.web.utils.AesUtil;
import com.citygis.web.utils.SM4Util;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 登录用户 服务实现类
 * </p>
 *
 * @author citygis
 * @since 2025-01-13
 */
@Service
public class TabUserServiceImpl extends ServiceImpl<TabUserMapper, TabUser> implements ITabUserService {

    private static final Logger logger = LoggerFactory.getLogger(TabUserServiceImpl.class);

    @Value("${paiLaUserUrl.userUrl}")
    private String userUrl;

    @Value("${paiLaUserUrl.callbackUrl}")
    private String callbackUrl;

    @Value("${paiLaUserUrl.key}")
    private String key;

    @Resource
    private ISysUserService sysUserService;

    @Override
    @Transactional
    public AjaxResult insertTabUser(TabUser tabUser) {
        Snowflake snowflake = IdUtil.getSnowflake(1, 1);
        long id = snowflake.nextId();
        tabUser.setId(id);

        LambdaQueryWrapper<TabUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TabUser::getUserId, tabUser.getUserId());
        TabUser one = this.getOne(queryWrapper);

        if (one != null) {
            tabUser.setPassword(AesUtil.aesEncrypt(tabUser.getPassword()));
            this.update(tabUser, queryWrapper);
        } else {
            tabUser.setPassword(AesUtil.aesEncrypt(tabUser.getPassword()));
            this.save(tabUser);
        }

        return AjaxResult.success("添加成功");
    }

    @Override
    public void userSynchronous() {
        forwardRequest(userUrl);
    }

    public void forwardRequest(String url) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url);
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                HttpEntity entity = response.getEntity();
                String responseString = EntityUtils.toString(entity);
                parseJsonResponse(responseString);
            }
        } catch (IOException e) {
            handleException(e);
        }
    }

    public void parseJsonResponse(String jsonResponse) {
        Map<String, Object> requestData = new HashMap<>();
        JSONArray errors = new JSONArray();
        StringBuilder ids = new StringBuilder();

        try {
            JSONObject rootNode = JSONObject.parseObject(jsonResponse);
            JSONObject dataNode = rootNode.getJSONObject("data");
            JSONArray listNode = dataNode.getJSONArray("list");

            for (int i = 0; i < listNode.size(); i++) {
                JSONObject accountNode = listNode.getJSONObject(i);
                SysUser sysUser = extractSysUserFromAccountNode(accountNode);

                int insertResult = sysUserService.insertUser(sysUser);
                if (insertResult == 1) {
                    appendRequestId(ids, sysUser.getRequestLogId());
                } else {
                    addError(errors, sysUser.getRequestLogId(), "保存失败");
                }
            }

            requestData.put("ids", ids.toString());
            requestData.put("errors", errors);
            callback(requestData);
        } catch (Exception e) {
            handleException(e);
        }
    }

    private SysUser extractSysUserFromAccountNode(JSONObject accountNode) throws Exception {
        SysUser sysUser = new SysUser();
        String accountName = accountNode.getString("app_account__account_name");
        String accountNo = accountNode.getString("app_account__account_no");
        String password = accountNode.getString("request_log__account_pwd");
        String requestLogId = accountNode.getString("request_log__id");

        SM4Util sm4Util = SM4Util.getInstance(key);
        String decryptBase64 = sm4Util.decryptBase64(password);

        sysUser.setUserName(accountNo);
        sysUser.setNickName(accountName);
        sysUser.setPassword(decryptBase64);
        sysUser.setCreateBy("用户同步");
        sysUser.setRequestLogId(requestLogId);

//        printUserInfo(accountNode, sysUser);

        return sysUser;
    }

//    private void printUserInfo(JSONObject accountNode, SysUser sysUser) {
//        logger.info("帐号名称: {}", sysUser.getNickName());
//        logger.info("帐号: {}", sysUser.getUserName());
//        logger.info("状态: {}", accountNode.getString("app_account__status"));
//
//        JSONArray jobsNode = accountNode.getJSONArray("jobs");
//        for (int j = 0; j < jobsNode.size(); j++) {
//            JSONObject jobNode = jobsNode.getJSONObject(j);
//            logger.info("岗位编码: {}, 岗位名称: {}", jobNode.getString("idt_job__code"), jobNode.getString("idt_job__name"));
//        }
//
//        JSONArray orgsNode = accountNode.getJSONArray("orgs");
//        for (int k = 0; k < orgsNode.size(); k++) {
//            JSONObject orgNode = orgsNode.getJSONObject(k);
//            logger.info("组织名称: {}", orgNode.getString("idt_org__name"));
//        }
//    }

    private void appendRequestId(StringBuilder ids, String requestId) {
        if (ids.length() > 0) {
            ids.append(",");
        }
        ids.append(requestId);
    }

    private void addError(JSONArray errors, String id, String msg) {
        Map<String, String> error = new HashMap<>();
        error.put("id", id);
        error.put("msg", msg);
        errors.add(error);
    }

    public void callback(Map<String, Object> requestData) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(callbackUrl);
            httpPost.setHeader("Content-Type", "application/json");
            StringEntity entity = new StringEntity(JSON.toJSONString(requestData));
            httpPost.setEntity(entity);

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                HttpEntity responseEntity = response.getEntity();
                String responseString = EntityUtils.toString(responseEntity);
                logger.info("响应内容: {}", responseString);
            }
        } catch (IOException e) {
            handleException(e);
        }
    }

    private void handleException(Exception e) {
        logger.error("发生异常", e);
    }
}



