package com.sunxung.factoring.service.credit.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.config.FileUploadProperties;
import com.sunxung.factoring.component.exception.ValidatorException;
import com.sunxung.factoring.component.util.ElectronicSignatureUtil;
import com.sunxung.factoring.dict.impl.FileModuleDict;
import com.sunxung.factoring.entity.GridPage;
import com.sunxung.factoring.entity.credit.CreditDetail;
import com.sunxung.factoring.entity.credit.CreditInfo;
import com.sunxung.factoring.entity.entprise.Enterprise;
import com.sunxung.factoring.entity.sys.FileStorage;
import com.sunxung.factoring.mapper.credit.CreditInfoMapper;
import com.sunxung.factoring.mapper.customerinformation.ElectronicSignaturePersonalMapper;
import com.sunxung.factoring.service.credit.CreditDetailService;
import com.sunxung.factoring.service.credit.CreditService;
import com.sunxung.factoring.service.sys.FileStorageService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

@Service
public class CreditServiceImpl extends ServiceImpl<CreditInfoMapper, CreditInfo> implements CreditService {

    @Autowired
    private CreditDetailService creditDetailService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ElectronicSignaturePersonalMapper electronicSignaturePersonalMapper;

    @Autowired
    private FileStorageService fileStorageService;

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

    @Override
    public GridPage findByName(String name, Integer type, Integer page, Integer rows) {
        Page objectPage = PageHelper.startPage(page, rows);

        LambdaQueryWrapper<CreditInfo> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(CreditInfo::getType,type);
        lambdaQueryWrapper.and(temp->temp.like(CreditInfo::getName,name).or().like(CreditInfo::getCardNo,name));
        lambdaQueryWrapper.orderByDesc(CreditInfo::getGmtCreate);
        List<CreditInfo> list = list(lambdaQueryWrapper);
        return new GridPage(rows,page,objectPage.getTotal(),list);
    }
                                                                     
    @Override
    public void add(CreditInfo creditInfo) {
        CreditInfo creditInfo1 = this.getOne(new QueryWrapper<CreditInfo>().eq("card_no", creditInfo.getCardNo()));
        if (creditInfo1 != null){
            throw new ValidatorException("200","该企业已存在！");
        }
        save(creditInfo);
        //保存征信详情
        CreditDetail creditDetail = new CreditDetail();
        creditDetail.setCreditId(creditInfo.getId());
        creditDetail.setSearchDate(creditInfo.getSearchDate());
        creditDetail.setAuthAddress(creditInfo.getAuthAddress());
        creditDetail.setCreditAddress(creditInfo.getCreditAddress());
        creditDetailService.add(creditDetail);
    }

    @Override
    public CreditInfo get(Long id) {
        CreditInfo creditInfo = getById(id);
        if (StringUtils.isNotEmpty(creditInfo.getCardPhoto())){
            FileStorage fileStorage = fileStorageService.get(Long.valueOf(creditInfo.getCardPhoto()));
            creditInfo.setCardPhotoFile(fileStorage);
        }
        if (StringUtils.isNotEmpty(creditInfo.getCardRevPhoto())){
            FileStorage fileStorage = fileStorageService.get(Long.valueOf(creditInfo.getCardRevPhoto()));
            creditInfo.setCardRevPhotoFile(fileStorage);
        }
        if (StringUtils.isNotEmpty(creditInfo.getAuthAddress())){
            FileStorage fileStorage = fileStorageService.get(Long.valueOf(creditInfo.getAuthAddress()));
            creditInfo.setAuthAddressFile(fileStorage);
        }
        if (StringUtils.isNotEmpty(creditInfo.getCreditAddress())){
            FileStorage fileStorage = fileStorageService.get(Long.valueOf(creditInfo.getCreditAddress()));
            creditInfo.setCreditAddressFile(fileStorage);
        }
        List<CreditDetail> creditDetails = creditDetailService.getByCreditId(id);
        if (CollectionUtil.isNotEmpty(creditDetails)){
            for (CreditDetail creditDetail : creditDetails){
                if (StringUtils.isNotEmpty(creditDetail.getAuthAddress())){
                    FileStorage fileStorage = fileStorageService.get(Long.valueOf(creditDetail.getAuthAddress()));
                    creditDetail.setAuthAddressFile(fileStorage);
                }
                if (StringUtils.isNotEmpty(creditDetail.getCreditAddress())){
                    FileStorage fileStorage = fileStorageService.get(Long.valueOf(creditDetail.getCreditAddress()));
                    creditDetail.setCreditAddressFile(fileStorage);
                }
            }
            creditInfo.setCreditDetails(creditDetails);
        }
        return creditInfo;
    }

