package jnpf.personnels.controller.web.shortchain;

import cn.hutool.core.util.StrUtil;
import com.tencentcloudapi.faceid.v20180301.models.IdCardVerificationResponse;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.model.personnels.dto.uchisuike.FtbGenerateShortChainDTO;
import jnpf.personnels.service.FtbPersonnelsShortchainService;
import jnpf.personnels.utils.PersonalizedTenantWhitelistUtils;
import jnpf.personnels.utils.PersonnelIdCardVerificationUtils;
import jnpf.util.NoDataSourceBind;
import jnpf.util.TenantUtil;
import jnpf.util.UserProvider;
import jnpf.util.excel.ShortChainUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * web和app人事调离身份证校验模块
 *
 * @author xxxxx
 */
@Slf4j
@RestController
@RequestMapping("/personnels-shortchain")
public class FtbPersonnelsShortchainController {

    @Resource
    private FtbPersonnelsShortchainService ftbPersonnelsShortchainService;
    @Resource
    private TenantUtil tenantUtil;
    @Resource
    private PersonalizedTenantWhitelistUtils personalizedTenantWhitelistUtils;
    @Resource
    private PersonnelIdCardVerificationUtils personnelIdCardVerificationUtils;

    /**
     * 根据长链地址生成短链地址
     *
     * @return {@link ActionResult}
     */
    @PostMapping("/generate-short-link-address")
    public ActionResult<String> generateShortChain(@Validated @RequestBody FtbGenerateShortChainDTO ftbGenerateShortChainDTO) {
        String generateShortChain = ftbPersonnelsShortchainService.generateShortChain(ftbGenerateShortChainDTO.getLongChainAddress());
        // decode解密
        ftbPersonnelsShortchainService.saveShortChain(generateShortChain, ftbGenerateShortChainDTO.getLongChainAddress(),
                ShortChainUtils.reverseLongChain(ftbGenerateShortChainDTO.getRequestUrl()));
        UserInfo userInfo = UserProvider.getUser();
        return ActionResult.success("成功", ftbGenerateShortChainDTO.getProxyUrl() + "/" + generateShortChain + "/" + userInfo.getTenantId());
    }

    /**
     * 短链地址访问，实际跳转到长链地址
     *
     * @param url 短链6位地址
     */
    @GetMapping("/redirect/{url}/{tenantId}")
    @NoDataSourceBind
    public void redirect(@PathVariable("url") String url, @PathVariable("tenantId") String tenantId, HttpServletResponse response) throws IOException {
        if (StrUtil.isBlank(tenantId)) {
            log.error("短链地址:{},缺乏租户id参数:{}", url, tenantId);
            return;
        }
        tenantUtil.switchTenant(tenantId);
        String physicalAddress = ftbPersonnelsShortchainService.redirect(url);
        if (StringUtils.hasText(physicalAddress)) {
            log.error("正常日志请忽略，短链重定向地址到:{}", physicalAddress);
            response.sendRedirect(physicalAddress);
        } else {
            log.error("无效的短链地址:{}", url);
        }
    }

    /**
     * 个性化租户白名单（返回租户标识）
     *
     * @return {@link ActionResult}
     */
    @GetMapping("/redirect/personalized-tenant-whitelist")
    @NoDataSourceBind
    public ActionResult<List<String>> internalRecommendationInvitationAdded() {
        return ActionResult.success(personalizedTenantWhitelistUtils.getTenantry());
    }

    /**
     * 身份证校验
     *
     * @param userName 姓名
     * @param tenantId 租户Id
     * @param idCard 身份证号码
     */
    @GetMapping("/redirect/id-card-verification")
    @NoDataSourceBind
    public ActionResult<IdCardVerificationResponse> idCardVerification(@RequestParam("userName") String userName, @RequestParam("tenantId") String tenantId, @RequestParam("idCard") String idCard) throws IOException {
        if (StrUtil.isBlank(tenantId)) {
            log.error("身份证校验:{},缺乏租户id参数:{}", idCard, tenantId);
            return ActionResult.fail("缺少租户id参数");
        }
        IdCardVerificationResponse idCardVerificationResponse = personnelIdCardVerificationUtils.idCardVerification(idCard, userName, tenantId);
        return ActionResult.success(idCardVerificationResponse);
    }

}
