package com.seeyon.apps.src_flowIntegration.controller;

import cn.hutool.log.Log;
import com.alibaba.fastjson.JSONArray;
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.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;

public class URLSkipController extends BaseController {

    private static Log log = Log.get(URLSkipController.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 {
//        String thirdPartyFlowId = request.getParameter("thirdPartyFlowId");//第三方系统流程ID
        String thirdPartyCode = request.getParameter("thirdPartyCode");//第三方系统编码
        String tableName = request.getParameter("tableName");//表单名称
        String recordId = request.getParameter("recordId");//按钮对应行ID

        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 formUrl = getToFormUrlByThirdPartyFlowId(tableName,recordId);
        URL url = new URL(formUrl);
        String query = url.getQuery();
        if (query == null || query.isEmpty()) {
            log.info("没有查询到请求参数，请检查");
            ModelAndView mav = exceptionRedirect("没有查询到请求参数，请检查");
            return mav;
        }
        Map<String, String> paramMap = parseQueryParams(query);
        String tourl = paramMap.get("tourl");
//        连接地址转换，特殊标识符
        String encodedToken = URLEncoder.encode(encrypted, StandardCharsets.UTF_8.name());
        StringBuilder urlsb = new StringBuilder(tourl).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;
    }

    private String getToFormUrlByThirdPartyFlowId(String tableName,String recordId){
//        通过当前表单名称获取当前表单的所有字段信息
        String fieldInfoStr = srcFlowDao.getFieldInfoByFormName(tableName);
//        通过所有字段信息查询出第三方系统ID字段名称及第三方系统编码
        JSONObject fieldInfoJson = JSONObject.parseObject(fieldInfoStr);
        JSONObject frontFormmain = fieldInfoJson.getJSONObject("front_formmain");
//        查询相关链接明细表信息
        JSONArray formsons = fieldInfoJson.getJSONArray("formsons");
//        根据相关明细名称获取对应明细表数据库名称
        JSONObject linkformson = new JSONObject();
        for(int i = 0 ; i < formsons.size();i++){
            JSONObject json = formsons.getJSONObject(i);
            if("相关链接".equals(json.getString("display"))){
                linkformson = json;
            }
        }
//        未查询到对应明细表，返回连接为空
        if(linkformson.size()==0){
            log.info("未查询到对应相关链接明细表信息，返回连接信息为空");
            return "";
        }
        String linkSubTableName = linkformson.getString("tableName");
//        获取需要查询的字段名称
        JSONArray linkFieldInfos = linkformson.getJSONArray("fieldInfo");
        String urlStrName = "";
        for(int i = 0 ; i < linkFieldInfos.size();i++){
            JSONObject linkFieldInfo = linkFieldInfos.getJSONObject(i);
            if("跳转链接".equals(linkFieldInfo.getString("display"))){
                urlStrName = linkFieldInfo.getString("name");
            }
        }
        if(StringUtil.isEmpty(urlStrName)){
            log.info("未查询到对应相关链接明细表中存在跳转链接信息，返回连接信息为空");
            return "";
        }
//        通过表单，第三方系统ID，第三方系统编码查询出指定字段
        String[] fieldNameString = new String[]{urlStrName};
        Map<String,String> params = new HashMap<>();
        params.put("id",recordId);
        List<Map<String,Object>> formDatas = srcFlowDao.getFormDataByParam(linkSubTableName,fieldNameString,params);
        String urlStr = "";
        if(formDatas.size()>0){
            Map<String,Object> formData = formDatas.get(0);
            urlStr = formData.get(urlStrName)==null?"":formData.get(urlStrName).toString();
        }
//        返回指定字段
        return urlStr;
    }


    /**
     * 解析查询参数字符串为Map（处理参数解码）
     */
    private Map<String, String> parseQueryParams(String query) throws UnsupportedEncodingException {
        Map<String, String> paramMap = new HashMap<>();
            // 按&拆分所有参数
            String[] paramPairs = query.split("&");
            for (String pair : paramPairs) {
                // 按=拆分参数名和值（处理没有值的情况，如?toUrl）
                String[] keyValue = pair.split("=", 2); // 限制拆分次数为2，避免值中包含=
                String key = URLDecoder.decode(keyValue[0],"UTF-8");
                String value = keyValue.length > 1
                        ? URLDecoder.decode(keyValue[1], "UTF-8")
                        : "";
                paramMap.put(key, value);
        }
        return paramMap;
    }

}
