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

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fadada.sdk.utils.crypt.FddEncryptTool;
import com.fadada.sdk.verify.client.FddVerifyClient;
import com.fadada.sdk.verify.model.req.CompanyVerifyUrlParams;
import com.mmc.iuav.response.ResultBody;
import com.mmc.iuav.response.ResultEnum;
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.dao.fdd.UserFddAuthDao;
import com.mmc.iuav.user.entity.UserAccountDO;
import com.mmc.iuav.user.entity.fdd.FddVerifyInfoDO;
import com.mmc.iuav.user.entity.fdd.UserFddDO;
import com.mmc.iuav.user.model.dto.LoginSuccessDTO;
import com.mmc.iuav.user.model.fdd.resp.CompanyVerifyResp;
import com.mmc.iuav.user.model.fdd.resp.PersonVerifyResp;
import com.mmc.iuav.user.service.fdd.FddService;
import com.mmc.iuav.user.service.fdd.UserFddAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

/**
 * author:zhenjie
 * Date:2022/9/1
 * time:15:46
 */
@Service
public class UserFddAuthServiceImpl implements UserFddAuthService {

    @Autowired
    private FddService fddService;

    @Resource
    private UserServiceDao userServiceDao;

    @Autowired
    private UserFddAuthDao userFddAuthDao;

    @Override
    public String register(String uid, String accountType) {
        return fddService.register(uid, accountType);
    }

    @Override
    public PersonVerifyResp getPersonVerifyUrl(String customerId) {
        return fddService.getPersonVerifyUrl(customerId);
    }

    @Override
    public ResultBody getCompanyVerifyUrl(Integer port, LoginSuccessDTO loginSuccessDTO) {
        String uId;
        if (port.equals(0)) {
            // 获取小程序用户信息拿到unionId
            UserAccountDO userInfo = userServiceDao.getUserAccountById(loginSuccessDTO.getUserAccountId());
            uId = this.replaceUnableString(userInfo.getUnionId());
        } else {
            uId = loginSuccessDTO.getUserAccountId().toString();
        }
        //验证是否注册企业
        String customerId = this.checkRegisterFdd(uId);
        if (customerId == null) {
            return ResultBody.error(ResultEnum.REQUEST_PARAM_ILLEGAL_ERROR);
        }
        UserFddDO userFddDO = userFddAuthDao.checkRegisterFdd(uId);
        if (userFddDO == null) {
            return ResultBody.error(ResultEnum.NOT_FOUND);
        }
        //查看原来是否有申请
        FddVerifyInfoDO verifyInfoDO = userFddAuthDao.getCompanyVerifyUrl(userFddDO.getCustomerId());
        if (verifyInfoDO == null) {
            CompanyVerifyResp companyVerifyResp = this.reqCompanyVerifyUrl(customerId);
            if (companyVerifyResp == null) {
                return ResultBody.error(ResultEnum.REQUEST_PARAM_ILLEGAL_ERROR);
            }
            FddVerifyInfoDO verifyInfoDO1 = new FddVerifyInfoDO();
            verifyInfoDO1.setUserFddId(userFddDO.getId());
            verifyInfoDO1.setCustomerId(customerId);
            verifyInfoDO1.setTransactionNo(companyVerifyResp.getTransactionNo());
            verifyInfoDO1.setUrl(companyVerifyResp.getUrl());
            userFddAuthDao.insertVerifyInfo(verifyInfoDO1);
            return ResultBody.success(companyVerifyResp.getUrl());
        }
        return ResultBody.success(verifyInfoDO.getUrl());
    }


    @Override
    public ResultBody notifyECertRes(Map<String, String> map) {
        String appId = map.get("appId");
        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);
        }
        FddVerifyInfoDO verifyInfoDO = userFddAuthDao.getCompanyVerifyUrl(customerId);
        if (verifyInfoDO == null) {
            return ResultBody.error(ResultEnum.NOT_FOUND);
        }
        //修改认证状态
        userFddAuthDao.updateCompanyCertStatus(customerId, status);
        //通过需要申请证书
        if (status.equals("4")) {
            fddService.getApplyCert(verifyInfoDO.getCustomerId(), verifyInfoDO.getTransactionNo());
        }
