package com.mmc.iuav.user.service.fdd.impl;

import com.alibaba.fastjson2.JSONObject;
import com.fadada.sdk.base.client.FddBaseClient;
import com.fadada.sdk.base.model.req.RegisterAccountParams;
import com.fadada.sdk.verify.client.FddVerifyClient;
import com.fadada.sdk.verify.model.req.ApplyCertParams;
import com.mmc.iuav.user.constant.fdd.FddConnectConstant;
import com.mmc.iuav.user.constant.fdd.FddConstant;
import com.mmc.iuav.user.dao.UserServiceDao;
import com.mmc.iuav.user.service.fdd.FddService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * author:zhenjie
 * Date:2022/7/16
 * time:15:30
 */
@Service
@Slf4j
public class FddServiceImpl implements FddService {

    @Resource
    UserServiceDao userServiceDao;

    @Override
    public String register(String uid, String accountType) {
        FddBaseClient baseClient = new FddBaseClient(FddConnectConstant.APP_ID, FddConnectConstant.APP_KEY, FddConnectConstant.VERSION, FddConnectConstant.HOST);
        RegisterAccountParams params = new RegisterAccountParams();
        //账号类型1个人 2企业
        params.setAccountType(accountType);
        //替换uid中包含的-或者_
        String openId = uid.replaceAll("[-|_]", "");
        //平台方自定义唯一标识
        params.setOpenId(openId);
        String result = baseClient.invokeRegisterAccount(params);
        log.info(result);
        if (!JSONObject.parseObject(result).getString(FddConstant.CODE).equals(FddConstant.SUCCESS)) {
            return null;
        }
        return JSONObject.parseObject(result).getString(FddConstant.DATA);
    }

//    @Override
//    public ResultBody findPersonCertInfo(String verifiedSerialNo) {
//        FddVerifyClient client = new FddVerifyClient(FddConnectConstant.APP_ID, FddConnectConstant.APP_KEY, FddConnectConstant.VERSION, FddConnectConstant.HOST);
//        FindPersonCertParams params = new FindPersonCertParams();
//        params.setVerifiedSerialNo(verifiedSerialNo); //此处填获取个人实名认证地址返回的交易号
//        String result = client.invokeFindPersonCert(params);
//        return ResultBody.success(result);
//    }
//
//    @Override
//    public ResultBody getCompanyVerifyUrl(Integer userAccountId) {
//        String customerId = this.checkRegisterFdd(userAccountId);
//        if(customerId == null){
//            return ResultBody.error(ResultEnum.REQUEST_PARAM_ILLEGAL_ERROR);
//        }
//        //查询原来有没有请求
//        FddEVerifyInfoDO fddEVerifyInfo = fddVerifyDao.getFddEVerifyInfo(userAccountId);
//        if(fddEVerifyInfo == null){
//            CompanyVerifyResp companyVerifyResp = this.reqCompanyVerifyUrl(customerId);
//            if(companyVerifyResp == null){
//                return ResultBody.error(ResultEnum.REQUEST_PARAM_ILLEGAL_ERROR);
//            }
//            //保存实名认证链接和交易号
//            FddEVerifyInfoDO fddEVerifyInfoDO = new FddEVerifyInfoDO();
//            fddEVerifyInfoDO.setUserAccountId(userAccountId);
//            fddEVerifyInfoDO.setCustomerId(customerId);
//            fddEVerifyInfoDO.setTransactionNo(companyVerifyResp.getTransactionNo());
//            fddEVerifyInfoDO.setUrl(companyVerifyResp.getUrl());
//            fddVerifyDao.addFddEVerifyInfo(fddEVerifyInfoDO);
//            return ResultBody.success(companyVerifyResp.getUrl());
//        }
//        return ResultBody.success(fddEVerifyInfo.getUrl());
//    }
//
//    private CompanyVerifyResp reqCompanyVerifyUrl(String customerId){
//        FddVerifyClient client = new FddVerifyClient(FddConnectConstant.APP_ID, FddConnectConstant.APP_KEY, FddConnectConstant.VERSION, FddConnectConstant.HOST);
//        CompanyVerifyUrlParams params = new CompanyVerifyUrlParams();
//        params.setCustomerId(customerId);
//        params.setPageModify("1");//1允许 2不允许 默认为1
//        //设置回调通知
//        params.setReturnUrl(FddConnectConstant.MMC_URL + FddConstant.RETURN_E_CERT_RES);
//        params.setNotifyUrl(FddConnectConstant.MMC_URL + FddConstant.NOTIFY_E_CERT_RES);
//        String result = client.invokeCompanyVerifyUrl(params);
//        if(!JSONObject.parseObject(result).getString(FddConstant.CODE).equals(FddConstant.SUCCESS)){
//            return null;
//        }
//        CompanyVerifyResp data = JSON.parseObject(JSONObject.parseObject(result).getString(FddConstant.DATA), CompanyVerifyResp.class);
//        return data;
//    }

