package cn.pluss.platform.interceptor;

import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultCode;
import cn.pluss.platform.constants.CommonError;
import cn.pluss.platform.entity.MerchantStaffConn;
import cn.pluss.platform.entity.UserApp;
import cn.pluss.platform.entity.UserInfo;
import cn.pluss.platform.merchant.MerchantStaffConnService;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.userInfo.UserInfoService;
import cn.pluss.platform.util.ComUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author djh
 */
public class TokenRegistryInterceptor extends HandlerInterceptorAdapter {

    @Resource
    private UserAppService userAppService;

    @Resource
    private UserInfoService uiService;

    @Resource
    private MerchantStaffConnService staffConnService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestUri = request.getRequestURI();
        List<String> limitUri = new ArrayList<>();
        limitUri.add("/api/agreement/getAgreementOne");
        limitUri.add("/api/phoneValidateCode");
        limitUri.add("/api/img");
        limitUri.add("/api/test/");
        limitUri.add("/api/push/pushMsg");
        limitUri.add("/api/machineCallback/orderCallback");
        limitUri.add("/api/makeMoney/sxfCallback");
        limitUri.add("/api/img");
        limitUri.add("/api/test/");
        limitUri.add("/api/wx/img");
        limitUri.add("/api/userInfo");
        limitUri.add("/api/error");
        limitUri.add("/api/wxCert/wxCertGuide");
        limitUri.add("/api/callback/");
        limitUri.add("/api/open/login");
        limitUri.add("/api/index.html");
        limitUri.add("/api/merchantOrder/posScanPay");
        boolean passFlag = limitUri.stream().anyMatch(s -> s.equals(requestUri) || requestUri.startsWith(s));
        if (passFlag) {
            return true;
        }

        String contentType = request.getContentType();


        synchronized (this) {
            String requestToken = request.getHeader("token");
            // 登录账号
            String myLoginName = request.getHeader("myLoginName");
            if (StringUtils.isEmpty(myLoginName)) {
                myLoginName = request.getHeader("myloginname");
            }

            if (StringUtils.isEmpty(myLoginName)) {
                myLoginName = request.getHeader("MYLOGINNAME");
            }

            if (StringUtils.isEmpty(myLoginName) || StringUtils.isEmpty(requestToken)) {
                Result<Object> result = new Result<>();
                result.setCode(ResultCode.NOT_TOKEN).setMessage("非法请求");
                ComUtil.responseResult(response, result);
                return false;
            }

            myLoginName = URLDecoder.decode(myLoginName, "UTF-8");

            // 商户编号
            String merchantCode = request.getHeader("merchantCode");

            UserInfo userInfo = new UserInfo();
            userInfo.setLoginName(myLoginName);
            userInfo = uiService.queryUserInfo(userInfo);
            if (userInfo == null) {
                Result<Object> result = new Result<>();
                result.setCode(ResultCode.NOT_TOKEN).setMessage(CommonError.NO_EXIST_ACCOUNT);
                ComUtil.responseResult(response, result);
                return false;
            }

//            if (Objects.equals(userInfo.getStatus(), 0)) {
//                Result<Object> result = new Result<>();
//                result.setCode(ResultCode.UNAUTHORIZED).setMessage("账号涉嫌违规");
//                ComUtil.responseResult(response, result);
//                return false;
//            }




            UserApp userApp = new UserApp();
            userApp.setUserId(userInfo.getId());
            userApp = userAppService.queryUserApp(userApp);
            //TODO 去掉设备登录注释
           /* if (!requestToken.equals(userApp.getToken())) {
                Result<Object> result = new Result<>();
                result.setCode(ResultCode.NOT_TOKEN).setMessage("您在其他设备中登录");
                ComUtil.responseResult(response, result);
                return false;
            }*/

            if (StringUtils.isNotBlank(merchantCode) && "staff".equals(userApp.getUserType())) {
                MerchantStaffConn staffConn = new MerchantStaffConn().setMerchantCode(merchantCode);
                staffConn.setUserId(userApp.getUserId());
                staffConn = staffConnService.getOne(new QueryWrapper<>(staffConn));

                if (staffConn == null) {
                    Result<Object> result = new Result<>();
                    result.setCode(ResultCode.FAIL).setMessage("商户信息异常");
                    ComUtil.responseResult(response, result);
                    return false;
                }
            }

        }
        return true;

        // 验证Pass注解
//		boolean pass = verificationPassAnnotation(request, response, handler,requestToken);
//		if(pass){
//			return true;
//		}
//		boolean token = false;
//		synchronized(this) {
//			token = validateSign(request,requestToken,requestSource);
//		}
//		if(token){
//			return true;
//		}else{
//			logger.warn("签名认证失败，请求接口：{}，请求IP：{}，请求参数：{}",request.getRequestURI(), ComUtil.getIpAddress(request), JSON.toJSONString(request.getParameterMap()));
//            Result result = new Result();
//            result.setCode(ResultCode.NOT_TOKEN).setMessage("TOKEN丢失，请检查");
//            ComUtil.responseResult(response, result);
//            return false;
//		}
    }
}