//        // 已认证实时同步到小程序用户
//        if(status.equals("4")){
//            UserFddDO appUserFddDO = appUserFddAuthDao.getAppUserFddInfoByCustomerId(customerId);
//            if(appUserFddDO!=null){
//                mallUserClient.feingUpdateEntVerify(appUserFddDO.getUnionId(),1,appUserFddDO.getCreateTime());
//            }
//        }
        return ResultBody.success();
    }

    //
//    @Override
//    public ResultBody findCompanyCertInfo(String unionId) {
//        String uId = this.replaceUnableString(unionId);
//        UserFddDO appUserFddDO = appUserFddAuthDao.getAppUserFddInfo(uId);
//        if(appUserFddDO == null){
//            return ResultBody.error(ResultEnum.REQUEST_PARAM_ILLEGAL_ERROR);
//        }
//        AppEVerifyInfoDO appEVerifyInfoDO = appUserFddAuthDao.getCompanyVerifyUrl(appUserFddDO.getCustomerId());
//        if(appEVerifyInfoDO == null){
//            return ResultBody.error(ResultEnum.REQUEST_PARAM_ILLEGAL_ERROR);
//        }
//        FddVerifyClient client = new FddVerifyClient(FddConnectConstant.APP_ID, FddConnectConstant.APP_KEY, FddConnectConstant.VERSION, FddConnectConstant.HOST);
//        FindCompanyCertParams params = new FindCompanyCertParams();
//        params.setVerifiedSerialNo(appEVerifyInfoDO.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 getAppUserFddInfo(String unionId) {
//        String uId = this.replaceUnableString(unionId);
//        UserFddDO appUserFddDO = appUserFddAuthDao.getAppUserFddInfo(uId);
//        return ResultBody.success(appUserFddDO == null ? null : appUserFddDO.buildAppUserFddDTO());
//    }
//
    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.setNotifyUrl(FddConnectConstant.MMC_URL + FddConstant.NOTIFY_E_CERT_RES);
        params.setMVerifiedWay("4");
        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;
    }

    private String checkRegisterFdd(String unionId) {
        //查看是否已注册
        UserFddDO userFddDO = userFddAuthDao.checkRegisterFdd(unionId);
        String customerId;
        if (userFddDO == null) {
            //账号类型1个人 2企业
            Integer accountType = 2;
            customerId = this.register(unionId, accountType.toString());
            if (customerId == null) {
                return null;
            }
            UserFddDO userFddDO1 = new UserFddDO();
            userFddDO1.setUnionId(unionId);
            userFddDO1.setCustomerId(customerId);
            userFddDO1.setAccountType(accountType);
            userFddDO1.setEntVerifyStatus(0);
            userFddDO1.setPersonVerifyStatus(0);
            userFddAuthDao.insertAppUserFdd(userFddDO1);
        } else {
            customerId = userFddDO.getCustomerId();
        }
        return customerId;
    }

    //
    @Override
    public String replaceUnableString(String uid) {
        String u = uid.replaceAll(FddConstant.UID_REGEX, "");
        return u;
    }
//
//    @Override
//    public List<AppUserFddDTO> feignGetAppUserFddInfo(List<String> unionId) {
//        List<String> uids = new ArrayList<>();
//        for (String uId : unionId) {
//            String repUnionId = this.replaceUnableString(uId);
//            uids.add(repUnionId);
//        }
//        List<UserFddDO> appUserFddDOs = appUserFddAuthDao.feignGetAppUserFddInfo(uids);
//        List<AppUserFddDTO> appUserFddDTOS = new ArrayList<>();
//        if(!CollectionUtils.isEmpty(appUserFddDOs)){
//            appUserFddDTOS = appUserFddDOs.stream().map(UserFddDO::buildAppUserFddDTO).collect(Collectors.toList());
//        }
//        return appUserFddDTOS;
//    }
}
