package com.inkasso.factoring.acceptanceManagement.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.util.StringUtil;
import com.inkasso.adapter.exception.BusinessException;
import com.inkasso.adapter.util.CodeUtil;
import com.inkasso.adapter.util.CollectionUtil;
import com.inkasso.auth.exception.ValidatorException;
import com.inkasso.auth.response.ResponseJson;
import com.inkasso.factoring.acceptanceManagement.dao.CAcceptanceSignConfirmationMapper;
import com.inkasso.factoring.acceptanceManagement.entity.*;
import com.inkasso.factoring.acceptanceManagement.service.*;
import com.inkasso.factoring.common.util.ElectronicSignatureUtil;
import com.inkasso.factoring.common.util.PdfUtil;
import com.inkasso.factoring.common.util.onlineConverter.OfficeConverterUtil;
import com.inkasso.factoring.creditmanagement.service.IEnterpriseService;
import com.inkasso.factoring.electronicSignature.entity.ElectronicSignaturePersonal;
import com.inkasso.factoring.electronicSignature.entity.FddSignData;
import com.inkasso.factoring.electronicSignature.service.IElectronicSignaturePersonalService;
import com.inkasso.factoring.file.entity.FileStorageDO;
import com.inkasso.factoring.file.enums.FileTypeEnum;
import com.inkasso.factoring.file.service.FileService;
import com.inkasso.factoring.steelwaiter.service.ISellBillItemService;
import com.inkasso.factoring.steelwaiter.service.ISellBillService;
import com.itextpdf.text.pdf.PdfReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 验收单签署确认表 服务实现类
 * </p>
 *
 * @author yafan
 * @since 2023-11-30
 */
@Service
public class CAcceptanceSignConfirmationServiceImpl extends ServiceImpl<CAcceptanceSignConfirmationMapper, CAcceptanceSignConfirmation> implements ICAcceptanceSignConfirmationService {

    @Autowired
    private ICAcceptanceBasicInfoService acceptanceBasicInfoService;
    @Autowired
    private ICAcceptanceSignConfirmationElectronicInfoService acceptanceSignConfirmationElectronicInfoService;
    @Autowired
    private ICAcceptanceGoodsInfoService acceptanceGoodsInfoService;
    @Autowired
    private FileService fileService;
    @Autowired
    private ICAcceptanceSignConfirmationGoodsInfoService acceptanceSignConfirmationGoodsInfoService;
    @Autowired
    private ICAcceptancePersonInfoService acceptancePersonInfoService;
    @Autowired
    private IElectronicSignaturePersonalService electronicSignaturePersonalService;
    @Autowired
    private ISellBillItemService sellBillItemService;
    @Autowired
    private ISellBillService sellBillService;
    @Autowired
    private RestTemplate restTemplate;
    @Value("${trade.acceptanceSignHandleProcessUrl}")
    private String acceptanceSignHandleProcessUrl;
    @Autowired
    private IEnterpriseService enterpriseService;

