package nckd.jimin.jyyy.hr.tsrsc.plugin.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.exception.KDException;
import kd.bos.ext.ssc.util.DateUtil;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.openapi.common.custom.annotation.*;
import kd.bos.openapi.common.result.CustomApiResult;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import nckd.jimin.jyyy.hr.tsrsc.plugin.util.MokaApiUtil;


import java.io.IOException;
import java.io.Serializable;
import java.util.Date;
import java.util.UUID;

/**
 * Moka跳转金蝶：根据操作人邮箱返回对应跳转地址
 * api编码：data/redirectUrl
 * Tyx
 * 2025-06-13
 */
@ApiController(value = "moka", desc = "Moka")
@ApiMapping("/data")
public class MokaRedirectUrlApi implements Serializable {
    private static final Log log = LogFactory.getLog(MokaRedirectUrlApi.class);

    /**
     * 金蝶环境地址
     */
    private String kingdeeUrl = System.getProperty("domain.contextUrl") + "/";


    @ApiPostMapping(value = "/redirectUrl", desc = "根据操作人邮箱返回对应跳转地址")
    public CustomApiResult<@ApiResponseBody JSONObject> pushRedirectUrl(
            @ApiParam(value = "候选人信息", required = true) JSONObject data
    ) {
        try {
            // 操作人邮箱
            String email = data.getJSONObject("operator").getString("number");
            if (email == null) {
                log.error("MokaRedirectUrlApi:入参工号为空");
                throw new KDException("入参工号为空");
            }
            JSONObject responseJson = getKingdeeToken();

            String accessToken = "";
            if ("0".equals(responseJson.getString("errorCode"))) {
                accessToken = responseJson.getJSONObject("data").getString("access_token");
            } else {
                log.error("MokaRedirectUrlApi:获取星瀚accessToken失败!{}", responseJson.getString("message"));
                throw new KDException("获取星瀚accessToken失败!" + responseJson.getString("message"));
            }

            // 新建表，将token和邮箱属性落库，并建立token和邮箱的映射关系，后续需根据token查询邮箱。
            DynamicObject mokaToken = BusinessDataServiceHelper.newDynamicObject("nckd_mokatoken");
            mokaToken.set("nckd_email", email);
            mokaToken.set("nckd_accesstoken", accessToken);
            SaveServiceHelper.save(new DynamicObject[]{mokaToken});

            // 拼接返回的url
            String redirectUrl = kingdeeUrl +
                    "?formId=pc_main_console" +
                    "&appNumber=tsrsc" +
                    "&token=" + accessToken +
                    "&thirdAppType=moka" +
                    "&accountId=" + RequestContext.get().getAccountId();

            /*
             *{
             *     "code": 200,
             *     "flag": false,
             *     "message": "成功111",
             *     "redirectUrl": {
             *         "mobileUrl": "http://www.baidu.com?name=1",
             *         "pcUrl": "http://www.baidu.com?name=1"
             *     }
             * }
             *
             */

            JSONObject responeData = new JSONObject()
                    .fluentPut("code", 200)
                    .fluentPut("flag", false)
                    .fluentPut("message", "成功111")
                    .fluentPut("redirectUrl", new JSONObject()
                            .fluentPut("mobileUrl", "")
                            .fluentPut("pcUrl", redirectUrl)
                    );

            return CustomApiResult.success(responeData);
        } catch (Exception e) {
            // 出现报错，返回默认的url
            log.error("MokaRedirectUrlApi出现异常:{}", e.getMessage());
            return CustomApiResult.success(new JSONObject()
                    .fluentPut("code", 200)
                    .fluentPut("flag", false)
                    .fluentPut("message", "成功111")
                    .fluentPut("redirectUrl", new JSONObject()
                            .fluentPut("mobileUrl", "")
                            .fluentPut("pcUrl", kingdeeUrl)
                    ));
        }
    }

    private JSONObject getKingdeeToken() throws IOException {
        // 获取该操作人的token
        String url = kingdeeUrl + "kapi/oauth2/getToken";
        //
        JSONObject body = new JSONObject()
                .fluentPut("client_id", MokaApiUtil.getParamValue("moka_client_id", "Moka_tomoka"))
                .fluentPut("client_secret", MokaApiUtil.getParamValue("moka_client_secret", "1q;E28%E@zY*Mo9y"))
                .fluentPut("username", MokaApiUtil.getParamValue("moka_username", "xinghanduiwaitongyongjiekouzhang"))
                .fluentPut("accountId", RequestContext.get().getAccountId())
                .fluentPut("nonce", UUID.randomUUID())
                .fluentPut("timestamp", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"))
                .fluentPut("language", "zh_CN");

        return MokaApiUtil.doKingdeePostByHttpClient(url, body);
    }


}