    @Override
    public void update(CreditInfo creditInfo) {
        //更新最近查询时间
        updateById(creditInfo);
        if ((creditInfo.getType() == 1 && StringUtils.isNotEmpty(creditInfo.getCreditAddress()) ) ||
                (creditInfo.getType() == 0 && (StringUtils.isNotEmpty(creditInfo.getCreditAddress()) || creditInfo.getSearchDate() != null))){
            CreditDetail creditDetail = new CreditDetail();
            creditDetail.setCreditId(creditInfo.getId());
            creditDetail.setAuthAddress(creditInfo.getAuthAddress());
            creditDetail.setCreditAddress(creditInfo.getCreditAddress());
            creditDetail.setSearchDate(creditInfo.getSearchDate());
            creditDetailService.add(creditDetail);
        }
    }

    @Override
    public FileStorage getAuthAddress(String cardNo) throws Exception {
        FileStorage result = null;
        List<Enterprise> list = electronicSignaturePersonalMapper.findByComName(cardNo, null);
        for (Enterprise enterprise : list) {
            if (enterprise.getCertificateSignStatus() == 1){
                String contractId = enterprise.getCertificateContractId();
                String url = ElectronicSignatureUtil.downloadContract(contractId);
                //下载征信授权书
                result = createFileStorage("征信授权书", ".pdf", FileModuleDict.ChildEnum.CREDIT_AUTH.getCode());
                fileStorageService.add(result);
                downloadFile(url,result.getAbsolutePath());
                break;
            }
        }
        return result;
    }


    public static FileStorage createFileStorage(String name,String suffix,
                                                   String fileBusinessEnum) {
        FileStorage fileStorageDO = new FileStorage();
        fileStorageDO.setOriginalName(name);
        fileStorageDO.setFileType(suffix);
        String newFileName = IdUtil.fastSimpleUUID() + suffix;
        FileUploadProperties bean = SpringUtil.getBean(FileUploadProperties.class);
        fileStorageDO.setPath(fileBusinessEnum + File.separator + newFileName);
        File file = new File(bean.getStoragePath() + File.separator + fileBusinessEnum + File.separator
                + newFileName);
        fileStorageDO.setAbsolutePath(file.getAbsolutePath());
        FileStorage.Belong belong = new FileStorage.Belong();
        belong.setBelongType(fileBusinessEnum);
        fileStorageDO.setBelong(belong);
        return fileStorageDO;
    }

    /**
     * 根据网络URL下载文件
     * @param fileUrl
     * @param fileLocal
     * @return
     * @throws Exception
     */
    public static boolean downloadFile(String fileUrl,String fileLocal) throws Exception {
        boolean flag=false;
        URL url = new URL(fileUrl);
        HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
        urlCon.setConnectTimeout(15000);
        urlCon.setReadTimeout(15000);
        int code = urlCon.getResponseCode();
        if (code != HttpURLConnection.HTTP_OK) {
            throw new Exception("文件读取失败");
        }
        //读文件流
        DataInputStream in = new DataInputStream(urlCon.getInputStream());
        DataOutputStream out = new DataOutputStream(new FileOutputStream(fileLocal));
        byte[] buffer = new byte[2048];
        int count = 0;
        while ((count = in.read(buffer)) > 0) {
            out.write(buffer, 0, count);
        }
        try {
            if(out!=null) {
                out.close();
            }
            if(in!=null) {
                in.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        flag=true;
        return flag;
    }

    @Override
    public List<Enterprise> getBusinessByKeyWord(String keyword) {
        String url = getBusinessByKeyWordUrl + "?keyword=" + keyword;
        JSONObject responseJson = restTemplate.getForObject(url, JSONObject.class);
        if(responseJson != null){
            List<JSONObject> list= responseJson.getBeanList("data", JSONObject.class);
            if(CollectionUtil.isNotEmpty(list)){
                List<Enterprise> result = new ArrayList<>();
                for (JSONObject jsonObject : list) {
                    Enterprise enterprise = new Enterprise(jsonObject);
                    result.add(enterprise);
                }
                return result;
            }
        }
        return null;
    }


}
