package com.bonus.canteen.core.auth.oauth.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bonus.canteen.core.auth.oauth.util.OAuthUtil;
import com.bonus.canteen.core.auth.user.dto.MgrUserLoginDTO;
//import com.bonus.canteen.core.auth.user.service.MgrUserService;
import com.bonus.canteen.core.config.SmUtils;
import com.bonus.canteen.core.customer.model.PigxUser;
import com.bonus.canteen.core.device.mq.MacMessageService;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.houqin.framework.secure.SecureProperties;
import com.google.common.base.Joiner;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.bonus.canteen.core.auth.oauth.vo.DeviceLoginResponseVo;
import com.bonus.canteen.core.common.utils.HeaderFetchUtil;
import com.bonus.common.houqin.framework.secure.AccessToken;
import com.bonus.common.houqin.framework.secure.WebContext;
import com.bonus.canteen.core.device.manage.controller.deprecated.vo.MessageConfigVO;
import com.bonus.canteen.core.device.manage.model.DeviceInfoInSystem;
import com.bonus.canteen.core.device.manage.service.DeviceInfoService;
import com.bonus.canteen.core.merchant.api.MercMerchantApi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;
import java.lang.invoke.SerializedLambda;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

@RestController
@RequestMapping({"/oauth"})
@Api(
   value = "auth",
   tags = {"登陆模块"}
)
public class AuthController {
   private static final Logger log = LoggerFactory.getLogger(AuthController.class);
   private static final String HEADER_SECURITY_TENANT_ID = "X-Security-Tenant-Id";
   private static final String HEADER_SECURITY_TOKEN = "X-Security-Token";
   private static final String HEADER_SECURITY_SN = "X-Security-Sn";
//   @Autowired
//   private MgrUserService mgrUserService;
   @Autowired
   @Lazy
   private MercMerchantApi mercMerchantApi;
   @Autowired
   @Lazy
   private DeviceInfoService deviceInfoService;
   @Autowired
   @Lazy
   private MacMessageService macMessageService;
   @Autowired
   @Lazy
   private SecureProperties secureProperties;
//   @Autowired
//   @Lazy
//   BackDeviceApi backDeviceApi;
//   @Autowired
//   private OpenAppService openAppService;

//   @RequireVerifyCode
//   @PostMapping({"/web/token"})
//   @RequiresGuest
//   @ApiOperation("web登陆")
//   public LeResponse<JSONObject> webLogin(@RequestParam String content) {
//      MgrUserLoginDTO loginDTO = (MgrUserLoginDTO)JSON.parseObject(content, MgrUserLoginDTO.class);
//
//      JSONObject object;
//      try {
//         PigxUser user = this.mgrUserService.login(loginDTO);
//         object = JSON.parseObject(JSON.toJSONString(user));
//         if (ObjectUtil.isNotNull(user.getMerchantId())) {
//            TenantContextHolder.setTenantId(user.getMerchantId());
//            MercMerchant mercMerchant = this.mercMerchantApi.getMerchant();
//            object.put("merchantName", mercMerchant.getMerchantName());
//         }
//
//         if (WebContext.get().getAccessToken().isPresent()) {
//            object.put("securityTokenSign", OAuthUtil.responseSetSecurityTokenSign(user.getMerchantId(), ((AccessToken)WebContext.get().getAccessToken().get()).getId()));
//         }
//      } catch (LeCheckedException var6) {
//         return LeResponse.fail(var6.getMessage());
//      }
//
//      return LeResponse.succ(object);
//   }

