package com.kingdee.shr.base.syssetting.web.handler;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.eas.base.permission.PermItemInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.shr.base.permission.api.service.SHRFunctionPermissionService;
import com.kingdee.shr.base.syssetting.app.cache.PermItemURLCache;
import com.kingdee.shr.base.syssetting.context.SHRContext;
import com.kingdee.shr.base.syssetting.exception.SHRWebException;
import com.kingdee.shr.base.syssetting.exception.ShrWebBizException;
import com.kingdee.shr.base.syssetting.ml.SHRWebResource;
import com.kingdee.shr.base.syssetting.util.FileOperateUtil;
import com.kingdee.shr.base.syssetting.util.SHRSyssettingUtil;
import com.kingdee.shr.websso.IWSUser;
import com.kingdee.shr.websso.WSUserFactory;
import com.kingdee.shr.websso.WSUserInfo;
import com.kingdee.util.StringUtils;
import com.kingdee.util.UuidException;
import org.apache.log4j.Logger;
import org.springframework.ui.ModelMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Properties;

/**
 * description: WSUserEditHandler <br>
 * date: 20/11/2025 ÉÏÎç 11:19 <br>
 * author: lhbj <br>
 * version: 1.0 <br>
 */
public class WSUserEditHandler extends EditHandler {
    private static Logger logger = Logger.getLogger(WSUserEditHandler.class);

    public WSUserEditHandler() {
    }

    protected void beforeRender(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws SHRWebException {
        WSUserInfo wsUser = (WSUserInfo)modelMap.get("model");
        if (wsUser != null && wsUser.getId() != null && !StringUtils.isEmpty(wsUser.getPasswd())) {
            String operateStatus = this.getOperateStatus(request, modelMap);
            if ("EDIT".equalsIgnoreCase(operateStatus)) {
                wsUser.setPasswd((String)null);
            } else {
                String bs = this.substitution(wsUser.getPasswd());
                wsUser.setPasswd(bs);
            }
        }

        super.beforeRender(request, response, modelMap);
    }

    public String downloadAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws SHRWebException {
        String wsUserId = request.getParameter("billId");
        if (StringUtils.isEmpty(wsUserId)) {
            throw new ShrWebBizException(SHRWebResource.getString("com.kingdee.shr.base.syssetting.CommonserviceResource", "sdk_non_existent"));
        } else {
            File propFile = null;

            try {
                Context ctx = SHRContext.getInstance().getContext();
                String permItemUrl = "/dynamic.do?method=initalize#uri=com.kingdee.shr.websso.app.WSUser.form";
                PermItemInfo permItem = PermItemURLCache.getPermItemInfoByURL(ctx, permItemUrl);
                SHRFunctionPermissionService.checkCurrnetUserFunctionPermission(ctx, permItem);
                IWSUser instance = WSUserFactory.getRemoteInstance();
                WSUserInfo wsUser = (WSUserInfo)((WSUserInfo)instance.getValue(new ObjectUuidPK(BOSUuid.read(wsUserId))));
                String realPath = SHRSyssettingUtil.getShrPropertiesPath();
                StringBuffer sb = new StringBuffer();
                String zipPath = sb.append(realPath).append(File.separator).append("osf_ws_client").append(File.separator).toString();
                propFile = new File(zipPath + "userInfo.properties");
                if (!propFile.exists()) {
                    propFile.createNewFile();
                }

                boolean isCloudServ = false;
                this.writePropFile(propFile, wsUser, isCloudServ);
                String userInfoP = "com/kingdee/shr/osf/webservice/client/userInfo.properties";
                FileOperateUtil.downloadSDK(zipPath, propFile, userInfoP, response);
            } catch (IOException var21) {
                logger.error(var21.getMessage());
                throw new SHRWebException(var21.getMessage(), var21);
            } catch (EASBizException var22) {
                throw new ShrWebBizException(SHRWebResource.getString("com.kingdee.shr.base.syssetting.CommonserviceResource", "download_fails"), var22);
            } catch (UuidException | BOSException var23) {
                throw new SHRWebException(var23.getMessage(), var23);
            } finally {
                if (propFile != null) {
                    propFile.delete();
                }

            }

            return null;
        }
    }

    private void writePropFile(File propFile, WSUserInfo wsUser, boolean isCloudServ) throws ShrWebBizException {
        Properties prop = new Properties();
        prop.setProperty("easAddr", wsUser.getShrAddr());
        prop.setProperty("userName", wsUser.getUserName());
        String pwd = wsUser.getPasswd();
        prop.setProperty("password", pwd);
        prop.setProperty("dcName", wsUser.getDcName());
        prop.setProperty("slnName", wsUser.getSlnName());
        prop.setProperty("language", wsUser.getLanguage().getValue());
        prop.setProperty("dbType", (String)wsUser.get("dbtype"));
        if (isCloudServ) {
            prop.setProperty("isCloudServ", "true");
        }

        FileOutputStream fos = null;

        try {
            fos = new FileOutputStream(propFile, false);
            prop.store(fos, (String)null);
        } catch (FileNotFoundException var12) {
            throw new ShrWebBizException(SHRWebResource.getString("com.kingdee.shr.base.syssetting.CommonserviceResource", "api_user_config_non_exist"), var12);
        } catch (IOException var13) {
            throw new ShrWebBizException(SHRWebResource.getString("com.kingdee.shr.base.syssetting.CommonserviceResource", "api_user_config_add_fails"), var13);
        } finally {
            FileOperateUtil.closeStream(new Closeable[]{fos});
        }

    }

    private String substitution(String str) {
        int length = str.length();
        StringBuffer sb = new StringBuffer();

        for(int i = 0; i < length; ++i) {
            sb.append("*");
        }

        return sb.toString();
    }
}
