package com.dgtly.wxportal.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.dgtly.system.domain.CustomersExt;
import com.dgtly.wxportal.domain.EReceivingNote;
import com.dgtly.system.domain.SysUser;
import com.dgtly.system.service.ICustomersExtService;
import com.dgtly.wxportal.domain.ESignUpPDFModal;
import com.dgtly.wxportal.domain.OrderFile;
import com.dgtly.wxportal.domain.OrderSelfNote;
import com.dgtly.wxportal.service.IEReceivingNoteService;
import com.dgtly.system.service.ISysUserService;
import com.dgtly.wxportal.config.ESignConfig;
import com.dgtly.wxportal.service.ESignService;
import com.dgtly.wxportal.utils.ESign.ESignHttpUtil;
import com.dgtly.wxportal.utils.ESign.ESignUploadUtil;
import com.dgtly.wxportal.utils.ESign.ESignUrl;
import com.dgtly.wxportal.utils.pdf.PDFSelfUtil;
import com.dgtly.wxportal.utils.pdf.PDFUtil;
import com.dgtly.wxportal.utils.pdf.Watermark;
import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ZhangDing
 * @version 1.0
 * @descption: TODO
 * @company 神州数码通用软件（洛阳）有限公司
 * @copyright (c) 2019 LuoYang DGT Co'Ltd Inc. All rights reserved.
 * @date 2020-10-10 11:27
 * @since JDK1.8
 */
@Service
public class ESignServiceImpl implements ESignService {


    private static final Logger log = LoggerFactory.getLogger(ESignServiceImpl.class);

    @Autowired
    private ESignHttpUtil eSignHttpUtil;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ICustomersExtService customersExtService;
    @Autowired
    private ESignConfig eSignConfig;
    @Autowired
    private IEReceivingNoteService iMetaHanaSalesOrderService;

    @Override
    public ESignUpPDFModal upload(String orderId,String tmsShipNumber,String customerCode,String customerName,String userName) {

        EReceivingNote receivingNote = iMetaHanaSalesOrderService.selectEReceivingNote(orderId,tmsShipNumber,customerCode,customerName,userName);
        Map<String,Object> map = new HashMap<>();
        //创建PDF
        ESignUpPDFModal fileModal = creatPdf(receivingNote);
        String md5 = ESignUploadUtil.getStringContentMD5(fileModal.getFilePath());
        String contentTtpe = "application/pdf";
        int fileLength = ESignUploadUtil.getFileSize(fileModal.getFilePath());
        //根据文件获取上传路径
        JSONObject urlData =  getUpUrl(fileModal.getFilePath(),md5,contentTtpe,fileLength).getJSONObject("data");
        //文件id
        String fileId = urlData.getString("fileId");
        //文件上传路径
        String uploadUrl = urlData.getString("uploadUrl");
        //上传文件
        String res = eSignHttpUtil.upLoadFile(uploadUrl,fileModal.getFilePath(),md5,contentTtpe,fileLength);
        fileModal.setFileId(fileId);
        return fileModal;
    }

    @Override
    public ESignUpPDFModal uploadDriver(OrderFile orderFile) {

        OrderSelfNote receivingNote =new OrderSelfNote();
        receivingNote.setBeentrustName(orderFile.getBeentrustName());
        receivingNote.setOrderCreationTime(orderFile.getRun_time());
        receivingNote.setbId(orderFile.getbId());
        receivingNote.setCarNumber(orderFile.getCarNumber());
        receivingNote.setDeliveryNumber(orderFile.getDeliveryNumber());
        receivingNote.setEntrustName(orderFile.getEntrustName());
        receivingNote.setBelongTo(orderFile.getChainsCode());
        receivingNote.setPhone(orderFile.getPhone());
        Map<String,Object> map = new HashMap<>();
        //创建PDF
        ESignUpPDFModal fileModal = creatDriverPdf(receivingNote);
        String md5 = ESignUploadUtil.getStringContentMD5(fileModal.getFilePath());
        String contentTtpe = "application/pdf";
        int fileLength = ESignUploadUtil.getFileSize(fileModal.getFilePath());
        //根据文件获取上传路径
        JSONObject urlData =  getUpUrl(fileModal.getFilePath(),md5,contentTtpe,fileLength).getJSONObject("data");
        //文件id
        String fileId = urlData.getString("fileId");
        //文件上传路径
        String uploadUrl = urlData.getString("uploadUrl");
        //上传文件
        String res = eSignHttpUtil.upLoadFile(uploadUrl,fileModal.getFilePath(),md5,contentTtpe,fileLength);
        fileModal.setFileId(fileId);
        return fileModal;
    }

