package com.huiju.estateagents.eContract.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fadada.sdk.client.FddClientBase;
import com.fadada.sdk.client.authForfadada.FindCertInfo;
import com.fadada.sdk.client.authForfadada.GetPersonVerifyUrl;
import com.huiju.estateagents.common.CommConstant;
import com.huiju.estateagents.common.MD5Utils;
import com.huiju.estateagents.common.StringUtils;
import com.huiju.estateagents.config.FadadaProperties;
import com.huiju.estateagents.eContract.entity.TaContractUser;
import com.huiju.estateagents.eContract.mapper.TaContractUserMapper;
import com.huiju.estateagents.eContract.service.ITaContractUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huiju.estateagents.entity.TaMiniapp;
import com.huiju.estateagents.entity.TaPerson;
import com.huiju.estateagents.entity.TaRaiseRecord;
import com.huiju.estateagents.mapper.TaMiniappMapper;
import jodd.util.URLDecoder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.net.URLEncoder;
import java.time.LocalDateTime;

/**
 * <p>
 * 电子合同注册用户表  服务实现类
 * </p>
 *
 * @author fxf
 * @since 2020-03-26
 */
@Slf4j
@Service
public class TaContractUserServiceImpl extends ServiceImpl<TaContractUserMapper, TaContractUser> implements ITaContractUserService {

    @Autowired
    private FadadaProperties fadadaProperties;

    @Autowired
    private TaContractUserMapper taContractUserMapper;

