package com.hzya.frame.bip.v3.v2207.dps.task;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hzya.frame.bip.v3.v2207.dps.service.IPayMentService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.util.HashMap;


@EnableScheduling
@Component
public class ElectronicTask {
    static Logger logger= LoggerFactory.getLogger(ElectronicTask.class);

    @Resource
    private IPayMentService payMentService;
    //@Resource
    //private ISeeYonDao seeYonDao;
    //@Resource
    //private ICtpAttachmentDao ctpAttachmentDao;


    //@Scheduled(cron = "0 20 10 * * ?")
    //public void sendElectronicToCFS() {
    //    logger.info("CFS电子回单共享开始执行---------->");
    //    try {
    //        String token = payMentService.sendCFSToken("admin", "aHRzejg4OA==");
    //        if(null!=token) {
    //            List<SeeyonEntity> seeyonEntities = seeYonDao.selectOAListByTypeformmain_0327(new SeeyonEntity());
    //            if (seeyonEntities != null && seeyonEntities.size() > 0) {
    //                for (SeeyonEntity seeyonEntity : seeyonEntities) {
    //                    String bankAcc = seeyonEntity.getField0137();//付款账号
    //                    //String bankAcc="03005389347";
    //                    String erpVoucherNo = seeyonEntity.getId();//OA付款单号
    //                    String xml = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:mdm=\"http://mdmData.server.webservice.banck.com\">\n" +
    //                            "   <soap:Header/>\n" +
    //                            "   <soap:Body>\n" +
    //                            "      <mdm:intoPaymentDataXml>\n" +
    //                            "         <!--Optional:-->\n" +
    //                            "         <mdm:xml>\n" +
    //                            "         <![CDATA[\n" +
    //                            "         <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
    //                            "<message>\n" +
    //                            "<head>\n" +
    //                            "<transCode>BkReceiptQueryExchange</transCode>\n" +
    //                            "<erpTimestamp>" + DateUtil.dateToString(new Date(), "yyyy-mm-dd hh:mm:ss") + "</erpTimestamp>\n" +
    //                            "<sourcePlat>CFS</sourcePlat>\n" +
    //                            "<desPlat>OA</desPlat>\n" +
    //                            "<rmk>OA电子回单共享发送</rmk>\n" +
    //                            "<sessionId>" + token + "</sessionId>\n" +
    //                            "</head>\n" +
    //                            "<body>\n" +
    //                            "<bankAcc>" + bankAcc + "</bankAcc>\n" +
    //                            "<erpVoucherNo>" + erpVoucherNo + "</erpVoucherNo>\n" +
    //                            "</body>\n" +
    //                            "</message>\n" +
    //                            "         ]]>\n" +
    //                            "         </mdm:xml>\n" +
    //                            "      </mdm:intoPaymentDataXml>\n" +
    //                            "   </soap:Body>\n" +
    //                            "</soap:Envelope>";
    //                    logger.info("CFS电子回单共享请求参数为:{}", xml);
    //                    String url = "http://101.132.140.208:26893/erp/services/HTSZ_OA_BkReceiptQueryWebService?wsdl";
    //                    String result = HttpRequest.post(url).header("Content-Type", "soap/xml").timeout(30000).body(xml).execute().body();
    //                    logger.info("CFS电子回单共享请求参数为:{}", result);
    //                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    //                    DocumentBuilder builder = factory.newDocumentBuilder();
    //                    org.w3c.dom.Document document = builder.parse(new InputSource(new StringReader(result)));
    //                    org.w3c.dom.Element bodyElement = (org.w3c.dom.Element) document.getElementsByTagName("ns:return").item(0);
    //                    if (null != bodyElement) {
    //                        String textContent = bodyElement.getTextContent();
    //                        Document documentContext = DocumentHelper.parseText(textContent);
    //                        Element rootElement = documentContext.getRootElement();
    //                        Element body = rootElement.element("body");
    //                        if("0000".equalsIgnoreCase(rootElement.element("head").element("returnCode").getText())){
    //                            if (null != body) {
    //                                Element listElc = body.element("list");
    //                                List<Element> elementsElc = listElc.elements();
    //                                for (Element element : elementsElc) {
    //                                    String fielPath = element.element("filePath").getText();//电子回单附件路径
    //                                    if (fielPath != null && fielPath!="") {
    //                                        // String fielPath="C:\\Users\\笃曙\\Desktop\\15HZ000342CIBN2023091100066856211000001.pdf";
    //                                        File file = new File(fielPath);
    //                                        JSONObject jsonObject = fileUpload(file);
    //                                        logger.info("上传返回的附件id为:{}", jsonObject.getString("fileUrl"));
    //                                        if (jsonObject.getString("fileUrl") != null) {
    //                                            //表单的附件字段=ctpAttachment的Sub_reference，表单的Summary_id=ctpAttachment的att_reference
    //                                            String sub_reference = String.valueOf(UUIDLong.longUUID());
    //                                            seeyonEntity.setField0264(sub_reference);
    //                                            seeYonDao.updateFormformmain_0327(seeyonEntity);
    //                                            //根据附件id查询附件业务数据
    //                                            String file_url = jsonObject.getString("fileUrl");
    //                                            CtpAttachmentEntity ctpAttachmentEntity = new CtpAttachmentEntity();
    //                                            ctpAttachmentEntity.setFile_url(file_url);
    //                                            String att_reference = seeyonEntity.getSummary_id();//Summary_id
    //                                            ctpAttachmentEntity.setSub_reference(sub_reference);
    //                                            ctpAttachmentEntity.setAtt_reference(att_reference);
    //                                            List<CtpAttachmentEntity> ctpAttachmentEntities = ctpAttachmentDao.queryCtpAttachment(ctpAttachmentEntity);
    //                                            //如果没有查询到数据，就新增附件业务，否则更新
    //                                            if (ctpAttachmentEntities.size() == 0) {
    //                                                String category = jsonObject.getString("category");
    //                                                String type = jsonObject.getString("type");
    //                                                String filename = jsonObject.getString("filename");
    //                                                String mime_type = jsonObject.getString("mimeType");
    //                                                String attachment_size = jsonObject.getString("size");
    //                                                String id = String.valueOf(UUIDLong.longUUID());
    //                                                ctpAttachmentEntity.setCategory(category);
    //                                                ctpAttachmentEntity.setFilename(filename);
    //                                                ctpAttachmentEntity.setType(type);
    //                                                ctpAttachmentEntity.setMime_type(mime_type);
    //                                                ctpAttachmentEntity.setAttachment_size(attachment_size);
    //                                                ctpAttachmentEntity.setId(id);
    //                                                ctpAttachmentEntity.setCategory("66");
    //                                                ctpAttachmentEntity.setCreatedate(new Date());
    //                                                ctpAttachmentDao.saveCtpAttachment(ctpAttachmentEntity);
    //                                            } else {
    //                                                if (ctpAttachmentEntities.size() > 1) {
    //                                                    throw new BaseSystemException("OA附件业务表中查到多条记录");
    //                                                }
    //                                                //更新数据到OA附件业务表中
    //                                                ctpAttachmentDao.updateCtpAttachment(ctpAttachmentEntity);
    //                                            }
    //                                        }
    //                                    }
    //                                }
    //                            }
    //                        }else{
    //                            logger.info("CFS电子回单返回得错误编码：{}，以及返回的错误信息:{}",rootElement.element("head").element("returnCode").getText(),rootElement.element("head").element("returnMsg").getText());
    //                        }
    //                    }
    //                }
    //            }
    //        }
    //    }catch (Exception e){
    //        logger.info("CFS电子回单共享错误:{}",e.getMessage());
    //    }
    //}