    /**
     * @param orderFile
     * @description: 委托签署pdf
     * @param: [orderFile]
     * @return: com.dgtly.wxportal.domain.ESignUpPDFModal
     * @author: njs
     * @date: 2023/3/22 17:42
     */
    @Override
    public ESignUpPDFModal uploadEmpowerByAuth(OrderFile orderFile) {
        OrderSelfNote receivingNote =new OrderSelfNote();
        // 受托人
        receivingNote.setBeentrustName(orderFile.getBeentrustName());
        //委托人
        receivingNote.setEntrustName(orderFile.getEntrustName());
        receivingNote.setBelongTo(orderFile.getChainsCode());
        receivingNote.setCustomerName(orderFile.getChainsName());
        receivingNote.setAuthName(orderFile.getAuthName());
        receivingNote.setBeentrustPost(orderFile.getBeentrustPost());
        receivingNote.setEntrustPost(orderFile.getEntrustPost());
        Map<String,Object> map = new HashMap<>();
        //创建PDF
        ESignUpPDFModal fileModal = creatEmpowerByAuthPdf(receivingNote);
        String md5 = ESignUploadUtil.getStringContentMD5(fileModal.getFilePath());
        String contentTtpe = "application/pdf";
        int fileLength = ESignUploadUtil.getFileSize(fileModal.getFilePath());
        //根据文件获取上传路径
        JSONObject urlData =  getUpUrl(fileModal.getFilePath(),md5,contentTtpe,fileLength).getJSONObject("data");
        //文件id
        String fileId = urlData.getString("fileId");
        //文件上传路径
        String uploadUrl = urlData.getString("uploadUrl");
        //上传文件
        String res = eSignHttpUtil.upLoadFile(uploadUrl,fileModal.getFilePath(),md5,contentTtpe,fileLength);
        fileModal.setFileId(fileId);
        return fileModal;
    }

    @Override
    public String verificationUser() {
        return null;
    }

    @Override
    public SysUser createPersonalAccount(SysUser user) {
        JSONObject json = new JSONObject();
        json.put("thirdPartyUserId",user.getLoginName());
//        json.put("name",user.getUserName());
        json.put("idType","CRED_PSN_CH_IDCARD");
//        json.put("idNumber",user.getIdNumber());
//        json.put("mobile",user.getPhonenumber());
//        json.put("email",user.getEmail());
        JSONObject resule = eSignHttpUtil.doPostGetJson(ESignUrl.CreatePersonalAccount,json);
        user.setAccountId(resule.getJSONObject("data").getString("accountId"));
        int isok = userService.insertPersonalAccount(user);
        if (isok>0){
            return user;
        }else {
            return null;
        }
    }

    @Override
    public CustomersExt createThirdParty(CustomersExt customersExt) {
        JSONObject json = new JSONObject();
        int isok = 1;
        json.put("thirdPartyUserId",customersExt.getChainsCode());
        json.put("creator",customersExt.getCreator());
//        json.put("name",customersExt.getCustomersName());
//        json.put("idType","CRED_ORG_USCC");
//        json.put("idNumber",customersExt.getIdNumber());
//        json.put("orgLegalIdNumber",customersExt.getOrgLegalidNumber());
//        json.put("orgLegalName",customersExt.getOrgLegalName());
        JSONObject resule = eSignHttpUtil.doPostGetJson(ESignUrl.CreateThirdParty,json);
        customersExt.setOrgId(resule.getJSONObject("data").getString("orgId"));
        isok = customersExtService.insertCustomersExt(customersExt);
        if (isok>0){
            return customersExt;
        }else {
            return null;
        }
    }

