package com.sunxung.factoring.service.tradingPlatform.Impl;

import cn.hutool.core.date.DateUnit;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sunxung.factoring.component.util.DateUtil;
import com.sunxung.factoring.component.util.ElectronicSignatureUtil;
import com.sunxung.factoring.entity.GridPage;
import com.sunxung.factoring.entity.ResponseJson;
import com.sunxung.factoring.entity.tradingPlatform.Platform;
import com.sunxung.factoring.entity.vo.ConditionVo;
import com.sunxung.factoring.mapper.tradingPlatform.PlatformMapper;
import com.sunxung.factoring.service.businessmanagement.BusinessBasicInfoService;
import com.sunxung.factoring.service.sys.UserService;
import com.sunxung.factoring.service.tradingPlatform.PlatformService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author liutao yaFan
 */
@Service
public class PlatformServiceImpl extends ServiceImpl<PlatformMapper,Platform> implements PlatformService {


    @Autowired
    private RestTemplate restTemplate;

    @Value("${sop.synchronizeInformation}")
    private String synchronizeInformation;

    @Value("${sop.getFlushUrl}")
    private String flushUrl;

    @Value("${sop.getEnterpriseInfoUrl}")
    private String enterpriseInfoUrl;

    private static Logger logger = LogManager.getLogger(PlatformServiceImpl.class);

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseJson add(Platform platform){
//       对比统一社会信用代码
        List<Platform> list = list(new QueryWrapper<Platform>().eq("socialCreditCode",platform.getSocialCreditCode()));
        if(!list.isEmpty()){
            return new ResponseJson("500","企业已添加，勿重复操作");
        }

        ResponseJson forObject = restTemplate.getForObject(enterpriseInfoUrl+"?code="+platform.getSocialCreditCode(), ResponseJson.class);
        Map<String,Object> data = (Map) forObject.getData();


        platform.setAuthUrl(data.get("authUrl").toString());
        platform.setShortAuthUrl(data.get("shortAuthUrl").toString());
        platform.setAuthStatus(0);
        platform.setFddCustomerId(data.get("fddCustomerId").toString());
        platform.setAutoSignUrl(data.get("autoSignUrl").toString());
        platform.setShortAutoSignUrl(data.get("shortAutoSignUrl").toString());
        platform.setShortAutoSignUrlCreate(new Date());
        Integer autoSignStatus = (Integer) data.get("autoSignStatus");
        platform.setAutoSignStatus(autoSignStatus == 1?true:false);
        save(platform);

        //电子签章获取认证地址
//        String customerId = ElectronicSignatureUtil.registerAccount(platform.getSocialCreditCode(), "2");
//        String authResult = ElectronicSignatureUtil.getAuthUrl("2",platform.getSocialCreditCode(),null);
//        JSONObject authJson = (JSONObject) JSONObject.parse(authResult);
//        String authUrl = authJson.getString("authUrl");
//        String customerId = authJson.getString("customerId");
//        String shortAuthUrl = ElectronicSignatureUtil.shortUrl(null, authUrl);
//        platform.setShortAuthUrl(shortAuthUrl);
//        platform.setShortAuthUrlCreate(new Date());
//        platform.setFddCustomerId(customerId);
//        platform.setAuthUrl(authUrl);
//        save(platform);
//        String transactionId = "platformFDD" + platform.getId()+"FDD"+ DateUtil.getCurrentDate().replace("-","").replace(" ","").replace(":","");
//        logger.error("transactionId:"+transactionId);
//        String beforeAutoSignUrl = ElectronicSignatureUtil.beforeAutoSign(transactionId,customerId,customerId);
//        String shortAutoSignUrl = ElectronicSignatureUtil.shortUrl(null, beforeAutoSignUrl);
//        platform.setShortAutoSignUrl(shortAutoSignUrl);
//        platform.setShortAutoSignUrlCreate(new Date());
//        platform.setAutoSignUrl(beforeAutoSignUrl);
//        platform.setAuthStatus(0);
//        updateById(platform);
        return new ResponseJson("新增成功");
    }

    @Override
    public List<Platform> findAll() {
        return list();
    }

    @Override
    public GridPage findPage(ConditionVo conditionVo) {
        Page<Platform> page = PageHelper.startPage(conditionVo.getPage(), conditionVo.getRows());
        list(new QueryWrapper<Platform>().orderByDesc("gmt_create"));
        return new GridPage(conditionVo.getRows(),conditionVo.getPage(),page.getTotal(),page.getResult());
    }