    public static JSONObject fileUpload(File file) {
        if (null != file) {
            try {
                HashMap<String, Object> paramMap = new HashMap<>();
                paramMap.put("file", file);
                String url = "/seeyon/rest/attachment?token=@token@";//如果后面加上applicationCategory=1&extensions=&firstSave=true，附件业务自动生成一条记录
                url = url.replaceAll("@token@", getToken());
                String result = HttpUtil.post("http://60.204.152.210" + url, paramMap);
                if (StrUtil.isNotBlank(result)) {
                    logger.info("附件上传结果"+result);
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    String atts = jsonObject.get("atts").toString();
                    if (StrUtil.isNotEmpty(atts)) {
                        JSONArray jsonArray = JSONArray.parseArray(atts);
                        JSONObject res = (JSONObject) jsonArray.get(0);
                       /* String fileUrl =  res.getString("fileUrl");
                        logger.info("附件id:" + fileUrl);
                        return fileUrl;*/
                        return res;
                    }
                }
            }catch (Exception e){
                logger.error("附件上传失败"+e.getMessage());
            }
        }
        return null;
    }

    private static String getToken() {
        //获取oatoken
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("userName", "hzyaRest");
        hashMap.put("password", "a5ce21b8-91db-4cec-b3e3-3e44719655fd");
        hashMap.put("loginName","bdmanager");
        String result = HttpUtil.post("http://60.204.152.210" + "/seeyon/rest/token", JSON.toJSONString(hashMap));
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (null != jsonObject) {
            logger.info(result);
            logger.info("======token：{}======" + jsonObject.getString("id"));
            return jsonObject.getString("id");
        }
        return null;
    }
}
