package com.seeyon.apps.src_hxinvoice.sso;

import com.seeyon.apps.addressbook.manager.AddressBookCustomerFieldInfoManager;
import com.seeyon.apps.addressbook.po.AddressBook;
import com.seeyon.apps.common.config.ICstConfigApi;
import com.seeyon.apps.common.plugin.vo.ConfigVo;
import com.seeyon.apps.src_hxinvoice.constants.HxinvoiceConstants;
import com.seeyon.apps.src_hxinvoice.util.SXAESUtil;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.controller.BaseController;
import com.seeyon.ctp.util.Strings;
import org.springframework.web.servlet.ModelAndView;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

public class HxInvoicesso  extends BaseController {

    @Inject
    private ICstConfigApi cstConfigApi;
    @Inject
    private AddressBookCustomerFieldInfoManager addressBookCustomerFieldInfoManager;



    @Override
    public ModelAndView index(HttpServletRequest request, HttpServletResponse response) throws Exception {

        ConfigVo config = cstConfigApi.getConfig(HxinvoiceConstants.getPluginId());

        AddressBook addressBook = addressBookCustomerFieldInfoManager.getByMemberId(AppContext.currentUserId());
        if(null == addressBook) {
            super.rendJavaScript(response, "alert('航信账号未维护，无法单点登录！');");
            return null;
        }
        String code = addressBook.getExtAttr3();
        if(Strings.isBlank(code)) {
            super.rendJavaScript(response, "alert('航信账号未维护，无法单点登录！');");
            return null;
        }
//        进行参数加密
        String time = String.valueOf(System.currentTimeMillis());
        String mw = URLEncoder.encode(SXAESUtil.aesEncrypt(code+","+time));
        try {
            String url = config.getParamVal(HxinvoiceConstants.hxInvoicessoIpportUrl.name());
            String hxInvoicessoUrl = config.getParamVal(HxinvoiceConstants.hxInvoicessoUrl.name());
                String ssoUrl = url + hxInvoicessoUrl + mw;
                response.sendRedirect(ssoUrl);
//            } else {
//                super.rendJavaScript(response, "alert('单点登录错误：" + hxinvoiceResponse.getMsg() + "');");
//            }
        } catch (Exception e) {
            logger.error("单点登录异常", e);
            super.rendJavaScript(response, "alert('后台发生错误');");
        }
        return null;
    }
}