    @Override
    public int updatePersonalAccount(SysUser user) {
        JSONObject json = new JSONObject();
        int isok = 0;
        JSONObject resule = null;
        if (user.getUserName()!=null) {
            json.put("name", user.getUserName());
        }
        if (user.getIdNumber()!=null) {
            json.put("idNumber", user.getIdNumber());
        }
        if (user.getPhonenumber()!=null) {
            json.put("mobile", user.getPhonenumber());
        }
        if (user.getEmail()!=null) {
            json.put("email", user.getEmail());
        }
        if (user.getAccountId()!=null) {
            resule  = eSignHttpUtil.doPutGetJson(ESignUrl.updatePersonalAccount, json, user.getAccountId());
            if (resule.getInteger("code")==0){
                isok = 1;
            }
        }

        return isok;
    }

    @Override
    public int updateThirdParty(CustomersExt customersExt) {
        JSONObject json = new JSONObject();
        int isok = 0;
        JSONObject resule = null;
        if (customersExt.getCustomersName()!=null) {
            json.put("name", customersExt.getCustomersName());
        }
        if (customersExt.getIdNumber()!=null) {
            json.put("idNumber", customersExt.getIdNumber());
        }
        if (customersExt.getOrgLegalidNumber()!=null) {
            json.put("orgLegalIdNumber", customersExt.getOrgLegalidNumber());
        }
        if (customersExt.getOrgLegalName()!=null) {
            json.put("orgLegalName", customersExt.getOrgLegalName());
        }
        if (customersExt.getOrgId()!=null) {
            resule  = eSignHttpUtil.doPutGetJson(ESignUrl.updateThirdParty, json, customersExt.getOrgId());
            if (resule.getInteger("code")==0){
                isok = 1;
            }
        }
        return isok;
    }

    @Override
    public String getOrgIdByThirdId(String chainsCode) {
        JSONObject json =null;
        JSONObject jsonObject = eSignHttpUtil.doGetGetJson(ESignUrl.getOrgIdByThirdId, json, chainsCode);
        if (jsonObject!=null) {
            JSONObject result = (JSONObject) jsonObject.get("data");
            return result.get("orgId").toString();
        }else{
            return null;
        }
    }

    @Override
    public JSONObject delOrganizations(String orgId) {
        String url = eSignConfig.getUrl(ESignUrl.delOrgUrl, orgId);
        return JSONObject.parseObject(eSignHttpUtil.doDelete(url, new JSONObject().toJSONString()));
    }

    /**
     * @description: 根据loginName查询E签宝是否存在
     * @param: [loginName]
     * @return: java.lang.String
     * @author: qxm
     * @date: 2020/11/27 14:23
     */
    @Override
    public String getAccountIdByThirdId(String loginName) {
        JSONObject json =null;
        JSONObject jsonObject = eSignHttpUtil.doGetGetJson(ESignUrl.getAccountIdByThirdId, json, loginName);
        if (jsonObject!=null) {
            JSONObject result = (JSONObject)jsonObject.get("data");
            return result.get("accountId").toString();
        }else{
            return null;
        }
    }