   @PostMapping({"/token"})
   @ApiOperation("设备登陆接口登陆")
   public AjaxResult login(@RequestParam String content) {
      MgrUserLoginDTO loginDTO = (MgrUserLoginDTO)JSON.parseObject(content, MgrUserLoginDTO.class);

      JSONObject object;
      try {
         PigxUser user = new PigxUser(); //this.mgrUserService.login(loginDTO);
         object = JSON.parseObject(JSON.toJSONString(user));
         object.put("user_id", user.getId());
         object.put("merchant_id", user.getMerchantId());
         if (WebContext.get().getAccessToken().isPresent()) {
            object.put("securityTokenSign", OAuthUtil.responseSetSecurityTokenSign(user.getMerchantId(),
                    ((AccessToken)WebContext.get().getAccessToken().get()).getId()));
         }
      } catch (Exception e) {
         return AjaxResult.error(e.getMessage());
      }

      return AjaxResult.success(object);
   }

//   @DeleteMapping({"/logOut"})
//   @RequiresAuthentication
//   @ApiOperation("退出登陆")
//   @AnLogRecord(
//      value = "退出登录",
//      type = LogRecordOperTypeEnum.SIGN_OUT
//   )
//   public LeResponse<String> logOut() {
//      SecureManager.logout();
//      return LeResponse.succ("操作成功");
//   }
//
//   @PostMapping({"/public/login"})
//   @RequiresGuest
//   @ApiOperation("采购库存公众号登陆接口")
//   public LeResponse<PigxUser> publicLogin(@RequestBody LeRequest<MgrUserLoginDTO> request) {
//      MgrUserLoginDTO loginDTO = (MgrUserLoginDTO)request.getContent();
//      loginDTO.setUsername(new String(loginDTO.getUsername().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
//
//      PigxUser user;
//      try {
//         user = this.mgrUserService.login(loginDTO);
//         if (CharSequenceUtil.isBlank(loginDTO.getOpenid())) {
//            return LeResponse.succ(user);
//         }
//
//         MgrUser mgrUser = (MgrUser)this.mgrUserService.getOne((Wrapper)Wrappers.lambdaQuery().eq(MgrUser::getUserId, user.getId()));
//         String wxOpenids = mgrUser.getWxOpenid();
//         List<String> openidList = CharSequenceUtil.isNotBlank(wxOpenids) ? CharSequenceUtil.split(wxOpenids, ",") : CollUtil.newArrayList(new String[0]);
//         ((List)openidList).add(loginDTO.getOpenid());
//         mgrUser.setWxOpenid(CollUtil.join((Iterable)openidList, ","));
//         this.mgrUserService.updateById(mgrUser);
//      } catch (LeCheckedException var7) {
//         return LeResponse.fail(var7.getMessage());
//      }
//
//      return LeResponse.succ(user);
//   }
//
//   @ApiOperation("web-单点登陆")
//   @PostMapping({"/web/single-sign-on"})
//   @RequiresGuest
//   public PigxUser webSingleSignOn(@RequestParam("tenantId") Long tenantId, @RequestBody LeRequest<MgrUserSsoDTO> request) {
//      return this.mgrUserService.webSingleSignOn(tenantId, (MgrUserSsoDTO)request.getContent());
//   }

   @ApiOperation("设备认证")
   @PostMapping({"/device/login"})
   public AjaxResult deviceLogin(@RequestHeader Map<String, String> header, @RequestBody String request) {
      String deviceSn = SmUtils.decryptBySm2(request);
      String encryptKey = HeaderFetchUtil.getValueFromHeadersIgnoreCase(header, this.secureProperties.getSecurity().getServerEncryptedClientKeyHeaderName());
      String clientKey = SmUtils.decryptBySm4WithServerKey(encryptKey);
      if (CharSequenceUtil.isEmpty(deviceSn)) {
         return AjaxResult.success();
      } else {
         DeviceInfoInSystem deviceInfo = this.deviceInfoService.getBySnInSys(deviceSn);
         if (ObjectUtil.isNull(deviceInfo)) {
            return AjaxResult.success();
         } else {
            MessageConfigVO messageConfigVO = this.macMessageService.getMessageConfig();
            DeviceLoginResponseVo responseVo = new DeviceLoginResponseVo();
            responseVo.setTenantId(deviceInfo.getTenantId());
            responseVo.setMqClientAddress(messageConfigVO.getMqClientAddress());
            String deviceToken = this.generatorToken(deviceSn, clientKey, deviceInfo.getTenantId());
            String securityTokenSign = this.getSecurityTokenSign(deviceSn, clientKey, deviceInfo.getTenantId(), deviceToken);
            responseVo.setDeviceToken(deviceToken);
            responseVo.setSecurityTokenSign(securityTokenSign);
            return AjaxResult.success(responseVo);
         }
      }
   }

//   @ApiOperation("后场设备认证")
//   @PostMapping({"/back/device/login"})
//   @RequiresGuest
//   public LeResponse<DeviceLoginResponseVo> backDeviceLogin(@RequestHeader Map<String, String> header, @RequestBody LeRequest<String> request) {
//      String deviceSn = SmUtils.decryptBySm2((String)request.getContent());
//      String encryptKey = HeaderFetchUtil.getValueFromHeadersIgnoreCase(header, this.secureProperties.getSecurity().getServerEncryptedClientKeyHeaderName());
//      String clientKey = SmUtils.decryptBySm4WithServerKey(encryptKey);
//      if (CharSequenceUtil.isEmpty(deviceSn)) {
//         return LeResponse.succ();
//      } else {
//         BackDevicesInSystem backDevicesInSystem = this.backDeviceApi.getBySnInSyS(deviceSn);
//         if (ObjectUtil.isNull(backDevicesInSystem)) {
//            return LeResponse.succ();
//         } else {
//            MessageConfigVO messageConfigVO = this.macMessageService.getMessageConfig();
//            DeviceLoginResponseVo responseVo = new DeviceLoginResponseVo();
//            responseVo.setTenantId(backDevicesInSystem.getTenantId());
//            responseVo.setMqClientAddress(messageConfigVO.getMqClientAddress());
//            String deviceToken = this.generatorToken(deviceSn, clientKey, backDevicesInSystem.getTenantId());
//            String securityTokenSign = this.getSecurityTokenSign(deviceSn, clientKey, backDevicesInSystem.getTenantId(), deviceToken);
//            responseVo.setDeviceToken(deviceToken);
//            responseVo.setSecurityTokenSign(securityTokenSign);
//            return LeResponse.succ(responseVo);
//         }
//      }
//   }

