package com.qmth.teachcloud.exchange.common.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.qmth.boot.tools.signature.SignatureEntity;
import com.qmth.boot.tools.signature.SignatureType;
import com.qmth.teachcloud.exchange.common.bean.dto.syssetting.SimpleObject;
import com.qmth.teachcloud.exchange.common.bean.params.OpenParams;
import com.qmth.teachcloud.exchange.common.contant.SystemConstant;
import com.qmth.teachcloud.exchange.common.entity.BasicSchool;
import com.qmth.teachcloud.exchange.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.exchange.common.service.CommonCacheService;
import com.qmth.teachcloud.exchange.common.service.CommonService;
import com.qmth.teachcloud.exchange.common.util.Base64Util;
import com.qmth.teachcloud.exchange.common.util.JacksonUtil;
import com.qmth.teachcloud.exchange.common.util.ServletUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.StringJoiner;

/**
 * @Description: 公用serviceImpl 实现类
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2021/3/25
 */
@Service
public class CommonServiceImpl implements CommonService {
    private final static Logger log = LoggerFactory.getLogger(CommonServiceImpl.class);

    @Resource
    CommonCacheService commonCacheService;

    /**
     * 跳转方法
     *
     * @param account
     * @param schoolCode
     * @param returnUrl
     * @param params
     * @throws IOException
     */
    @Override
    public void redirectLogic(String functionalType, String account, String schoolCode, String returnUrl, String params) throws IOException {
        log.info("公用跳转接口进来了,account:{},schoolCode:{},returnUrl:{},params:{}", account, schoolCode, returnUrl, params);
        BasicSchool basicSchool = commonCacheService.schoolCache(schoolCode);
        Optional.ofNullable(basicSchool).orElseThrow(() -> ExceptionResultEnum.PARAMS_ERROR.exception("学校信息不存在"));
        Map<String, SimpleObject> mapSetting = commonCacheService.getSysSetting(basicSchool.getId());
        String teachcloudLoginUrl = null;
        if (!CollectionUtils.isEmpty(mapSetting)) {
            log.info("mapSetting1 value:{}", JSONObject.toJSONString(mapSetting));
            SimpleObject simpleObject = mapSetting.get(SystemConstant.TEACH_CLOUD_PRINT);
            Objects.requireNonNull(simpleObject, "未配置知学知考地址");
            log.info("simpleObject1 value:{}", JSONObject.toJSONString(simpleObject));
            String teachCloudPrint = simpleObject.getValue();
            if (Objects.nonNull(teachCloudPrint) && !Objects.equals(teachCloudPrint.trim(), "")) {
                teachcloudLoginUrl = teachCloudPrint.replace("/login", SystemConstant.CAS_VUE_LOGIN_PATH);
            }
        }
        if (Objects.isNull(teachcloudLoginUrl) || Objects.equals(teachcloudLoginUrl, "")) {
            throw ExceptionResultEnum.PARAMS_ERROR.exception("知学登录跳转地址不存在");
        }
        if (Objects.isNull(account) || Objects.equals(account, "")) {
            throw ExceptionResultEnum.PARAMS_ERROR.exception("工号不存在");
        }
        if (Objects.isNull(schoolCode) || Objects.equals(schoolCode, "")) {
            throw ExceptionResultEnum.PARAMS_ERROR.exception("学校code不存在");
        }

        HttpServletResponse response = ServletUtil.getResponse();
        response.setHeader(SystemConstant.ACCESS_CONTROL_ALLOW_ORIGIN, SystemConstant.PATH_MATCH);

        if (Objects.nonNull(params)) {
            long timestamp = System.currentTimeMillis();
//        String path = teachcloudLoginUrl.substring(teachcloudLoginUrl.indexOf(SystemConstant.PATH_SUBSTR), teachcloudLoginUrl.length());
            String signature = SignatureEntity.build(SignatureType.SECRET, SystemConstant.GET, SystemConstant.CAS_VUE_LOGIN_PATH, timestamp, basicSchool.getAccessKey(), basicSchool.getAccessSecret());

            StringJoiner stringJoiner = new StringJoiner("")
                    .add(teachcloudLoginUrl)
                    .add(SystemConstant.GET_UNKNOWN).add(SystemConstant.HEADER_TIME).add(SystemConstant.GET_EQUAL).add(String.valueOf(timestamp))
                    .add(SystemConstant.GET_SYMBOL).add(SystemConstant.SIGNATURE).add(SystemConstant.GET_EQUAL).add(Base64Util.encode(signature.getBytes(StandardCharsets.UTF_8)))
                    .add(SystemConstant.GET_SYMBOL).add(SystemConstant.USER).add(SystemConstant.GET_EQUAL).add(URLEncoder.encode(account, SystemConstant.CHARSET_NAME))
                    .add(SystemConstant.GET_SYMBOL).add(SystemConstant.FUNCTIONAL_TYPE).add(SystemConstant.GET_EQUAL).add(URLEncoder.encode(functionalType, SystemConstant.CHARSET_NAME));

            if (Objects.nonNull(returnUrl) && !Objects.equals(returnUrl, "")) {
                stringJoiner = stringJoiner.add(SystemConstant.GET_SYMBOL).add(SystemConstant.RETURN_URL).add(SystemConstant.GET_EQUAL).add(URLEncoder.encode(returnUrl, SystemConstant.CHARSET_NAME));
            }
            if (Objects.nonNull(params) && !Objects.equals(params, "")) {
                String decodeJson = URLDecoder.decode(params, SystemConstant.CHARSET_NAME);
                OpenParams openParams = JacksonUtil.readJson(decodeJson, OpenParams.class);
                stringJoiner = stringJoiner.add(SystemConstant.GET_SYMBOL).add(SystemConstant.PARAMS).add(SystemConstant.GET_EQUAL).add(URLEncoder.encode(JacksonUtil.parseJson(openParams), SystemConstant.CHARSET_NAME));
            }
//        String redirectUrl = URLEncoder.encode(stringJoiner.toString(), SystemConstant.CHARSET);
//        log.info("path:{},timestamp:{},account:{},signature:{},redirectUrl:{},redirectUrl_urlencode:{}", path, timestamp, account, signature, stringJoiner.toString(), redirectUrl);
            log.info("path:{},timestamp:{},account:{},functionalType:{},signature:{}, redirectUrl:{}", SystemConstant.CAS_VUE_LOGIN_PATH, timestamp, account, functionalType, signature, stringJoiner.toString());
            response.sendRedirect(stringJoiner.toString());
        } else {
            response.sendRedirect(returnUrl);
        }
    }
}
