package com.seeyon.apps.src_flowIntegration.controller;

import cn.hutool.log.Log;
import com.alibaba.fastjson.JSONObject;
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_flowIntegration.config.FlowIntegrationConfigProvider;
import com.seeyon.apps.src_flowIntegration.constants.FlowIntegrationConstants;
import com.seeyon.apps.src_flowIntegration.dao.SrcFlowDao;
import com.seeyon.apps.src_flowIntegration.util.AddressBookUtil;
import com.seeyon.apps.src_flowIntegration.util.AesUtil;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.controller.BaseController;
import com.seeyon.ctp.common.ctpenumnew.manager.EnumManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import www.seeyon.com.utils.StringUtil;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;

public class FormRedirectController extends BaseController {

    private static Log log = Log.get(FormRedirectController.class);

    @Inject
    private AddressBookCustomerFieldInfoManager addressBookCustomerFieldInfoManager;
    @Inject
    private SrcFlowDao srcFlowDao;
    @Autowired
    private FlowIntegrationConfigProvider configProvider;
    @Inject
    private EnumManager enumManagerNew;


    protected ICstConfigApi cstConfigApi = (ICstConfigApi) AppContext.getBean("cstConfigApi");

    public ModelAndView index(HttpServletRequest request,HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        System.out.println("进入表单跳转方法");
        ConfigVo config = cstConfigApi.getConfig(FlowIntegrationConstants.getPluginId());
//        表单连接跳转处理方法。
//        获取系统内置参数第三方系统主数据字段信息
        String extAttrLabel = configProvider.getBizConfigByKey(FlowIntegrationConstants.extAttrLabel);
        log.info("获取人员账号自定义字段名称"+extAttrLabel);
//        获取当前登录账号的人员自定义主数据信息，通过主数据信息查询到BIP系统登录信息
        AddressBook addressBook = addressBookCustomerFieldInfoManager.getByMemberId(AppContext.currentUserId());
        if(null == addressBook) {
            log.info("人员自定义数据未维护，无法单点登录！");
            ModelAndView mav = exceptionRedirect("人员自定义数据未维护，无法单点登录！");
            return mav;
        }
        JSONObject addressBookjson = AddressBookUtil.appleAddressBook(addressBook,enumManagerNew);
//        通过字段名称查询人员账号主数据数据库字段
        String extAttrName = srcFlowDao.getMetadataNameByLabel(extAttrLabel);
        String extAttrValue = addressBookjson.getString(extAttrName);
        log.info("查询对应人员账号"+extAttrValue);
        if(StringUtil.isEmpty(extAttrValue)){
            log.info(extAttrLabel+"未维护，无法单点登录！");
            ModelAndView mav = exceptionRedirect(extAttrLabel+"未维护，无法单点登录！");
            return mav;
        }
//        获取第三方系统标识，通过第三方系统标识查询第三方系统的ip，端口，表单跳转地址，加密规则信息等
        String thirdpartyCode = request.getParameter("thirdpartyCode");
//        设置跳转参数
        JSONObject autoToken = new JSONObject();
        autoToken.put("thirdPartyLoginName",extAttrValue);
        autoToken.put("loginName",AppContext.currentUserLoginName());
        autoToken.put("time",new Date().getTime());
        log.info("第三方应用编码："+thirdpartyCode+"，设置连接跳转参数"+autoToken);
//        根据第三方系统标识获取加密key和vi
        String paramValue = srcFlowDao.getThirdpartyParamByThirdpartyCode(thirdpartyCode);
        log.info("参数信息"+paramValue);
        if(StringUtil.isEmpty(paramValue)){
            log.info("当前第三方系统标识在系统中没有找到，请检查系统设置。");
            ModelAndView mav = exceptionRedirect("当前第三方系统标识在系统中没有找到，请检查系统设置。");
            return mav;
        }
        JSONObject paramjson = JSONObject.parseObject(paramValue);
        String secretKey = paramjson.getString("secretKey");
        String vi = paramjson.getString("vi");
        String encrypted = AesUtil.encrypt(autoToken.toString(),secretKey,vi);
        String tourl = request.getParameter("tourl");

//        JSONObject thirdpartyParamjson = JSONObject.parseObject(paramValue);
//        连接地址转换，特殊标识符
        String url = tourl;
        String encodedToken = URLEncoder.encode(encrypted, StandardCharsets.UTF_8.name());
        StringBuilder urlsb = new StringBuilder(url).append("&auth_token=").append(encodedToken);
        log.info("跳转链接为："+urlsb);
        response.sendRedirect(urlsb.toString());
        return null;
    }

    private ModelAndView exceptionRedirect(String popupContent){
        ModelAndView mav = new ModelAndView("popup");
        // 2. 向前端传递弹窗参数（可自定义字段）
        mav.addObject("showPopup", true); // 是否显示弹窗
        mav.addObject("popupTitle", "操作提示"); // 弹窗标题
        mav.addObject("popupContent", popupContent); // 弹窗内容
        mav.addObject("popupType", "success"); // 弹窗类型（成功/失败）
        return mav;
    }
}