    /**
     * 创建收货单pdf文件
     * @param
     * @return
     */
    private ESignUpPDFModal creatPdf(EReceivingNote receivingNote){
        ESignUpPDFModal res = new ESignUpPDFModal();
        String fileUrl = "";
        int size = 0;
        try {
            // 1.新建document对象
            Document document = new Document(PageSize.A4);// 建立一个Document对象

            // 2.建立一个书写器(Writer)与document对象关联
            String uploadPath = eSignConfig.getFileUrl() ;
            String filePath = uploadPath+File.separator+new Date().getTime()+"PDFDemo.pdf";
            File file = new File(filePath);
            if (!file.getParentFile().exists())
            {
                file.getParentFile().mkdirs();
            }
            fileUrl = filePath;
            file.createNewFile();

            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
//            writer.setPageEvent(new Watermark("我是水印"));// 水印
//                writer.setPageEvent(new MyHeaderFooter());// 页眉/页脚

            // 3.打开文档
            document.open();
            document.addTitle("随  身  邦  收  货  单");// 标题
            document.addAuthor("");// 作者
            document.addSubject("");// 主题
            document.addKeywords("");// 关键字
            document.addCreator("");// 创建者

            // 4.向文档中添加内容
            size = PDFUtil.generateEPDF(document,receivingNote, true);
            writer.flush();
            // 5.关闭文档
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("生成PDF出错：",e);
        }
        //计算宽高
        Float fosX = 500F;
        Float fosY = 700F;
//        for (int i =0;i<size;i++){
//           fosY = fosY-11f;
//        }
        res.setX(fosX);
        res.setY(fosY);
        res.setFilePath(fileUrl);
        return res;
    }
    /**
     * @description: 委托授权签署
     * @param: [receivingNote]
     * @return: com.dgtly.wxportal.domain.ESignUpPDFModal
     * @author: njs
     * @date: 2023/3/22 17:55
     */
    private ESignUpPDFModal creatEmpowerByAuthPdf(OrderSelfNote receivingNote){
        ESignUpPDFModal res = new ESignUpPDFModal();
        String fileUrl = "";
        int size = 0;
        try {
            // 1.新建document对象
            Document document = new Document(PageSize.A4);// 建立一个Document对象

            // 2.建立一个书写器(Writer)与document对象关联
            String uploadPath = eSignConfig.getFileUrl() ;
            String filePath = uploadPath+File.separator+new Date().getTime()+"PDFDemo.pdf";
            File file = new File(filePath);
            if (!file.getParentFile().exists())
            {
                file.getParentFile().mkdirs();
            }
            fileUrl = filePath;
            file.createNewFile();

            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
            // 3.打开文档
            document.open();
            document.addTitle("随  身  邦  授  权  委  托  书");// 标题
            document.addAuthor("");// 作者
            document.addSubject("");// 主题
            document.addKeywords("");// 关键字
            document.addCreator("");// 创建者

            // 4.向文档中添加内容
            size = PDFSelfUtil.generateByEmpowerByAuthPDF(document,receivingNote, false);
            writer.flush();
            // 5.关闭文档
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("生成PDF出错：",e);
        }
        //计算宽高
        Float fosX = 500F;
        Float fosY = 510F;
//        for (int i =0;i<size;i++){
//           fosY = fosY-11f;
//        }
        res.setX(fosX);
        res.setY(fosY);
        res.setFilePath(fileUrl);
        return res;
    }
    /**
     * 创建指派司机pdf文件
     * @param
     * @return
     */
    private ESignUpPDFModal creatDriverPdf(OrderSelfNote receivingNote){
        ESignUpPDFModal res = new ESignUpPDFModal();
        String fileUrl = "";
        int size = 0;
        try {
            // 1.新建document对象
            Document document = new Document(PageSize.A4);// 建立一个Document对象

            // 2.建立一个书写器(Writer)与document对象关联
            String uploadPath = eSignConfig.getFileUrl() ;
            String filePath = uploadPath+File.separator+new Date().getTime()+"PDFDemo.pdf";
            File file = new File(filePath);
            if (!file.getParentFile().exists())
            {
                file.getParentFile().mkdirs();
            }
            fileUrl = filePath;
            file.createNewFile();

            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
//            writer.setPageEvent(new Watermark("我是水印"));// 水印
//                writer.setPageEvent(new MyHeaderFooter());// 页眉/页脚

            // 3.打开文档
            document.open();
            document.addTitle("随  身  邦  授  权  司  机  货  单");// 标题
            document.addAuthor("");// 作者
            document.addSubject("");// 主题
            document.addKeywords("");// 关键字
            document.addCreator("");// 创建者

            // 4.向文档中添加内容
            size = PDFSelfUtil.generateEPDF(document,receivingNote, false);
            writer.flush();
            // 5.关闭文档
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("生成PDF出错：",e);
        }
        //计算宽高
        Float fosX = 430F;
        Float fosY = 465F;
//        for (int i =0;i<size;i++){
//           fosY = fosY-11f;
//        }
        res.setX(fosX);
        res.setY(fosY);
        //第二个盖章位置
        Float fosX2 = 100F;
        Float fosY2 = 400F;
        res.setX2(fosX2);
        res.setY2(fosY2);
        res.setFilePath(fileUrl);
        return res;
    }


    /**
     * 获取文件上传路径
     * @param filePath
     * @return
     */
    private JSONObject getUpUrl(String filePath,String contentMd5,String contentType,int fileLength){
        File file = new File(filePath);
        String fileName = file.getName();
        JSONObject json = new JSONObject();
        json.put("contentMd5", contentMd5);
        json.put("contentType",contentType);
        json.put("convert2Pdf",false);
        json.put("fileName",fileName);
        json.put("fileSize",fileLength);
        JSONObject result=  eSignHttpUtil.doPostGetJson(ESignUrl.uploadCreateFile,json);
        return result;
    }

}
