package com.bocloud.ims.service.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bocloud.common.encrypt.DESEncrptor;
import com.bocloud.common.encrypt.Encryptor;
import com.bocloud.common.enums.PostDataFormat;
import com.bocloud.common.http.HttpClient;
import com.bocloud.common.model.BocloudResult;
import com.bocloud.common.model.Result;
import com.bocloud.ims.entity.dto.OaNotifyTodoAppResult;
import com.bocloud.ims.service.internal.SmsSystemConfigService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * OA待办消息处理
 *
 * @author sxp
 * @since 2023/6/30
 */
@Service
public class ZjkyOAService {
    private static final Logger logger = LoggerFactory.getLogger(ZjkyOAService.class);

    @Autowired
    private SmsSystemConfigService smsSystemConfigService;

    private static String URI_SEND_TODO = "/api/sys-notify/sysNotifyTodoRestService/sendTodo";
    private static String URI_SET_TODO_DONE = "/api/sys-notify/sysNotifyTodoRestService/setTodoDone";

    /**
     * 发送待办信息
     *
     * @author sxp
     * @since 2023/7/4
     */
    public BocloudResult<OaNotifyTodoAppResult> sendTodo(Map<String, Object> params) {
        boolean enable = this.getOaEnable();
        if (!enable) {
            return new BocloudResult(true, "OA系统通知未启用");
        }

        HttpClient httpClient = new HttpClient();
        try {
            httpClient.setDataFormat(PostDataFormat.RAW);
            Map<String, Object> header = this.buildHeader();
            String url = this.getOaUrl();

            String username = this.getOaUsername();
            String password = this.getOaPwd();
            if (StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password)) {
                addAuth(header, username + ":" + password);
            }

            Result result = httpClient.post(header, params, url + URI_SEND_TODO);
            return this.assembleResult(result);
        } catch (Exception e) {
            logger.warn("发送待办信息出错", e);
            return new BocloudResult(false, "发送待办信息出错，错误原因为:" + e.getMessage());
        } finally {
            httpClient.close();
        }
    }

    /**
     * 设置待办信息为已办
     *
     * @author sxp
     * @since 2023/7/4
     */
    public BocloudResult<OaNotifyTodoAppResult> setTodoDone(Map<String, Object> params) {
        boolean enable = this.getOaEnable();
        if (!enable) {
            return new BocloudResult(true, "OA系统通知未启用");
        }

        HttpClient httpClient = new HttpClient();
        try {
            httpClient.setDataFormat(PostDataFormat.RAW);
            Map<String, Object> header = this.buildHeader();
            String url = this.getOaUrl();

            String username = this.getOaUsername();
            String password = this.getOaPwd();
            if (StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password)) {
                addAuth(header, username + ":" + password);
            }
            Result result = httpClient.post(header, params, url + URI_SET_TODO_DONE);
            return this.assembleResult(result);
        } catch (Exception e) {
            logger.warn("设置待办信息为已办出错", e);
            return new BocloudResult(false, "设置待办信息为已办出错，错误原因为:" + e.getMessage());
        } finally {
            httpClient.close();
        }
    }


    private Map<String, Object> buildHeader() {
        Map<String, Object> header = new HashMap<>();
        header.put("Content-type", "application/json");
        return header;
    }

    private BocloudResult<OaNotifyTodoAppResult> assembleResult(Result response) {
        try {
            if (response.isSuccess()) {
                OaNotifyTodoAppResult result = JSON.parseObject(response.getMessage(), OaNotifyTodoAppResult.class);
                //0:表示未操作,1:表示操作失败,2:表示操作成功
                Integer returnState = result.getReturnState();
                if (returnState == null) {
                    returnState = 0;
                }
                if (returnState.intValue() == 2 || returnState.intValue() == 0) {
                    return new BocloudResult(true, result, "success");
                } else {
                    return new BocloudResult(false, null, result.getMessage());
                }
            } else {
                return new BocloudResult(false, null, response.getMessage());
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return new BocloudResult(false, e.getMessage());
        }
    }

    private static void addAuth(Map<String, Object> headers, String yourEncryptedWorlds) {
        byte[] encodedAuth = org.springframework.security.crypto.codec.Base64.encode(yourEncryptedWorlds.getBytes(Charset.forName("UTF-8")));
        String authHeader = "Basic " + new String(encodedAuth);
        headers.put("Authorization", authHeader);
    }

    public boolean getOaEnable() {
        JSONObject configJson = smsSystemConfigService.getJSONObjectByCode("zjkyOaEnable");
        if (configJson == null || configJson.isEmpty()) {
            logger.info("未获取到是否启用OA系统通知参数配置，视为不启用");
            return false;
        }
        String value = configJson.getString("zjkyOaEnable");
        if (value != null) {
            value = value.trim();
        }
        if ("true".equalsIgnoreCase(value)) {
            return true;
        }
        return false;
    }

    private String getOaUrl() {
        JSONObject configJson = smsSystemConfigService.getJSONObjectByCode("zjkyOaUrl");
        Assert.notNull(configJson, "OA系统地址未配置");
        String value = configJson.getString("zjkyOaUrl");
        if (value != null) {
            value = value.trim();
        }
        Assert.notNull(value, "OA系统地址未配置");
        return value;
    }

    private String getOaUsername() {
        JSONObject configJson = smsSystemConfigService.getJSONObjectByCode("zjkyOaUsername");
        if (configJson == null || configJson.isEmpty()) {
            return null;
        }
        String value = configJson.getString("zjkyOaUsername");
        if (value != null) {
            value = value.trim();
        }
        Assert.notNull(value, "OA系统用户名未配置");
        return value;
    }

    private String getOaPwd() {
        JSONObject configJson = smsSystemConfigService.getJSONObjectByCode("zjkyOaPwd");
        if (configJson == null || configJson.isEmpty()) {
            return null;
        }
        String value = configJson.getString("zjkyOaPwd");
        if (value != null) {
            value = value.trim();
        }
        Assert.notNull(value, "OA系统密码未配置");

        String originPassword;
        try {
            Encryptor encryptor = new DESEncrptor();
            originPassword = encryptor.encrypt(value, "BocloudCMP");
        } catch (Exception e) {
            logger.error("OA系统密码解密失败，视为null");
            originPassword = null;
        }

        return originPassword;
    }
}