    @Autowired
    private TaMiniappMapper taMiniappMapper;
    /**
     * 小程序端首次签署合同的是要在法大大处创建账号
     *
     * @param person
     * @param taRaiseRecord
     * @return
     */
    @Override
    public TaContractUser newFirstCustomerInfo(TaPerson person, TaRaiseRecord taRaiseRecord) throws Exception {
        //首先判断是否注册过账号
        QueryWrapper<TaContractUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mini_openid",MD5Utils.md5(person.getMiniOpenid()));
        TaContractUser taContractUser = taContractUserMapper.selectOne(queryWrapper);
        if (null != taContractUser) {
            TaContractUser firstCustomerInfo = getFirstCustomerInfo(person);
            firstCustomerInfo.setRaiseRecordId(taRaiseRecord.getRaiseRecordId());
            firstCustomerInfo.setCertifiedAddress(getFddDownServerHost(person.getMiniappId(),taContractUser.getCertifiedAddress()));
            return firstCustomerInfo;
        }
        //没有法大大账号的先注册
        log.info("========法大大个人注册=======");
        //在法大大注册个人用户
        FddClientBase base = new FddClientBase(fadadaProperties.getAppId(),fadadaProperties.getAppSecret(),fadadaProperties.getVersion(),fadadaProperties.getServeHost());
        //小程序open——id为注册账号
        String open_id = MD5Utils.md5(person.getMiniOpenid());
        //account_type 1是个人注册
        String result =base.invokeregisterAccount(open_id,"1");
        log.info("法大大注册信息{}", result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (jsonObject.getInteger("code") != 1){
            throw new Exception(jsonObject.getString("msg"));
        }

        //插入个人用户数据
        TaContractUser newContractUser = new TaContractUser();
        newContractUser.setMiniOpenid(open_id);
        newContractUser.setFadadaCode(jsonObject.getString("data"));
        newContractUser.setPersonId(person.getPersonId());
        newContractUser.setAuthStatus(CommConstant.CERTIFIED_STATUS_REGISTERED);
        newContractUser.setCreateDate(LocalDateTime.now());
        newContractUser.setOrgId(person.getOrgId());

        log.info("正在申请个人认证,客户编码是{}",jsonObject.getString("data"));
        log.info("appid {} , secret {}, version {} , serverhost {}",fadadaProperties.getAppId(),fadadaProperties.getAppSecret(),fadadaProperties.getVersion(),getFddServerHost(person.getMiniappId(),fadadaProperties.getServeHost()));
        GetPersonVerifyUrl personverify = new GetPersonVerifyUrl(fadadaProperties.getAppId(),fadadaProperties.getAppSecret(),fadadaProperties.getVersion(),getFddServerHost(person.getMiniappId(),fadadaProperties.getServeHost()));
        String customer_id = jsonObject.getString("data");
        //0:三要素标准方案； 1:三要素补充方案 4 纯三要素方案；
        String verifyed_way = "4";
        String page_modify = "1";
        String notify_url = fadadaProperties.getCompanyNotify();
        String redirectUrl = URLEncoder.encode("/onlineSelling/pages/raiseMoney/Certification", "utf-8");
        String return_url=  fadadaProperties.getRedirectUrl() + "?appid=123&redirect="+ redirectUrl;
        String customer_ident_type = "0";
        String personResult = personverify.invokePersonVerifyUrl(customer_id,verifyed_way,
                page_modify,notify_url,return_url,null,customer_ident_type,
                taRaiseRecord.getIdcard(),taRaiseRecord.getTel(),null,"1","1");

        String data = JSON.parseObject(personResult).getString("data");
        if (null !=data){
            String url = JSON.parseObject(data).getString("url");
            url = decode(url);
            newContractUser.setCertifiedAddress(getFddDownServerHost(person.getMiniappId(),url));
            newContractUser.setCertifiedSerialNumber(JSON.parseObject(data).getString("transactionNo"));
        }
        newContractUser.setStatus(0);
        newContractUser.setAuthStatus(CommConstant.CERTIFIED_STATUS_CERTIFICATION);
        newContractUser.setRaiseRecordId(taRaiseRecord.getRaiseRecordId());
        taContractUserMapper.insert(newContractUser);
        return newContractUser;
    }

    /**
     * 替换法大大服务器地址
     * @return
     */
    private String getFddServerHost(String miniappId,String subUrl) {
        TaMiniapp taMiniapp = taMiniappMapper.selectById(miniappId);
        int index = subUrl.indexOf("/");
        int twoIndex = subUrl.indexOf("/",index+1);
        int threeIndex = subUrl.indexOf("/",twoIndex+1);
        String newUrl = StringUtils.isEmpty(taMiniapp.getFddServerHost()) ? subUrl : taMiniapp.getFddServerHost() + subUrl.substring(threeIndex);
        return newUrl;
    }

    /**
     * 替换法大大服务器地址
     * @return
     */
    private String getFddDownServerHost(String miniappId,String subUrl) {
        if (StringUtils.isEmpty(subUrl)){
            return subUrl;
        }
        TaMiniapp taMiniapp = taMiniappMapper.selectById(miniappId);
        int index = subUrl.indexOf("/");
        int twoIndex = subUrl.indexOf("/",index+1);
        int threeIndex = subUrl.indexOf("/",twoIndex+1);
        String newUrl = StringUtils.isEmpty(taMiniapp.getFddDownloadHost()) ? subUrl : taMiniapp.getFddDownloadHost() + subUrl.substring(threeIndex);
        return newUrl;
    }

    /**
     * 去法大大处更新客户的状态
     *
     * @param person
     * @return
     */
    @Override
    public TaContractUser getFirstCustomerInfo(TaPerson person) throws Exception {
        //注册账号信息
        QueryWrapper<TaContractUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mini_openid",MD5Utils.md5(person.getMiniOpenid()));
        TaContractUser taContractUser = taContractUserMapper.selectOne(queryWrapper);
        log.info("个人正在从法大大获取最新数据，企业编号是 {}", taContractUser.getFadadaCode());
        FindCertInfo personCertInfo = new FindCertInfo(fadadaProperties.getAppId(),fadadaProperties.getAppSecret(),fadadaProperties.getVersion(),fadadaProperties.getServeHost());
        String verified_serialno = taContractUser.getCertifiedSerialNumber();
        String result = personCertInfo.invokeFindPersonCert(verified_serialno,
                "1");
        log.info("个人最新数据结果 {}",result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (jsonObject.getInteger("code") != 1){
            throw new Exception(jsonObject.getString("msg"));
        }
        //更新数据
        String data = jsonObject.getString("data");
        if (null !=data){
            JSONObject dataJson = JSONObject.parseObject(data);
            //企业法人、代理人信息
            JSONObject personJson = dataJson.getJSONObject("person");
            if (null != personJson){
                taContractUser.setStatus(personJson.getInteger("status"));
                taContractUser.setTel(personJson.getString("mobile"));
                taContractUser.setIdCard(personJson.getString("idCard"));
                taContractUser.setReason(personJson.getString("auditFailReason"));
            }
        }
        taContractUserMapper.updateById(taContractUser);
        return taContractUser;
    }

    private String decode(String bizContent) {
        bizContent = URLDecoder.decode(bizContent, "utf-8");
        bizContent = new String(Base64.decodeBase64(bizContent.getBytes()));
        return bizContent;
    }
}