    @Override
    public Platform getPlateformByBusiness(String  businessNumber) {
        return null;
    }

    @Override
    public void updateShortUrl(Date date) {
        List<Platform> list = list();
        if(list!=null && list.size()>0){
            for (Platform platform : list) {
                if(platform.getAuthStatus().equals(0)){
                    Date shortAuthUrlCreate = platform.getShortAuthUrlCreate();
                    long between = cn.hutool.core.date.DateUtil.between(shortAuthUrlCreate, date, DateUnit.DAY);
                    if(between>=6){
                        //注册链接
                        String newShortUrl = ElectronicSignatureUtil.shortUrl(null, platform.getAuthUrl());
                        platform.setShortAuthUrl(newShortUrl);
                        platform.setShortAuthUrlCreate(date);
                        //自动签署链接
                        String autoSignUrl = platform.getAutoSignUrl();
                        if(autoSignUrl!=null){
                            String newShortAutoSignUrl = ElectronicSignatureUtil.shortUrl(null,autoSignUrl);
                            platform.setShortAutoSignUrl(newShortAutoSignUrl);
                            platform.setShortAutoSignUrlCreate(date);
                        }
                        updateById(platform);
                    }
                }
            }
        }
    }

    @Override
    public void flushUrl(Long id) {
        Platform platform = getById(id);

        ResponseJson forObject = restTemplate.getForObject(flushUrl+"?code="+platform.getSocialCreditCode(), ResponseJson.class);
        Map<String,String> data = (Map) forObject.getData();
        platform.setAuthUrl(data.get("authUrl"));
        platform.setShortAuthUrl(data.get("shortAuthUrl"));
        platform.setAuthStatus(0);
        platform.setFddCustomerId(data.get("fddCustomerId"));
        //更新自动签链接
        platform.setAutoSignUrl(data.get("autoSignUrl"));
        platform.setShortAutoSignUrl(data.get("shortAutoSignUrl"));
        platform.setAutoSignStatus(false);

//        //删除中间服务的认证信息
//        ElectronicSignatureUtil.removeAuthInfo(platform.getSocialCreditCode());
//        //刷新认证信息
//        String authResult = ElectronicSignatureUtil.getAuthUrl("2",platform.getSocialCreditCode(),null);
//        JSONObject authJson = (JSONObject) JSONObject.parse(authResult);
//        String authUrl = authJson.getString("authUrl");
//        String customerId = authJson.getString("customerId");
//        String shortAuthUrl = ElectronicSignatureUtil.shortUrl(null, authUrl);
//        platform.setShortAuthUrl(shortAuthUrl);
//        platform.setShortAuthUrlCreate(new Date());
//        platform.setFddCustomerId(customerId);
//        platform.setAuthUrl(authUrl);
//        String transactionId = "platformFDD" + platform.getId()+"FDD"+ DateUtil.getCurrentDate().replace("-","").replace(" ","").replace(":","");
//        logger.error("transactionId:"+transactionId);
//        String beforeAutoSignUrl = ElectronicSignatureUtil.beforeAutoSign(transactionId,customerId,customerId);
//        String shortAutoSignUrl = ElectronicSignatureUtil.shortUrl(null, beforeAutoSignUrl);
//        platform.setShortAutoSignUrl(shortAutoSignUrl);
//        platform.setShortAutoSignUrlCreate(new Date());
//        platform.setAutoSignUrl(beforeAutoSignUrl);
//        platform.setAuthStatus(0);
//        platform.setAutoSignStatus(false);
        updateById(platform);
    }

    @Override
    public void flush(Long id) {
        Platform platform = getById(id);

        //先从sop更新信息
        ResponseJson forObject = restTemplate.getForObject(synchronizeInformation+"?socialCreditCode="+platform.getSocialCreditCode(), ResponseJson.class);
        Map<String,String> data = (Map) forObject.getData();
        platform.setAuthUrl(data.get("authUrl"));
        platform.setShortAuthUrl(data.get("shortAuthUrl"));
        platform.setFddCustomerId(data.get("fddCustomerId"));
        //更新自动签链接
        platform.setAutoSignUrl(data.get("autoSignUrl"));
        platform.setShortAutoSignUrl(data.get("shortAutoSignUrl"));
        updateById(platform);

        //获取认证状态
        String result = ElectronicSignatureUtil.getAuthInfo(platform.getSocialCreditCode(), "2");
        if ("1".equals(result)){
            platform.setAuthStatus(1);
            updateById(platform);
        }
    }
}