    @Override
    public ResponseJson signConfirm(CAcceptanceSignConfirmation acceptanceSignConfirmation) {
       // Long businessKey = acceptanceSignConfirmation.getBusinessKey();
       // CAcceptanceBasicInfo acceptanceBasicInfo = acceptanceBasicInfoService.getById(businessKey);
        lambdaUpdate().set(CAcceptanceSignConfirmation::getRemark, acceptanceSignConfirmation.getRemark())
                .set(CAcceptanceSignConfirmation::getSignConclusion, acceptanceSignConfirmation.getSignConclusion())
                .eq(CAcceptanceSignConfirmation::getId, acceptanceSignConfirmation.getId()).update();
        if (acceptanceSignConfirmation.getSignConclusion()==1) {
            List<CAcceptanceSignConfirmationElectronicInfo> acceptanceSignConfirmationElectronicInfos = acceptanceSignConfirmationElectronicInfoService.lambdaQuery()
                    .eq(CAcceptanceSignConfirmationElectronicInfo::getcAcceptanceSignConfirmationId, acceptanceSignConfirmation.getId()).list();
            boolean allMatch = acceptanceSignConfirmationElectronicInfos.stream().allMatch(r -> r.getSignStatus().equals(1));
            if (!allMatch) {
                throw new BusinessException(CodeUtil.FAIL, "所有文件都签署完成才能提交！");
            }
            //签署确认 无法修改货物信息 所以 代码注释
//            if (CollectionUtil.isNotEmpty(acceptanceGoodInfos)) {
//                for (CAcceptanceGoodsInfo acceptanceBusinessGood : acceptanceGoodInfos) {
//                    acceptanceBusinessGood.setcAcceptanceBasicInfoId(businessKey);
//                }
//                acceptanceGoodsInfoService.saveBatch(acceptanceGoodInfos);
//                try {
//                    XMlToDoc xmlDoc = new XMlToDoc();
//                    //模板中填充数据
//                    File file = acceptanceBasicInfoService.inputData(acceptanceBasicInfo, xmlDoc);
//                    int lastIndexOf = file.getName().lastIndexOf(".");
//                    String fileName = file.getName().toLowerCase(Locale.ROOT);
//                    String name = fileName.substring(0, lastIndexOf);
//                    FileStorageDO fileStorage = FileStorageUtil.createFileStorage2(name, file.getName().substring(lastIndexOf + 1),
//                            FileTypeEnum.ACCEPTANCE_UPSTREAM_FILE);
//                    fileService.updateBusinessId(fileStorage.getId(), acceptanceBasicInfo.getId());
////上传合同
//                    String contractId = UUID.randomUUID().toString().trim().replaceAll("-", "").toUpperCase();
//                    String docTitle = "上游验收单" + acceptanceBasicInfo.getAcceptanceNumber();
//                    String transactionId = UUID.randomUUID().toString().trim().replaceAll("-", "").toUpperCase();
//                    ElectronicSignatureUtil.uploadContract(contractId, docTitle, file);
//                    //采购合同自动签署
//                    Platform platform = platformService.getById(acceptanceBasicInfo.getTradingPlatformId());
//                    String signKeyword = "gz";
//                    ElectronicSignatureUtil.autoSign(transactionId, contractId, platform.getFddCustomerId(), docTitle, signKeyword);
//                    //合同下载
//                    String contDownUrl = ElectronicSignatureUtil.downloadContract(contractId);
//                    FileStorage contractSupplementFile = fileService.addFileStorageWithBelongAndName(contractId, FileModuleDict.ChildEnum.ACCEPTANCE_UPSTREAM_FILE_SIGN, contDownUrl, null);
//                    fileStorageService.saveAttachmentRefByFileStorage(contractSupplementFile, FileModuleDict.ChildEnum.ACCEPTANCE_UPSTREAM_FILE_SIGN, acceptanceBasicInfo.getId());
//                    //合同归档
//                    ElectronicSignatureUtil.contractFiled(contractId);
//                } catch (Exception e) {
//                    throw new BusinessException(CodeUtil.FAIL, "生成验收单据出错");
//                }
//            } else {
//                if (acceptanceSignConfirmation.getSignConclusion()==1) {
//                    throw new ValidatorException(CodeUtil.FAIL, "验收货物必填！");
//                }
//            }
        }

        // 发送JSON格式的POST请求
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        String s = JSONObject.toJSONString(acceptanceSignConfirmation);
        HttpEntity<String> httpEntity = new HttpEntity<>(s, headers);

        ResponseEntity<ResponseJson> jsonResponseEntity = restTemplate
                .postForEntity(acceptanceSignHandleProcessUrl, httpEntity, ResponseJson.class);
        return jsonResponseEntity.getBody();

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CAcceptanceSignConfirmation getDetail(Long businessKey) {
        ElectronicSignaturePersonal signaturePersonal;
        CAcceptanceBasicInfo acceptanceBasicInfo = acceptanceBasicInfoService.getById(businessKey);
        CAcceptancePersonInfo acceptancePersonInfo = acceptancePersonInfoService.getById(acceptanceBasicInfo.getSigner());
        ElectronicSignaturePersonal oldElectronicSignaturePersonal = electronicSignaturePersonalService.lambdaQuery()
                .eq(ElectronicSignaturePersonal::getName, acceptancePersonInfo.getName())
                .eq(ElectronicSignaturePersonal::getMobile, acceptancePersonInfo.getMobile()).one();
        if (oldElectronicSignaturePersonal != null) {
            signaturePersonal = oldElectronicSignaturePersonal;
        } else {
            ElectronicSignaturePersonal electronicSignaturePersonal = new ElectronicSignaturePersonal();
            electronicSignaturePersonal.setName(acceptancePersonInfo.getName());
            electronicSignaturePersonal.setMobile(acceptancePersonInfo.getMobile());
            electronicSignaturePersonal.setAuthStatus(0);
            electronicSignaturePersonalService.save(electronicSignaturePersonal);
            //Update用来生成链接
            electronicSignaturePersonalService.updateInfo(electronicSignaturePersonal);
            signaturePersonal = electronicSignaturePersonal;
        }
        //电子签信息
        CAcceptanceSignConfirmation acceptanceSignConfirmation = lambdaQuery()
                .eq(CAcceptanceSignConfirmation::getcAcceptanceBasicInfoId, businessKey).one();
        if (acceptanceSignConfirmation == null) {
            acceptanceSignConfirmation = new CAcceptanceSignConfirmation();
            acceptanceSignConfirmation.setcAcceptanceBasicInfoId(businessKey);
            save(acceptanceSignConfirmation);
        }
        //电子签合同信息
        List<CAcceptanceSignConfirmationElectronicInfo> acceptanceSignConfirmationElectronicInfos =
                acceptanceSignConfirmationElectronicInfoService.lambdaQuery()
                        .eq(CAcceptanceSignConfirmationElectronicInfo::getcAcceptanceSignConfirmationId, acceptanceSignConfirmation.getId()).list();
        if (CollectionUtil.isEmpty(acceptanceSignConfirmationElectronicInfos)) {

            List<FileStorageDO> files = fileService.findByBusinessId(businessKey, FileTypeEnum.ACCEPTANCE_FILE.getCode());
            if (CollectionUtil.isNotEmpty(files)) {
                for (FileStorageDO file : files) {
                    CAcceptanceSignConfirmationElectronicInfo acceptanceSignConfirmationElectronicInfo = new CAcceptanceSignConfirmationElectronicInfo();
                    acceptanceSignConfirmationElectronicInfo.setcAcceptanceSignConfirmationId(acceptanceSignConfirmation.getId());
                    acceptanceSignConfirmationElectronicInfo.setSignStatus(0);
                    acceptanceSignConfirmationElectronicInfo.setFileId(file.getId());
                    acceptanceSignConfirmationElectronicInfo.setContractName(file.getOriginalName().replace(file.getType(), ""));
                    acceptanceSignConfirmationElectronicInfo.setElectronicSignaturePersonalId(signaturePersonal.getId());
                    acceptanceSignConfirmationElectronicInfoService.save(acceptanceSignConfirmationElectronicInfo);
                }
            } else {
                throw new ValidatorException(CodeUtil.FAIL, "未获取到下游验收单！");
            }
        }
        //电子签合同信息
        acceptanceSignConfirmationElectronicInfos = acceptanceSignConfirmationElectronicInfoService.lambdaQuery()
                .eq(CAcceptanceSignConfirmationElectronicInfo::getcAcceptanceSignConfirmationId, acceptanceSignConfirmation.getId()).list();
        Long electronicSignaturePersonalId = acceptanceSignConfirmationElectronicInfos.get(0).getElectronicSignaturePersonalId();
        if (!electronicSignaturePersonalId.equals(signaturePersonal.getId())) {
            acceptanceSignConfirmationElectronicInfos.forEach(r -> {
                r.setElectronicSignaturePersonalId(signaturePersonal.getId());
                r.setSignStatus(0);
                acceptanceSignConfirmationElectronicInfoService.updateById(r);
            });
            acceptanceSignConfirmation.setContractLink("");
            acceptanceSignConfirmation.setShortContractLink("");
            updateById(acceptanceSignConfirmation);
        }
        if (signaturePersonal.getAuthStatus().equals(1)) {
            if (StringUtil.isEmpty(acceptanceSignConfirmation.getContractLink())) {
                List<FddSignData> fddSignDataList = new ArrayList();
                for (CAcceptanceSignConfirmationElectronicInfo acceptanceSignConfirmationElectronicInfo : acceptanceSignConfirmationElectronicInfos) {
                    //将文件转换为PDF在上传法大大
                    FileStorageDO fileStorage = fileService.getById(acceptanceSignConfirmationElectronicInfo.getFileId());
                    File file = new File(fileStorage.getAbsolutePath());
                    String fileType = fileStorage.getType();
                    String newPath = file.getAbsolutePath().replace(fileType, ".pdf");
                    File pdfFile;
                    //只支持图片和excel转换
                    if (fileType.equals(".pdf")) {
                        pdfFile = file;
                    } else if (fileType.equals(".xlsx") || fileType.equals(".xls")) {
                        pdfFile = OfficeConverterUtil.office2Pdf(file.getAbsolutePath(), newPath);
                    } else if (fileType.equals(".jpg") || fileType.equals(".png") || fileType.equals(".jpeg") || fileType.equals(".bmp")) {
                        PdfUtil.convert(file.getAbsolutePath(), newPath);
                        pdfFile = new File(newPath);
                    } else {
                        throw new ValidatorException(CodeUtil.FAIL, "文件类型错误！");
                    }
                    Date date = new Date(); // 当前日期和时间
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
                    String chineseFormat = sdf.format(date);
                    String mark = "收料人："+signaturePersonal.getName()+"，手机号："+signaturePersonal.getMobile()+"于"+chineseFormat+" 收料确认";
                    PdfReader pdfReader = null;
                    File waterMarkFile = null;
                    try {
                    String markPath = pdfFile.getAbsolutePath().substring(0,pdfFile.getAbsolutePath().lastIndexOf(File.separator))+File.separator+UUID.randomUUID().toString()+".pdf";
                    PdfUtil.addPDFWaterMark(pdfFile.getAbsolutePath(),markPath,mark);
                    waterMarkFile =  new File(markPath);
                    pdfReader = new PdfReader(new FileInputStream(waterMarkFile));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    int pages = pdfReader.getNumberOfPages();
                    //上传合同
                    String contractId = UUID.randomUUID().toString().trim().replaceAll("-", "").toUpperCase();
                    String docTitle = fileStorage.getOriginalName();
                    String transactionId = UUID.randomUUID().toString().trim().replaceAll("-", "").toUpperCase();
                    ElectronicSignatureUtil.uploadContract(contractId, docTitle, waterMarkFile);
                    //批量手动签署
                    FddSignData fddSignData = new FddSignData();
                    fddSignData.setContractId(contractId);
                    fddSignData.setContractType("settlement");
                    String page = String.valueOf(pages - 1);
                    fddSignData.setSearchLocation(page);
                    fddSignData.setTransactionId(transactionId);
                    fddSignDataList.add(fddSignData);

                    acceptanceSignConfirmationElectronicInfo.setContractId(contractId);
                    acceptanceSignConfirmationElectronicInfo.setTransactionId(transactionId);
                    acceptanceSignConfirmationElectronicInfoService.updateById(acceptanceSignConfirmationElectronicInfo);
                }
                String contractLink = ElectronicSignatureUtil.batchSignUrlSearchLocation(signaturePersonal.getFddCustomerId(), fddSignDataList, "验收单签署确认批量签署");
                //合同链接
                String shortUrl = ElectronicSignatureUtil.shortUrl(null, contractLink);
                acceptanceSignConfirmation.setContractLink(contractLink);
                acceptanceSignConfirmation.setShortContractLink(shortUrl);
                acceptanceSignConfirmation.setShortContractLinkCreate(new Date());
                updateById(acceptanceSignConfirmation);
            }
        }
        acceptanceSignConfirmation.setSignConfirmationElectronicInfos(acceptanceSignConfirmationElectronicInfos);
        acceptanceSignConfirmation.setElectronicSignaturePersonal(signaturePersonal);
//        //钢小二货物
//        List<CAcceptanceGoodsInfo> list = acceptanceGoodsInfoService.lambdaQuery()
//            .eq(CAcceptanceGoodsInfo::getcAcceptanceBasicInfoId, businessKey).list();

//        代码删除
//        List<CAcceptanceGoodsInfo> acceptanceGoodsInfoList = new ArrayList<>();
//        if (acceptanceBasicInfo.getSteelWaiter().equals(1)) {
//            List<SellBill> list = sellBillService.lambdaQuery().eq(SellBill::getAcceptanceBasicInfoId, businessKey).list();
//            if (CollectionUtil.isNotEmpty(list)) {
//                for (SellBill sellBill : list) {
//                    List<SellBillItem> sellBillItems = sellBillItemService.lambdaQuery().eq(SellBillItem::getSellBillId, sellBill.getId()).list();
//                    if (CollectionUtil.isNotEmpty(sellBillItems)) {
//                        for (SellBillItem sellBillItem : sellBillItems) {
//                            CAcceptanceGoodsInfo acceptanceGoodsInfo = new CAcceptanceGoodsInfo();
//                            acceptanceGoodsInfo.setGoodsName(sellBillItem.getProductName());
//                            acceptanceGoodsInfo.setGoodsMaterial(sellBillItem.getMaterialName());
//                            acceptanceGoodsInfo.setGoodsType(sellBillItem.getSpecificationName());
//                            acceptanceGoodsInfo.setGoodsFactory(sellBillItem.getOriginName());
//                            acceptanceGoodsInfo.setGoodsUnit(sellBillItem.getUnitText());
//                            acceptanceGoodsInfo.setGoodsQuantity(sellBillItem.getAuditQuantity());
//                            acceptanceGoodsInfo.setSalesPrice(sellBillItem.getAuditPrice());
//                            acceptanceGoodsInfo.setAcceptanceDate(sellBill.getReceiptDate());
//                            acceptanceGoodsInfoList.add(acceptanceGoodsInfo);
//                        }
//                    }
//                }
//            }
//        }
//        acceptanceSignConfirmation.setAcceptanceGoodInfos(list);
        return acceptanceSignConfirmation;
    }

}
