package com.jwipc.sys.logic.impl;

import cn.hutool.core.util.StrUtil;
import com.jwipc.constant.OaProcessType;
import com.jwipc.exception.DaoException;
import com.jwipc.prop.SysProp;
import com.jwipc.security.LoginUtil;
import com.jwipc.sys.constant.SysOaClient;
import com.jwipc.sys.dto.OaSingleLoginRestDTO;
import com.jwipc.sys.logic.OaTrackLogic;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Objects;


/**
 * <p> </p>
 *
 * @author BOGON
 * @version 1.0
 * @since JDK 1.8
 */
@Service
@RequiredArgsConstructor
public class OaTrackLogicImpl implements OaTrackLogic {
    private final SysOaClient sysOaClient;
    private final SysProp sysProp;
    @Value("${sys.oa-supplier-change-view-id}")
    private String changeViewId;
    @Value("${sys.oa-supplier-create-view-id}")
    private String createViewId;

    @Override
    public String getUrl(String oaId, Integer type) throws UnsupportedEncodingException {
        final String account = LoginUtil.getAccount();
        final OaSingleLoginRestDTO oaSingleLoginRestDTO = sysOaClient.singleLogin(account);
        if (oaSingleLoginRestDTO.isResult()) {
        } else {
            throw new DaoException("OA单点登录失败:" + oaSingleLoginRestDTO.getErrorMsg());
        }
        //需要获
        final OaProcessType obj = OaProcessType.getObj(type);
        if (Objects.isNull(obj)) {
            throw new DaoException("审批类型未找到");
        }
        String url = obj.getUrl();
        if (obj.equals(OaProcessType.SUPPLIER_CHANGE)) {
            url = url.replace("${ID}", changeViewId);
        } else if (obj.equals(OaProcessType.SUPPLIER_ACCESS)) {
            url = url.replace("${ID}", createViewId);
        }
        final String pageUrl = StrUtil.format("{}{}{}", sysProp.getOaHost(), url, oaId);
        String encodedTarget = URLEncoder.encode(pageUrl, "UTF-8");
        final String urls = StrUtil.format("{}/sys/authentication/sso/login_auto.jsp?sessionId={}&target={}",
                sysProp.getOaHost(), oaSingleLoginRestDTO.getSessionId(), encodedTarget);
        return urls;
    }

    @Override
    public String getUrl(String url) throws UnsupportedEncodingException {
        final String account = LoginUtil.getAccount();
        final OaSingleLoginRestDTO oaSingleLoginRestDTO = sysOaClient.singleLogin(account);
        if (oaSingleLoginRestDTO.isResult()) {
        } else {
            throw new DaoException("OA单点登录失败:" + oaSingleLoginRestDTO.getErrorMsg());
        }
        String encodedTarget = URLEncoder.encode(url, "UTF-8");
        final String urls = StrUtil.format("{}/sys/authentication/sso/login_auto.jsp?sessionId={}&target={}",
                sysProp.getOaHost(), oaSingleLoginRestDTO.getSessionId(), encodedTarget);
        return urls;
    }
}