   private String getSecurityTokenSign(String deviceSn, String clientKey, Long tenantId, String deviceToken) {
      TreeMap<String, String> needSignMap = new TreeMap();
      needSignMap.put("X-Security-Tenant-Id", String.valueOf(tenantId));
      needSignMap.put("X-Security-Sn", deviceSn);
      needSignMap.put("X-Security-Token", deviceToken);
      return SmUtils.signAuthTokenBySm3(needSignMap, clientKey);
   }

   private String generatorToken(String deviceSn, String clientKey, Long tenantId) {
      TreeMap<String, String> paramMap = new TreeMap();
      paramMap.put("X-Security-Sn", deviceSn);
      paramMap.put("X-Security-Tenant-Id", String.valueOf(tenantId));
      log.info("设备登录待签名:{}", Joiner.on("&").useForNull("").withKeyValueSeparator("=").join(paramMap));
      return SmUtils.signAuthTokenBySm3(paramMap, clientKey);
   }

//   @ApiOperation("openapi认证")
//   @PostMapping({"/openapi/login"})
//   @RequiresGuest
//   @ResponseWrapperByPass
//   public OpenApiLoginVo openApiLogin(@RequestHeader Map<String, String> header, @RequestBody Map<String, String> content) {
//      String appIdEncrypt = (String)content.get("content");
//      if (ObjectUtil.isNull(appIdEncrypt)) {
//         throw new LeException(CheckEnum.VALID_APPID_MISS.getCode(), CheckEnum.VALID_APPID_MISS.getErrorMsg());
//      } else {
//         String appIdStr = SmUtils.decryptBySm2(appIdEncrypt);
//         if (!NumberUtil.isLong(appIdStr)) {
//            throw new LeException(CheckEnum.VALID_APPID_FORMAT_ERROR.getCode(), CheckEnum.VALID_APPID_FORMAT_ERROR.getErrorMsg());
//         } else {
//            Long appid = Long.parseLong(appIdStr);
//            OpenApp app = this.openAppService.getAppInfoByAppId(appid);
//            if (ObjectUtil.isNull(app)) {
//               throw new LeException(CheckEnum.VALID_APPID_ERROR.getCode(), CheckEnum.VALID_APPID_ERROR.getErrorMsg());
//            } else if (ObjectUtil.equals(app.getDisable(), LeConstants.COMMON_YES)) {
//               throw new LeException(CheckEnum.VALID_APPID_DISABLE.getCode(), CheckEnum.VALID_APPID_DISABLE.getErrorMsg());
//            } else {
//               LocalDateTime startTime = app.getStartTime();
//               LocalDateTime endTime = app.getEndTime();
//               LocalDateTime now = LocalDateTime.now();
//               if (ObjectUtil.isNotNull(startTime) && now.isBefore(startTime)) {
//                  throw new LeException(CheckEnum.VALID_APPID_BEFORE.getCode(), CheckEnum.VALID_APPID_BEFORE.getErrorMsg());
//               } else if (ObjectUtil.isNotNull(endTime) && now.isAfter(endTime)) {
//                  throw new LeException(CheckEnum.VALID_APPID_EXPIRED.getCode(), CheckEnum.VALID_APPID_EXPIRED.getErrorMsg());
//               } else {
//                  String encryptKey = HeaderFetchUtil.getValueFromHeadersIgnoreCase(header, this.secureProperties.getSecurity().getServerEncryptedClientKeyHeaderName());
//                  String clientKey = SmUtils.decryptBySm4WithServerKey(encryptKey);
//                  String token = this.generatorToken(String.valueOf(appid), clientKey, app.getTenantId());
//                  OpenApiLoginVo loginVo = new OpenApiLoginVo();
//                  loginVo.setToken(token).setTenantId(app.getTenantId()).setSecurityTokenSign(OAuthUtil.responseSetSecurityTokenSign(app.getTenantId(), token)).setAppName(app.getAppName());
//                  return loginVo;
//               }
//            }
//         }
//      }
//   }

}
