package com.dxhy.core.job.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.dxhy.api.model.invoice.TDxRecordInvoice;
import com.dxhy.common.service.impl.MpBaseServiceImpl;
import com.dxhy.common.util.ZipUtils;
import com.dxhy.common.utils.CommonUtil;
import com.dxhy.core.job.dao.LqTdxInvoiceFileCoreDao;
import com.dxhy.core.job.dao.TDxRecordInvoiceJobDao;
import com.dxhy.core.job.dao.TDxSaleRecordInvoiceJobDao;
import com.dxhy.core.job.entity.TDxInvoiceFileEntity;
import com.dxhy.core.job.entity.TDxSaleRecordInvoiceJobEntity;
import com.dxhy.core.job.service.TdxInvoiceFileService;
import com.dxhy.oss.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;


@Service("tdxRecordTspzKzxxFacade")
@Slf4j
public class TdxInvoiceFileServiceImpl
		extends MpBaseServiceImpl<LqTdxInvoiceFileCoreDao, TDxInvoiceFileEntity>
        implements TdxInvoiceFileService {
			

	@Resource
	private FileService fileService;

	@Resource
	private TDxRecordInvoiceJobDao tDxRecordInvoiceJobDao;
	@Resource
	private TDxSaleRecordInvoiceJobDao tDxSatleRecordInvoiceJobDao;

	@Autowired
	private LqTdxInvoiceFileCoreDao lqTdxInvoiceFileDao;

	/**
	* @Description 数电发票xml源文件下载
	* @param
	* @param tri 用底账查出来的实体
	 * @param fileUrl
	 * @param jxXxtype	  进项销项类型   01进项票   02销项票
	 * @Return void
	* @Author wangruwei
	* @Date 2024/4/9 16:27
	**/
	@Override
	public void dealXmlSource(TDxRecordInvoice tri, String fileUrl, String jxXxtype) throws Exception {
		//先判断是否已有，有的话，不再保存处理
		TDxInvoiceFileEntity tfileExist = lqTdxInvoiceFileDao.selectOne(new LambdaQueryWrapper<TDxInvoiceFileEntity>().eq(TDxInvoiceFileEntity::getUuid, tri.getUuid())
				.isNotNull(TDxInvoiceFileEntity::getXmlPath)
		);
		if(ObjectUtil.isNotEmpty(tfileExist)){
			log.info("uuid:{}。xml在invoice_file表里已存在，不再重复存",tri.getUuid());
			//更新抵账表xmlFlag
			updateXmlFlag(tri,jxXxtype,"1");
			return;
		}
		String xmlFileName = CommonUtil.getFileName(tri.getUuid());
		String tempXmlFilePath = fileService.getLocalPathDefault() + "/temp_xml/" + xmlFileName + ".xml";
		String tempZipFileName = fileService.getLocalPathDefault() + "/temp_xml/" + tri.getUuid() + ".zip";
		String tempJyZipFileDir = fileService.getLocalPathDefault() + "/temp_xml/" + tri.getUuid();
		if (HttpUtil.downloadFile(fileUrl, new File(tempZipFileName)) > 0) {
			log.info("xml文件下载成功，解压缩");
			ZipUtils.jyZip(tempZipFileName, tempJyZipFileDir);
			File file1 = new File(tempJyZipFileDir);
			File[] files = file1.listFiles();
			for (File f : files) {
				if (f.isFile()) {
					if (f.getName().endsWith("xml")||f.getName().endsWith("XML")) {
						FileUtils.copyFile(f, new File(tempXmlFilePath));
						break;
					}
				}
			}
			log.info("xml文件上传ftp");
			File tempFile = new File(tempXmlFilePath);
			if (tempFile.exists()) {
				// FTP文件存储路径
				String ftpFilePath = CommonUtil.getFtpFilePath(fileService.getPathPrefix(),tri.getGfTaxNo(),xmlFileName);
				log.info("开始上传ftp,ftp存储路径:{}",ftpFilePath);
				fileService.uploadFile(ftpFilePath, tempXmlFilePath);
				log.info("上传ftp完成,更新抵账表、插入发票附件表");

				//更新抵账表xmlFlag
				updateXmlFlag(tri,jxXxtype,"1");
				//保存xml路径至t_dx_invoice_file表
				TDxInvoiceFileEntity tdf = new TDxInvoiceFileEntity();
				tdf.setUuid(tri.getUuid());
				tdf.setXmlPath(ftpFilePath);
				tdf.setCreateTime(new Date());
				TDxInvoiceFileEntity tfile = lqTdxInvoiceFileDao.selectOne(new QueryWrapper<TDxInvoiceFileEntity>().eq("uuid", tri.getUuid()));
				if (tfile == null) {
					lqTdxInvoiceFileDao.insert(tdf);
				} else {
					lqTdxInvoiceFileDao.updateById(tdf);
				}

			}
		}
		//删除临时文件
		log.info("删除临时文件");
		File fileDir = new File(tempJyZipFileDir);
		if (fileDir.exists()) {
			FileUtils.deleteDirectory(fileDir);
		}
		FileUtils.deleteQuietly(new File(tempZipFileName));
	}

	/**
	 * @Description 处理源文件下载，xml的保存业务
	 * @param tri
	 * @param pdfUrl
	 * @param jxXxtype	  进项销项类型   01进项票   02销项票
	 * @Return void
	 * @Author wangruwei
	 * @Date 2024/4/9 16:31
	 **/
	@Override
	public void dealPdfSource(TDxRecordInvoice tri, String pdfUrl, String jxXxtype) throws Exception {
		//先判断是否已有，有的话，不再保存处理
		TDxInvoiceFileEntity tfileExist = lqTdxInvoiceFileDao.selectOne(new LambdaQueryWrapper<TDxInvoiceFileEntity>().eq(TDxInvoiceFileEntity::getUuid, tri.getUuid())
				.isNotNull(TDxInvoiceFileEntity::getPdfPath)
		);
		if(ObjectUtil.isNotEmpty(tfileExist)){
			log.info("uuid:{}。pdf在invoice_file表里已存在，不再重复存",tri.getUuid());
			//更新抵账表xmlFlag
			updateXmlFlag(tri,jxXxtype,"2");
			return;
		}
		String pdfFileName = CommonUtil.getFileNamePdf(tri.getUuid());
		String tempPdfFilePath = fileService.getLocalPathDefault() + "/temp_pdf/" + pdfFileName + ".pdf";
		if (HttpUtil.downloadFile(pdfUrl, new File(tempPdfFilePath)) > 0) {
			log.info("pdf文件下载成功");

			log.info("pdf文件上传ftp");
			File tempFile = new File(tempPdfFilePath);
			if (tempFile.exists()) {
				// FTP文件存储路径
				String ftpFilePath = CommonUtil.getFtpFilePath(fileService.getPathPrefix(),tri.getGfTaxNo(),pdfFileName);
				log.info("开始上传ftp,ftp存储路径:{}",ftpFilePath);
				fileService.uploadFile(ftpFilePath, tempPdfFilePath);
				log.info("上传ftp完成,更新抵账表、插入发票附件表");
				//更新抵账表xmlFlag
				updateXmlFlag(tri,jxXxtype,"2");
				//保存pdf路径至t_dx_invoice_file表
				TDxInvoiceFileEntity tdf = new TDxInvoiceFileEntity();
				tdf.setUuid(tri.getUuid());
				tdf.setPdfPath(ftpFilePath);
				tdf.setCreateTime(new Date());
				TDxInvoiceFileEntity tfile = lqTdxInvoiceFileDao.selectOne(new QueryWrapper<TDxInvoiceFileEntity>().eq("uuid",tri.getUuid()));
				if (tfile == null) {
					lqTdxInvoiceFileDao.insert(tdf);
				} else {
					lqTdxInvoiceFileDao.updateById(tdf);
				}
			}
		}
		//删除临时文件
		log.info("删除临时文件");
		File fileDir = new File(tempPdfFilePath);
		if (fileDir.exists()) {
			FileUtils.deleteQuietly(fileDir);
		}
		FileUtils.deleteQuietly(new File(tempPdfFilePath));
	}

	/**
	 * @Description 处理源文件下载，ofd的保存业务
	 * @param tri
	 * @param ofdUrl
	 * @param jxXxtype	  进项销项类型   01进项票   02销项票
	 * @Return void
	 * @Author wangruwei
	 * @Date 2024/4/9 16:31
	 **/
	@Override
	public void dealOfdSource(TDxRecordInvoice tri, String ofdUrl, String jxXxtype) throws Exception {
		//先判断是否已有，有的话，不再保存处理
		TDxInvoiceFileEntity tfileExist = lqTdxInvoiceFileDao.selectOne(new LambdaQueryWrapper<TDxInvoiceFileEntity>().eq(TDxInvoiceFileEntity::getUuid, tri.getUuid())
				.isNotNull(TDxInvoiceFileEntity::getOfdPath)
		);
		if(ObjectUtil.isNotEmpty(tfileExist)){
			log.info("uuid:{}。ofd在invoice_file表里已存在，不再重复存",tri.getUuid());
			//更新抵账表xmlFlag
			updateXmlFlag(tri,jxXxtype,"3");
			return;
		}
		String ofdFileName = CommonUtil.getFileNameOfd(tri.getUuid());
		String tempOfdFilePath = fileService.getLocalPathDefault() + "/temp_ofd/" + ofdFileName + ".ofd";
		if (HttpUtil.downloadFile(ofdUrl, new File(tempOfdFilePath)) > 0) {
			log.info("ofd文件下载成功");

			log.info("ofd文件上传ftp");
			File tempFile = new File(tempOfdFilePath);
			if (tempFile.exists()) {
				// FTP文件存储路径
				String ftpFilePath = CommonUtil.getFtpFilePath(fileService.getPathPrefix(),tri.getGfTaxNo(),ofdFileName);
				log.info("开始上传ftp,ftp存储路径:{}",ftpFilePath);
				fileService.uploadFile(ftpFilePath, tempOfdFilePath);
				log.info("上传ftp完成,更新抵账表、插入发票附件表");
				//更新抵账表xmlFlag
				updateXmlFlag(tri,jxXxtype,"3");
				//保存ofd路径至t_dx_invoice_file表
				TDxInvoiceFileEntity tdf = new TDxInvoiceFileEntity();
				tdf.setUuid(tri.getUuid());
				tdf.setOfdPath(ftpFilePath);
				tdf.setCreateTime(new Date());
				TDxInvoiceFileEntity tfile = lqTdxInvoiceFileDao.selectOne(new QueryWrapper<TDxInvoiceFileEntity>().eq("uuid", tri.getUuid()));
				if (tfile == null) {
					lqTdxInvoiceFileDao.insert(tdf);
				} else {
					lqTdxInvoiceFileDao.updateById(tdf);
				}
			}
		}
		//删除临时文件
		log.info("删除临时文件");
		File fileDir = new File(tempOfdFilePath);
		if (fileDir.exists()) {
			FileUtils.deleteQuietly(fileDir);
		}
		FileUtils.deleteQuietly(new File(tempOfdFilePath));
	}

	private void updateXmlFlag(TDxRecordInvoice tri, String jxXxtype,String flag) {

		//更新抵账表
		if("01".equals(jxXxtype)){
			String xmlFlag =  tDxRecordInvoiceJobDao.selectOne(new LambdaQueryWrapper<TDxRecordInvoice>().eq(TDxRecordInvoice::getUuid, tri.getUuid())).getXmlFlag();
			xmlFlag = CommonUtil.addXmlFlag(xmlFlag,flag);
			tDxRecordInvoiceJobDao.update(null, new UpdateWrapper<TDxRecordInvoice>().eq("uuid", tri.getUuid()).set("xml_flag", xmlFlag));
		}
		if("02".equals(jxXxtype)){
			String xmlFlag =  tDxSatleRecordInvoiceJobDao.selectOne(new LambdaQueryWrapper<TDxSaleRecordInvoiceJobEntity>().eq(TDxSaleRecordInvoiceJobEntity::getUuid, tri.getUuid())).getXmlFlag();
			xmlFlag = CommonUtil.addXmlFlag(xmlFlag,flag);
			tDxSatleRecordInvoiceJobDao.update(null, new LambdaUpdateWrapper<TDxSaleRecordInvoiceJobEntity>().eq(TDxSaleRecordInvoiceJobEntity::getUuid, tri.getUuid()).set(TDxSaleRecordInvoiceJobEntity::getXmlFlag, xmlFlag));
		}
	}

	public static void main(String[] args) {
	    String xmlFlag = "2";
	    String s = "3";
        if(xmlFlag.contains(s)){
            System.out.println(xmlFlag);
        }else{
            List<String> list = new LinkedList(Arrays.asList(xmlFlag.split("")));
            list.add(s);
            List<String> collect = list.stream().sorted().collect(Collectors.toList());
            System.out.println(String.join("", collect).replace("0", ""));
        }
    }
}
