package com.yh.saas.plugin.yiliangyiyun.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.winsea.svc.base.base.entity.CommonStaff;
import com.winsea.svc.base.base.service.ICommonStaffService;
import com.winsea.svc.base.security.util.AuthSecurityUtils;
import com.yh.saas.plugin.yiliangyiyun.entity.PaymentManagement;
import lombok.Getter;
import org.apache.http.entity.ContentType;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class XmlUtil implements InitializingBean {
    @Getter
    @Value("${oss.endpoint.internal:}")
    private String baseUrl;
    @Getter
    @Value("${oss.bucket.name:}")
    private String bucket;
    @Autowired
    private OSSClient ossClient;
    @Getter
    @Value("${oss.endpoint.default:}")
    private String endpoint;
    @Autowired
    private ICommonStaffService staffService;

    private String host;

    @Override
    public void afterPropertiesSet() throws Exception {
        host = "http://" + bucket + "." + endpoint;
    }

    public String xmlChangeString(String fileName) {
        try {
            SAXReader saxReader = new SAXReader();//新建一个解析类
            Document tempDocument = saxReader.read(cn.hutool.core.util.XmlUtil.class.getClassLoader().getResourceAsStream(fileName));//读入一个文件
            return tempDocument.asXML();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return null;
    }

    //将字符串string类型转换成xml文件
    public String strChangeXML(String str, String name) throws IOException {
        SAXReader saxReader = new SAXReader();
        Document document;
        try {
            document = DocumentHelper.parseText(str);
            document.setXMLEncoding("gb2312");
            document.asXML();
//            document = saxReader.read(new ByteArrayInputStream(str.getBytes("UTF-8")));
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("gb2312");
//            File file = new File(new String(("templates" + File.separator + name + ".xml").getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8));
//            if (!file.exists()) {
//                boolean flag = file.mkdirs();
//            }
            Path path = FileSystems.getDefault().getPath(new File("templates" + File.separator + name + ".xml").getAbsoluteFile().getPath());
            File file = new File(String.valueOf(path));
            /** 将document中的内容写入文件中 */
            OutputStream out = new FileOutputStream(file);
            Writer wr = new OutputStreamWriter(out,"gb2312");
            XMLWriter writer = new XMLWriter(wr, format);
            FileInputStream fileInputStream = new FileInputStream(String.valueOf(path));
            writer.write(document);
            writer.close();
            out.close();
            wr.close();
            MultipartFile multipartFile = new MockMultipartFile(ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
            String returnFile = upload(multipartFile, name);
            file.delete();
            return returnFile;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "NG";
    }
    //将字符串string类型转换成xml文件
    public String strChangeXMLs(String str, String name) throws IOException {
        SAXReader saxReader = new SAXReader();
        Document document;
        try {
            document = DocumentHelper.parseText(str);
            document.setXMLEncoding("GBK");
            document.asXML();
//            document = saxReader.read(new ByteArrayInputStream(str.getBytes("UTF-8")));
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("GBK");
//            File file = new File(new String(("templates" + File.separator + name + ".xml").getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8));
//            if (!file.exists()) {
//                boolean flag = file.mkdirs();
//            }
            Path path = FileSystems.getDefault().getPath(new File("templates" + File.separator + name + ".xml").getAbsoluteFile().getPath());
            File file = new File(String.valueOf(path));
            /** 将document中的内容写入文件中 */
            OutputStream out = new FileOutputStream(file);
            Writer wr = new OutputStreamWriter(out,"GBK");
            XMLWriter writer = new XMLWriter(wr, format);
            FileInputStream fileInputStream = new FileInputStream(String.valueOf(path));
            writer.write(document);
            writer.close();
            out.close();
            wr.close();
            MultipartFile multipartFile = new MockMultipartFile(ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
            String returnFile = upload(multipartFile, name);
            file.delete();
            return returnFile;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "NG";
    }

    public String readXml(PaymentManagement paymentManagement) {

        String regEx = "[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(paymentManagement.getPaymentNo());
        String number = m.replaceAll("").trim();
        Float weight = paymentManagement.getNetWeight();
        Double as = paymentManagement.getAmountIngPayable()/weight * 100;
        String goodsName = paymentManagement.getGoodsName();
        if(paymentManagement.getGoodsName().equals("玉米（潮粮）")){
//            paymentManagement.setGoodsName("玉米");
            goodsName = "玉米";
            weight = paymentManagement.getPureWeight();
        }
        if(paymentManagement.getPureWeight() == null){
            paymentManagement.setPureWeight(paymentManagement.getNetWeight());
        }
        String s = "<?xml version=\"1.0\" encoding=\"GBK\"?>\n" +
                "\n" +
                "<Kp>\n" +
                "\n" +
                "<Version>2.0</Version>\n" +
                "\n" +
                "\n" +
                "<Fpxx>\n" +
                "\n" +
                "<Zsl>1</Zsl>\n" +
                "\n" +
                "\n" +
                "<Fpsj>\n" +
                "\n" +
                "\n" +
                "<Fp>\n" +
                "\n" +
                "<Djh>" + number.substring(4) + "</Djh>\n" +
                "\n" +
                "<Gfmc>" + paymentManagement.getIdentityAuthenticationInfo().getCustomerName() + "</Gfmc>\n" +
                "\n" +
                "<Gfsh>" + paymentManagement.getIdentityAuthenticationInfo().getCustomerNumberCard() + "</Gfsh>\n" +
                "\n" +
                "<Gfyhzh>" + paymentManagement.getIdentityAuthenticationInfo().getBankDeposit()+paymentManagement.getIdentityAuthenticationInfo().getBankCard() + "</Gfyhzh>\n" +
                "\n" +
                "<Gfdzdh>" + paymentManagement.getIdentityAuthenticationInfo().getCompAddress() + "</Gfdzdh>\n" +
                "\n" +
                "<Bz>车号:" + paymentManagement.getCarNo() + "毛:" +
                paymentManagement.getGrossWeight()==null?"":paymentManagement.getGrossWeight()
                + " 皮:" +
                paymentManagement.getTare()==null?"":paymentManagement.getTare()
                + " 净:" + paymentManagement.getNetWeight() + " 纯:" + paymentManagement.getPureWeight() + " 应付:" + paymentManagement.getAmountIngPayable() + " 单号:" + m.replaceAll("").trim() + " ,★☆性质:贸易粮 形态:玉米堆</Bz>\n" +
                "\n" +
                "<Fhr/>\n" +
                "\n" +
                "<Skr/>\n" +
                "\n" +
                "<Spbmbbh>10.0</Spbmbbh>\n" +
                "\n" +
                "<Hsbz>0</Hsbz>\n" +
                "\n" +
                "\n" +
                "<Spxx>\n" +
                "\n" +
                "\n" +
                "-<Sph>\n" +
                "\n" +
                "<Xh>1</Xh>\n" +
                "\n" +
                "<Spmc>" + goodsName + "</Spmc>\n" +
                "\n" +
                "<Ggxh>" + paymentManagement.getGrade() + "</Ggxh>\n" +
                "\n" +
                "<Jldw>公斤</Jldw>\n" +
                "\n" +
                "<Spbm>1010101030000000000</Spbm>\n" +
                "\n" +
                "<Qyspbm/>\n" +
                "\n" +
                "<Syyhzcbz>0</Syyhzcbz>\n" +
                "\n" +
                "<Lslbz>1</Lslbz>\n" +
                "\n" +
                "<Yhzcsm/>\n" +
                "\n" +
                "<Dj>"+paymentManagement.getAmountIngPayable()/weight+"</Dj>\n" +
                "\n" +
                "<Sl>" + weight + "</Sl>\n" +
                "\n" +
                "<Je>" + paymentManagement.getAmountIngPayable() + "</Je>\n" +
                "\n" +
                "<Kce>0</Kce>\n" +
                "\n" +
                "<Slv>0</Slv>\n" +
                "\n" +
                "<Se>0</Se>\n" +
                "\n" +
                "</Sph>\n" +
                "\n" +
                "</Spxx>\n" +
                "\n" +
                "</Fp>\n" +
                "\n" +
                "</Fpsj>\n" +
                "\n" +
                "</Fpxx>\n" +
                "\n" +
                "</Kp>";
        try {
            String returnFile = strChangeXML(s, number.substring(4) + paymentManagement.getIdentityAuthenticationInfo().getCustomerName() + paymentManagement.getAmountIngPayable());
            return returnFile;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "NG";
    }


    public String readXmls(PaymentManagement paymentManagement) {

        //获取用户名称
        CommonStaff commonStaff = staffService.getInfo(AuthSecurityUtils.getCurrentUserId());

        String regEx = "[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(paymentManagement.getPaymentNo());
        String number = m.replaceAll("").trim();
        Float weight = paymentManagement.getNetWeight();
        Double as = paymentManagement.getAmountIngPayable()/weight * 100;
        String goodsName = paymentManagement.getGoodsName();
        if(paymentManagement.getGoodsName().equals("玉米（潮粮）")){
//            paymentManagement.setGoodsName("玉米");
            goodsName = "玉米";
            weight = paymentManagement.getPureWeight();
        }
        if(paymentManagement.getPureWeight() == null){
            paymentManagement.setPureWeight(paymentManagement.getNetWeight());
        }
        String s = "<?xml version=\"1.0\" encoding=\"GBK\"?>\n" +
                "\n" +
                "<Kp>\n" +
                "\n" +
                "<Version>2.0</Version>\n" +
                "\n" +
                "\n" +
                "<Fpxx>\n" +
                "\n" +
                "<Zsl>1</Zsl>\n" +
                "\n" +
                "\n" +
                "<Fpsj>\n" +
                "\n" +
                "\n" +
                "<Fp>\n" +
                "\n" +
                "<Djh>" + number.substring(4) + "</Djh>\n" +
                "\n" +
                "<Gfmc>" + paymentManagement.getIdentityAuthenticationInfo().getCustomerName() + "</Gfmc>\n" +
                "\n" +
                "<Gfsh>" + paymentManagement.getIdentityAuthenticationInfo().getCustomerNumberCard() + "</Gfsh>\n" +
                "\n" +
                "<Gfyhzh>" + paymentManagement.getIdentityAuthenticationInfo().getBankDeposit()+paymentManagement.getIdentityAuthenticationInfo().getBankCard() + "</Gfyhzh>\n" +
                "\n" +
                "<Gfdzdh>" + paymentManagement.getIdentityAuthenticationInfo().getCompAddress() + "</Gfdzdh>\n" +
                "\n" +
                "<Bz>车号:" + paymentManagement.getCarNo() + "毛:" +
                paymentManagement.getGrossWeightStr()
                + " 皮:" +
                paymentManagement.getTareStr()
                + " 净:" + paymentManagement.getNetWeight() + " 纯:" + paymentManagement.getPureWeight() + " 应付:" + paymentManagement.getAmountIngPayable() + " 单号:" + m.replaceAll("").trim() + " ,★☆性质:贸易粮 形态:玉米堆</Bz>\n" +
                "\n" +
                "<Fhr/>\n" +
                "\n" +
                "<Skr/>\n" +
                "\n" +
                "<Spbmbbh>40.0</Spbmbbh>\n" +
                "\n" +
                "<Hsbz>0</Hsbz>\n" +
                "\n" +
                "\n" +
                "<Sgbz>02</Sgbz>\n" +
                "\n" +
                "<Spxx>\n" +
                "\n" +
                "\n" +
                "<Sph>\n" +
                "\n" +
                "<Xh>1</Xh>\n" +
                "\n" +
                "<Spmc>" + goodsName + "</Spmc>\n" +
                "\n" +
                "<Ggxh>" + paymentManagement.getGrade() + "</Ggxh>\n" +
                "\n" +
                "<Jldw>公斤</Jldw>\n" +
                "\n" +
                "<Spbm>1010101030000000000</Spbm>\n" +
                "\n" +
                "<Qyspbm/>\n" +
                "\n" +
                "<Syyhzcbz>0</Syyhzcbz>\n" +
                "\n" +
                "<Lslbz>1</Lslbz>\n" +
                "\n" +
                "<Yhzcsm/>\n" +
                "\n" +
                "<Dj>"+paymentManagement.getAmountIngPayable()/weight+"</Dj>\n" +
                "\n" +
                "<Sl>" + weight + "</Sl>\n" +
                "\n" +
                "<Je>" + paymentManagement.getAmountIngPayable() + "</Je>\n" +
                "\n" +
                "<Slv>0</Slv>\n" +
                "\n" +
                "<Se>0</Se>\n" +
                "\n" +
                "</Sph>\n" +
                "\n" +
                "</Spxx>\n" +
                "\n" +
                "</Fp>\n" +
                "\n" +
                "</Fpsj>\n" +
                "\n" +
                "</Fpxx>\n" +
                "\n" +
                "</Kp>";
        try {
            String returnFile = strChangeXMLs(s, number.substring(4) + paymentManagement.getIdentityAuthenticationInfo().getCustomerName() + paymentManagement.getAmountIngPayable());
            return returnFile;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "NG";
    }

    public String readsXml(PaymentManagement paymentManagement) {

        String regEx = "[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(paymentManagement.getPaymentNo());
        String number = m.replaceAll("").trim();
        Float weight = paymentManagement.getPureWeight();
        Double as = paymentManagement.getAmountIngPayable()/weight * 100;
        String goodsName = paymentManagement.getGoodsName();
        if(paymentManagement.getGoodsName().equals("玉米（潮粮）")){
//            paymentManagement.setGoodsName("玉米");
            goodsName = "玉米";
            weight = paymentManagement.getPureWeight();
        }
        if(paymentManagement.getPureWeight() == null){
            paymentManagement.setPureWeight(paymentManagement.getNetWeight());
        }
        String s = "<?xml version=\"1.0\" encoding=\"GBK\"?>\n" +
                "\n" +
                "<Kp>\n" +
                "\n" +
                "<Version>2.0</Version>\n" +
                "\n" +
                "\n" +
                "<Fpxx>\n" +
                "\n" +
                "<Zsl>1</Zsl>\n" +
                "\n" +
                "\n" +
                "<Fpsj>\n" +
                "\n" +
                "\n" +
                "<Fp>\n" +
                "\n" +
                "<Djh>" + paymentManagement.getOddNumbers() + "</Djh>\n" +
                "\n" +
                "<Gfmc>" + paymentManagement.getIdentityAuthenticationInfo().getCustomerName() + "</Gfmc>\n" +
                "\n" +
                "<Gfsh>" + paymentManagement.getIdentityAuthenticationInfo().getCustomerNumberCard() + "</Gfsh>\n" +
                "\n" +
                "<Gfyhzh>" + paymentManagement.getIdentityAuthenticationInfo().getBankDeposit()+paymentManagement.getIdentityAuthenticationInfo().getBankCard() + "</Gfyhzh>\n" +
                "\n" +
                "<Gfdzdh>" + paymentManagement.getIdentityAuthenticationInfo().getCompAddress() + "</Gfdzdh>\n" +
                "\n" +
                "<Bz>" + paymentManagement.getRemarkss() + "</Bz>\n" +
                "\n" +
                "<Fhr/>\n" +
                "\n" +
                "<Skr/>\n" +
                "\n" +
                "<Spbmbbh>40.0</Spbmbbh>\n" +
                "\n" +
                "<Hsbz>0</Hsbz>\n" +
                "\n" +
                "\n" +
                "<Sgbz>02</Sgbz>\n" +
                "\n" +
                "<Spxx>\n" +
                "\n" +
                "\n" +
                "<Sph>\n" +
                "\n" +
                "<Xh>1</Xh>\n" +
                "\n" +
                "<Spmc>" + goodsName + "</Spmc>\n" +
                "\n" +
                "<Ggxh>" + paymentManagement.getGrade() + "</Ggxh>\n" +
                "\n" +
                "<Jldw>公斤</Jldw>\n" +
                "\n" +
                "<Spbm>1010101030000000000</Spbm>\n" +
                "\n" +
                "<Qyspbm/>\n" +
                "\n" +
                "<Syyhzcbz>0</Syyhzcbz>\n" +
                "\n" +
                "<Lslbz>1</Lslbz>\n" +
                "\n" +
                "<Yhzcsm/>\n" +
                "\n" +
                "<Dj>"+ paymentManagement.getTidalGrainPrice() +"</Dj>\n" +
                "\n" +
                "<Sl>" + weight + "</Sl>\n" +
                "\n" +
                "<Je>" + paymentManagement.getAmountIngPayable() + "</Je>\n" +
                "\n" +
                "<Slv>0</Slv>\n" +
                "\n" +
                "<Se>0</Se>\n" +
                "\n" +
                "</Sph>\n" +
                "\n" +
                "</Spxx>\n" +
                "\n" +
                "</Fp>\n" +
                "\n" +
                "</Fpsj>\n" +
                "\n" +
                "</Fpxx>\n" +
                "\n" +
                "</Kp>";
        try {
            String returnFile = strChangeXMLs(s, paymentManagement.getOddNumbers() + paymentManagement.getIdentityAuthenticationInfo().getCustomerName() + paymentManagement.getAmountIngPayable());
            return returnFile;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "NG";
    }



//    public static void main(String args[]){
//        String s ="<?xml version=\"1.0\" encoding=\"GBK\"?>\n" +
//                "\n" +
//                "<Kp>\n" +
//                "\n" +
//                "<Version>2.0</Version>\n" +
//                "\n" +
//                "\n" +
//                "<Fpxx>\n" +
//                "\n" +
//                "<Zsl>1</Zsl>\n" +
//                "\n" +
//                "\n" +
//                "<Fpsj>\n" +
//                "\n" +
//                "\n" +
//                "<Fp>\n" +
//                "\n" +
//                "<Djh>23003656</Djh>\n" +
//                "\n" +
//                "<Gfmc>12</Gfmc>\n" +
//                "\n" +
//                "<Gfsh>34</Gfsh>\n" +
//                "\n" +
//                "<Gfyhzh>56</Gfyhzh>\n" +
//                "\n" +
//                "<Gfdzdh>九台镇南戈庄村186号</Gfdzdh>\n" +
//                "\n" +
//                "<Bz>车号:鲁VU2873毛:15140 皮:6120 净:9020 应付:14017.08 整晒费:0 实付:14017.08 性质:贸易粮 单号:23003656 ,★☆性质:贸易粮 形态:玉米堆</Bz>\n" +
//                "\n" +
//                "<Fhr/>\n" +
//                "\n" +
//                "<Skr/>\n" +
//                "\n" +
//                "<Spbmbbh>10.0</Spbmbbh>\n" +
//                "\n" +
//                "<Hsbz>0</Hsbz>\n" +
//                "\n" +
//                "\n" +
//                "<Spxx>\n" +
//                "\n" +
//                "\n" +
//                "-<Sph>\n" +
//                "\n" +
//                "<Xh>1</Xh>\n" +
//                "\n" +
//                "<Spmc>玉米</Spmc>\n" +
//                "\n" +
//                "<Ggxh>3等</Ggxh>\n" +
//                "\n" +
//                "<Jldw>公斤</Jldw>\n" +
//                "\n" +
//                "<Spbm>1010101030000000000</Spbm>\n" +
//                "\n" +
//                "<Qyspbm/>\n" +
//                "\n" +
//                "<Syyhzcbz>0</Syyhzcbz>\n" +
//                "\n" +
//                "<Lslbz>1</Lslbz>\n" +
//                "\n" +
//                "<Yhzcsm/>\n" +
//                "\n" +
//                "<Dj>1.55400000</Dj>\n" +
//                "\n" +
//                "<Sl>9020</Sl>\n" +
//                "\n" +
//                "<Je>14017.08</Je>\n" +
//                "\n" +
//                "<Kce>0</Kce>\n" +
//                "\n" +
//                "<Slv>0</Slv>\n" +
//                "\n" +
//                "<Se>0</Se>\n" +
//                "\n" +
//                "</Sph>\n" +
//                "\n" +
//                "</Spxx>\n" +
//                "\n" +
//                "</Fp>\n" +
//                "\n" +
//                "</Fpsj>\n" +
//                "\n" +
//                "</Fpxx>\n" +
//                "\n" +
//                "</Kp>";
//        try{
//            strChangeXML(s,"2223");
//        }catch (IOException e) {
//            e.printStackTrace();
//        }
//
//    }


    /**
     * 后台通过服务器间接传文件
     *
     * @param file
     * @return
     * @throws IOException
     */
    public String upload(MultipartFile file, String name) throws IOException {
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(file.getSize());
        objectMetadata.setContentType(file.getContentType());
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, "FP/" + name + ".xml", file.getInputStream(), objectMetadata);
        ossClient.putObject(putObjectRequest);
        return baseUrl + "FP/" + name + ".xml";
    }
}