    @Override
    public String getApplyCert(String customerId, String transactionNo) {
        FddVerifyClient client = new FddVerifyClient(FddConnectConstant.APP_ID, FddConnectConstant.APP_KEY, FddConnectConstant.VERSION, FddConnectConstant.HOST);
        ApplyCertParams params = new ApplyCertParams();
        //客户编号
        params.setCustomerId(customerId);
        // 填写获取实名认证地址返回的交易号transactionNo
        params.setVerifiedSerialNo(transactionNo);
        String result = client.invokeApplyCert(params);
        if (!JSONObject.parseObject(result).getString(FddConstant.CODE).equals(FddConstant.SUCCESS)) {
            return null;
        }
        return result;
    }

//    @Override
//    public ResultBody findCompanyCertInfo(Integer userAccountId) {
//        UserFddDO userFddDO = fddVerifyDao.getUserFddByUserAccountId(userAccountId);
//        if(userFddDO == null){
//            return ResultBody.error(ResultEnum.NOT_FOUND);
//        }
//        FddEVerifyInfoDO fddEVerifyInfo = fddVerifyDao.getFddEVerifyInfo(userAccountId);
//        if( fddEVerifyInfo == null ){
//            return ResultBody.error(ResultEnum.NOT_FOUND);
//        }
//
//        FddVerifyClient client = new FddVerifyClient(FddConnectConstant.APP_ID, FddConnectConstant.APP_KEY, FddConnectConstant.VERSION, FddConnectConstant.HOST);
//        FindCompanyCertParams params = new FindCompanyCertParams();
//        params.setVerifiedSerialNo(fddEVerifyInfo.getTransactionNo());//此处填获取企业实名认证地址返回的交易号
//        String result = client.invokeFindCompanyCert(params);
//        if(!JSONObject.parseObject(result).getString(FddConstant.CODE).equals(FddConstant.SUCCESS)){
//            return ResultBody.error(ResultEnum.NOT_FOUND);
//        }
//        return ResultBody.success(JSONObject.parseObject(result).getString(FddConstant.DATA));
//    }
//
//    @Override
//    public ResultBody notifyECertRes(String appId, String serialNo, String customerId, String status, String statusDesc, String certStatus, String authenticationType, String timestamp, String sign) {
//        if (!appId.equals(FddConnectConstant.APP_ID)){
//            return ResultBody.error(ResultEnum.NOT_FOUND);
//        }
//        //修改状态认证
//        return userServletClient.notifyECertRes(appId, serialNo, customerId, status, statusDesc, certStatus, authenticationType, timestamp, sign);
//    }
//
//    @Override
//    public ResultBody returnECertRes(String personName, String transactionNo, String authenticationType, String status, String sign) {
//        //修改状态认证
//        return userServletClient.returnECertRes(personName, transactionNo, authenticationType, status, sign);
//    }
//
//    @Override
//    public ResultBody newNotifyECertRes(Map<String, String> map) {
//
//        String appId = map.get("appId");
////            String name="%E9%83%AD%E5%AE%B6%E8%BE%89";
//        String serialNo = map.get("serialNo");
//        String customerId = map.get("customerId");
//        String status = map.get("status");
//        String statusDesc = map.get("statusDesc");
//        String certStatus = map.get("certStatus");
//        String authenticationType = map.get("authenticationType");
//        String timestamp = map.get("timestamp");
//        String sign = map.get("sign");
//        String sha1 = FddEncryptTool.sha1(FddConnectConstant.APP_KEY +authenticationType +certStatus+customerId+ serialNo+status+ statusDesc);
//        try {
//            String md5 = FddEncryptTool.md5Digest(timestamp);
//            String outSha1 = FddEncryptTool.sha1(FddConnectConstant.APP_ID+md5 + sha1);
//            String base64 = new String(FddEncryptTool.Base64Encode(outSha1.getBytes())).trim();
//            if(!base64.equals(sign)){
//                return ResultBody.error(ResultEnum.NOT_FOUND);
//            }
//            if (!appId.equals(FddConnectConstant.APP_ID)){
//                return ResultBody.error(ResultEnum.NOT_FOUND);
//            }
//        }catch (Exception e){
//            return ResultBody.error(ResultEnum.NOT_FOUND);
//        }
//        FddEVerifyInfoDO fddEVerifyInfo = fddVerifyDao.getFddEVerifyInfoByTransactionNo(serialNo);
//        if(fddEVerifyInfo == null){
//            return ResultBody.error(ResultEnum.NOT_FOUND);
//        }
//        //修改认证状态
//        fddVerifyDao.updateCompanyCertStatus(customerId, status);
//        //通过需要申请证书
//        if(status.equals("4")){
//            this.getApplyCert(fddEVerifyInfo.getCustomerId(), fddEVerifyInfo.getTransactionNo());
//        }
//        return ResultBody.success();
//    }
//
//    @Override
//    public ResultBody getUserFddInfo(Integer id) {
//        UserFddDO userFddDO = fddVerifyDao.getUserFddByUserAccountId(id);
//        if(userFddDO == null){
//            return ResultBody.error(ResultEnum.NO_REAL_NAME);
//        }
//        return ResultBody.success(userFddDO.buildUserFddDTO());
//    }
//
//    @Override
//    public List<UserFddDTO> feignBatchUserFddPage(List<Integer> list) {
//        if( list.size() == 0 ){
//            return null;
//        }
//        List<UserFddDO> userFddDOList = fddVerifyDao.listUserFddPage(list);
//        List<UserFddDTO> collect = userFddDOList.stream().map(d -> {
//            return d.buildUserFddDTO();
//        }).collect(Collectors.toList());
//        return collect;
//    }
//
//    @Override
//    public ResultBody getFileByUuid(String uuid, String docType) {
//        FddVerifyClient client = new FddVerifyClient(FddConnectConstant.APP_ID, FddConnectConstant.APP_KEY, FddConnectConstant.VERSION, FddConnectConstant.HOST);
//        FileForUUIDParams params = new FileForUUIDParams();
//        params.setUuid(uuid);//此处传个人实名认证接口查询中返回的认证图片id，或查询企业认证信息中返回 的企业认证申请表id
//        params.setDocType(docType);//0：图片（默认图片）1：pdf (仅支持企业申请表模板)
//        String result = client.invokeFileForUUID(params);
//        //防止被转移，把字符串转base64
//        String base64 = new String(FddEncryptTool.Base64Encode(result.getBytes())).trim();
//        return ResultBody.success(base64);
//    }
//
//    /**
//     * 查询是否注册法大大
//     */
//    private String checkRegisterFdd(Integer userAccountId){
//        UserAccountDTO userAccountDTO = userServletClient.feignGetUserSimpleInfo(userAccountId);
//        UserFddDO userFddDO = fddVerifyDao.getUserFddByUserAccountId(userAccountId);
//        String customerId = null;
//        if(userFddDO == null){
//            //账号类型1个人 2企业，合伙人默认全部是企业
//            Integer accountType = 2;
//            customerId = this.register(userAccountDTO.getUid(), accountType+"");
//            if(customerId == null){
//                return null;
//            }
//            UserFddDO userFddDO1 = new UserFddDO();
//            userFddDO1.setUserAccountId(userAccountId);
//            userFddDO1.setCustomerId(customerId);
//            userFddDO1.setAccountType(accountType);
//            userFddDO1.setPersonVerifyStatus(0);
//            userFddDO1.setEntVerifyStatus(0);
//            fddVerifyDao.addUserFdd(userFddDO1);
//        }else {
//            customerId = userFddDO.getCustomerId();
//        }
//        return customerId;
//    }
}