package com.cftech.common.send.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cftech.brand.apply.detail.model.BrandApplyDetail;
import com.cftech.brand.apply.detail.model.BrandApplyDetailVo;
import com.cftech.brand.apply.model.BrandApply;
import com.cftech.brand.apply.model.BrandApplyVo;
import com.cftech.brand.util.BrandExportUtil;
import com.cftech.cms.SendEmail.EmailSendMessageUtil;
import com.cftech.common.marketing.model.Marketing;
import com.cftech.common.marketing.service.MarketingService;
import com.cftech.common.typeappform.model.TypeAppForm;
import com.cftech.common.typeappform.util.StatisticalCommonExportUtil;
import com.cftech.core.sql.Conds;
import com.cftech.core.util.DateUtils;
import com.cftech.core.util.StringUtils;
import com.cftech.core.util.SystemConfig;
import com.cftech.showroom.appform.model.AppForm;
import org.apache.commons.lang3.StringEscapeUtils;
import org.mp.api.wxsendmsg.JwTemplateMessageAPI;
import org.owasp.esapi.ESAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.math.BigDecimal;
import java.util.*;

public class CommonSendUtils {

    //域名
    static String yuming = SystemConfig.p.getProperty("QY_DOMAIN_NAME");

    //APPID
    static String appid = SystemConfig.p.getProperty("WX_MP_SERVER_APPID");
    //促销品模板消息keyword
    static String serverName = "促销品申请服务";
    // 市场服务模板消息keyword
    static String marketServerName = "市场服务";
    //促销品邮件主题
    static String commonTitle = "Marketing Service - Application needs to be approved";
    //促销品附件名字
    static String commonFileName = "市场服务申请单";
    //展厅申请附件名字
    static String showroomFileName = "展厅预约服务需求单Showroom Booking Requirement";
    //品牌申请附件名字
    static String brandApplyFileName= "品牌申请服务申请单";
    //申请失败模板消息ID
    static String applicationErrorTemplateId = SystemConfig.p.getProperty("applicationErrorTemplateId");
    //促销品通用模板消息ID
    static String applyReserveTemplateId = SystemConfig.p.getProperty("applyReserveTemplateId");
    //展厅取消模板消息ID
    static String cancelApplyReserveTemplateId = SystemConfig.p.getProperty("cancelApplyReserveTemplateId");
    /**
     * 促销品申请提交成功，模版消息ID
     */
    static String commonSubmitSuccessTemplateId= SystemConfig.p.getProperty("commonSubmitSuccessTemplateId");
    /**
     * 职能部门领导审批后流入市场部领导审批时通知管理员
     */
    static String orderAcceptanceSuccessTemplateId = SystemConfig.p.getProperty("orderAcceptanceSuccessTemplateId");

    /**
     * 发货通知申请人和管理员
     */
    static String orderDeliverGoodsTemplateId = SystemConfig.p.getProperty("orderDeliverGoodsTemplateId");

    /**
     * 【促销品申请】管理员确认收货后，通知申请人提交评价
     */
    static String serverEndTemplateId = SystemConfig.p.getProperty("serverEndTemplateId");


    //促销品申请模板消息跳转URL
    static String url = yuming +"/static/mp/schaeffler/process/check_form.html?appid="+appid + "&id=";
    //促销品申请申请人评价页面URL
    static String evaluateUrl = yuming+"/static/mp/schaeffler/process/apply_evaluate.html?appid="+appid+"&id=";
    //展厅申请模板消息跳转URL
    static String showroomUrl = yuming +"/static/mp/schaeffler/process/form.html?appid=" + appid + "&id=";
    //附件后缀
    static String pdfSuffix = ".pdf";


    /**
     * 促销品申请，给部门领导发送邮件
     */
    public static String [] sendDepartmentMail(String email, Long id, String name, String totalSum, List<File> files,String number){
        if(StringUtils.isEmpty(totalSum)){
            totalSum="0";
        }
//        if(StringUtils.isEmpty(personSum)){
//            personSum="0";
//        }
        BigDecimal totalSumBigDescimal = new BigDecimal(totalSum).setScale(2, BigDecimal.ROUND_HALF_UP);
        // BigDecimal personSumBigDescimal = new BigDecimal(personSum).setScale(2, BigDecimal.ROUND_HALF_UP);
        Set<String> toMails = new HashSet<>();
        toMails.add(email);
        String yuming = SystemConfig.p.getProperty("QY_DOMAIN_NAME");
        String okurl = yuming +"/mobile/wxjs/auditConfirm?id="+id+"&type=0"+"&mold=0";
        String nourl = yuming +"/mobile/wxjs/auditConfirm?id="+id+"&type=1"+"&mold=0";
        StringBuffer sb = new StringBuffer();
        sb.append("<br/>Dear Mr./Ms. "+name+",<br/><br/>");
        sb.append("You have received an application for marketing service that requires your approval.<br/> ");
        sb.append("Please confirm the application details as attached and click below to submit your approval：<br/>");
        sb.append("<a href='"+okurl+"'>- 同意Agree</a><br/>");
        sb.append("<a href='"+nourl+"'>- 拒绝申请Reject</a><br/>");
        sb.append("<br/>");
        sb.append("<span style='padding-left:2em;'>");
        sb.append("Here we kindly remind you that the accumulated amount you have approved for Marketing Service Application is <font color='red'>"+StatisticalCommonExportUtil.parseToThousandBit(totalSumBigDescimal)+"</font> CNY.<br>");
        // sb.append("the total amount Mr. /Ms. "+appName+" has applied for Marketing Service is <font color='red'>"+personSumBigDescimal+"</font> RMB.</br>");
        sb.append("</span>");
        sb.append("<br/>Thank you.<br/><br/>");
        sb.append("Best regards, <br/>");
        sb.append("Communications and Branding, Schaeffler Greater China<br/>");
        return  EmailSendMessageUtil.sendMail(files,toMails,null,commonTitle,sb.toString(),commonFileName+number+pdfSuffix);
    }

    /**
     * 促销品申请，给市场部领导发送邮件
     */
    public static String [] sendMarketMail(String email,Long id,String name,String totalSum, List<File> files,String number){
        if(StringUtils.isEmpty(totalSum)){
            totalSum="0";
        }
//        if(StringUtils.isEmpty(personSum)){
//            personSum="0";
//        }
        BigDecimal totalSumBigDescimal = new BigDecimal(totalSum).setScale(2, BigDecimal.ROUND_HALF_UP);
        // BigDecimal personSumBigDescimal = new BigDecimal(personSum).setScale(2, BigDecimal.ROUND_HALF_UP);
        Set<String> toMails = new HashSet<>();
        toMails.add(email);
        String yuming = SystemConfig.p.getProperty("QY_DOMAIN_NAME");
        String okurl = yuming +"/mobile/wxjs/auditConfirm?id="+id+"&type=0"+"&mold=1";
        String nourl = yuming +"/mobile/wxjs/auditConfirm?id="+id+"&type=1"+"&mold=1";
        StringBuffer sb = new StringBuffer();
        sb.append("<br/>Dear Mr./Ms. "+name+",<br/><br/>");
        sb.append("You have received an application for marketing service that requires your approval.<br/> ");
        sb.append("Please confirm the application details as attached and click below to submit your approval：<br/>");
        sb.append("<a href='"+okurl+"'>- 同意Agree</a><br/>");
        sb.append("<a href='"+nourl+"'>- 拒绝申请Reject</a><br/>");
        sb.append("<br/>");
        sb.append("<span style='padding-left:2em;'>");
        sb.append("Here we kindly remind you that the accumulated amount you have approved for Marketing Service Application is <font color='red'>"+StatisticalCommonExportUtil.parseToThousandBit(totalSumBigDescimal)+"</font> CNY.<br>");
        sb.append("</span>");
        //sb.append("the total amount Mr. /Ms. "+appName+" has applied for Marketing Service is <font color='red'>"+personSumBigDescimal+"</font> RMB.</br>");
        sb.append("<br/>Thank you.<br/><br/>");
        sb.append("Best regards, <br/>");
        sb.append("Communications and Branding, Schaeffler Greater China<br/>");
        return  EmailSendMessageUtil.sendMail(files,toMails,null,commonTitle,sb.toString(),commonFileName+number+pdfSuffix);
    }

    /**
     *促销品审核，给申请人发送模板消息审批通过，等待发货
     */
    public static void sendApplicationPassTemplate(String token,String openId,Date createTime,Long id,String name){
        String templateId = SystemConfig.p.getProperty("applyReserveTemplateId");
        String first = "尊敬的"+name+"，您的申请已审批通过，请等待发货。";
        String [] keywords = {marketServerName, DateUtils.formatDate(createTime,"yyyy-MM-dd HH:mm"),name};
        String remarks = "点击查看申请单详情。";
        String commonUrl = url+id;
        JwTemplateMessageAPI.sendMessage(templateId,token,openId,first,remarks,keywords,commonUrl);
    }
    /**
     * 职能部门领导拒绝申请后>>>>>给申请人发送：促销品申请，给申请人发送模板消息审批拒绝
     */
    public static void sendApplicationRejectedTemplate(String token,String openId,Long id,String name,String approvalName){
        String first = "尊敬的"+name+"，您的促销品申请审批不通过。";
        String [] keywords = { DateUtils.formatDate(new Date(),"yyyy-MM-dd HH:mm"),approvalName};
        String remarks = "请与审批人沟通确认后重新提交申请。";
        String commonUrl = url+id;
        JwTemplateMessageAPI.sendMessage(applicationErrorTemplateId,token,openId,first,remarks,keywords,commonUrl);
    }
    /**
     * 促销品申请，给申请人发送模板消息提交成功，等待审批
     */
    public static void sendApplicationSubmitTemplate(String token,String openId,Long id,String name,Date createTime,String number){
        String first = "尊敬的"+name+"，您的市场服务申请已提交成功，请等待审批。";
        String [] keywords = {number, DateUtils.formatDate(createTime,"yyyy-MM-dd HH:mm"),name};
        String remarks = "点击查看申请单详情。";
        String commonUrl = url+id;
        JwTemplateMessageAPI.sendMessage(commonSubmitSuccessTemplateId,token,openId,first,remarks,keywords,commonUrl);
    }
    /**
     * 促销品申请，管理员发放后给申请人发送发放成功模板消息
     */
    public static void sendApplicationGrantTemplate(String token,String openId,Long id,String name,Date createTime){
        String first = "尊敬的"+name+"，您的促销品申请已发货，请注意查收。";
        String [] keywords = {serverName, DateUtils.formatDate(createTime,"yyyy-MM-dd HH:mm"),name};
        String remarks = "点击查看促销品申请详情。";
        String commonUrl = url+id;
        JwTemplateMessageAPI.sendMessage(applyReserveTemplateId,token,openId,first,remarks,keywords,commonUrl);
    }

    /**
     * 促销品申请，申请人提交成功后，通知后台管理员
     */
    public static void sendManagerTemplate (String token,List<String> openId,Long id,Date nowDate,String number){
        for(String str : openId){
            String first = "尊敬的管理员，您收到一份市场服务申请。";
            String [] keywords = {number, DateUtils.formatDate(nowDate,"yyyy-MM-dd HH:mm")};
            String remarks = "点击查看该申请单详情。";
            String commonUrl = url+id;
            JwTemplateMessageAPI.sendMessage(commonSubmitSuccessTemplateId,token,str,first,remarks,keywords,commonUrl);
        }
    }

    /**
     * 促销品申请，市场部领导审核通过后，通知后台管理员
     */
    public static void sendManagerAuditSuccessTemplate (String token,List<String> openId,Long id,Date nowDate,String orderNo){
        for(String str : openId){
//            String first = "尊敬的管理员，该申请单（单号"+orderNo+"）市场部领导已经审批通过，请安排发货。";
            String first = "尊敬的管理员，该市场服务申请单（单号"+orderNo+"）已经审批通过，请安排发货。";
            String [] keywords = {marketServerName, DateUtils.formatDate(nowDate,"yyyy-MM-dd HH:mm")};
            String remarks = "点击查看申请单详情。";
            String commonUrl = url+id;
            JwTemplateMessageAPI.sendMessage(applyReserveTemplateId,token,str,first,remarks,keywords,commonUrl);
        }
    }

    /**
     * 促销品申请，职能部门领导领导审核通过后，不在需要市场部领导审核，通知后台管理员
     */
    public static void sendManagerDeptAuditSuccessTemplate (String token,List<String> openId,Long id,Date nowDate,String orderNo){
        for(String str : openId){
//            String first = "尊敬的管理员，该促销品申请单（单号"+orderNo+"）职能部门领导已经审批通过，请安排发货。";
            String first = "尊敬的管理员，该市场服务申请单（单号"+orderNo+"）已经审批通过，请安排发货。";
            String [] keywords = {marketServerName, DateUtils.formatDate(nowDate,"yyyy-MM-dd HH:mm")};
            String remarks = "点击查看申请单详情。";
            String commonUrl = url+id;
            JwTemplateMessageAPI.sendMessage(applyReserveTemplateId,token,str,first,remarks,keywords,commonUrl);
        }
    }


    /**
     * 促销品申请，金额超过上限，职能部门领导审批后流入市场部领导审批时通知管理员
     */
    public static void sendMarketAndDepartmentTemplate(String token,List<String> openId,Long id,Date nowDate,String orderNo){
        for(String str : openId){
            String first = "尊敬的管理员，该申请单职能部门领导已审批，目前市场部领导审批。";
            String [] keywords = {orderNo, DateUtils.formatDate(nowDate,"yyyy-MM-dd HH:mm"),"待市场部领导审批"};
            String remarks = "点击查看该申请单详情。";
            String commonUrl = url+id;
            JwTemplateMessageAPI.sendMessage(orderAcceptanceSuccessTemplateId,token,str,first,remarks,keywords,commonUrl);
        }
    }


    /**
     *促销品申请 市场部领导审批不通过时通知管理员
     */
    public static void sendManagerAndMarketrejected(String token,List<String> openId,Long id,Date nowDate,String orderNo){
        for(String str : openId){
            String first = "尊敬的管理员，该促销品申请单（单号"+orderNo+"）市场部审批拒绝。";
            String [] keywords = { serverName,DateUtils.formatDate(nowDate,"yyyy-MM-dd HH:mm")};
            String remarks = "点击查看申请单详情。";
            String commonUrl = url+id;
            JwTemplateMessageAPI.sendMessage(applicationErrorTemplateId,token,str,first,remarks,keywords,commonUrl);
        }
    }

    /**
     * 【促销品申请】管理员录入发放数量后，通知供应商发货，录入物流及单号信息。
     */
    public static void managerGrantSubmitSendSupplier(List<String> openId,Long id,Date nowDate,String orderNo,String token){
        for(String str : openId){
            String first = "尊敬的促销品供应商，请为申请单（单号"+orderNo+"）安排发货，并录入物流详情。";
            String [] keywords = {marketServerName, DateUtils.formatDate(nowDate,"yyyy-MM-dd HH:mm")};
            String remarks = "点击查看需发货的申请单详情。";
            String commonUrl = url+id;
            JwTemplateMessageAPI.sendMessage(applyReserveTemplateId,token,str,first,remarks,keywords,commonUrl);
        }
    }

    /**
     * 【促销品申请】供应商发货，录入物流后通知申请人
     * 当发货方方为管理员，管理员确认发货后即可推送，
     * 当发货方为供应商，供应商确认发货后即可推送，
     * 当发货方为供应商+管理员，双方确认发货后即可推送。
     */
    public static void grantPromotionSendApply(String openId,Long id,Date nowDate,String name,String logistics,String token,String orderNo){
        String first = "尊敬的"+name+"，您的订单已发货，请注意查收。";
        String [] keywords = {logistics,orderNo, DateUtils.formatDate(nowDate,"yyyy-MM-dd HH:mm")};
        String remarks = "点击查看市场服务申请单详情。";
        String commonUrl = url+id;
        JwTemplateMessageAPI.sendMessage(orderDeliverGoodsTemplateId,token,openId,first,remarks,keywords,commonUrl);
    }

    /**
     *【促销品申请】供应商发货后，通知管理员。
     * 当发货方方为管理员，管理员确认发货后即可推送，
     * 当发货方为供应商，供应商确认发货后即可推送，
     * 当发货方为供应商+管理员，双方确认发货后即可推送。
     */
    public static void grantPromotionSendManager(List<String> openIds,String logistics,Date date,String token,Long id,String orderNo){
        for(String str : openIds){
            String first = "尊敬的管理员，该申请单已发货，请及时确认收货。";
            String [] keywords = {logistics,orderNo, DateUtils.formatDate(date,"yyyy-MM-dd HH:mm")};
            String remarks = "点击查看申请单详情。";
            String commonUrl = url+id;
            JwTemplateMessageAPI.sendMessage(orderDeliverGoodsTemplateId,token,str,first,remarks,keywords,commonUrl);
        }
    }

    /**
     * 管理员确认收货后，通知申请人进行评分
     * 【促销品申请】管理员确认收货后，通知申请人提交评价
     */
    public static void confirmPromotionSendApply(String openId,String token,Date date,Long id,String name,String orderNo){
        String first = "尊敬的"+name+"，您的订单已经确认收货。我们期待您的评价和建议。";
        String [] keywords = {orderNo,marketServerName};
        String remarks = "欢迎点击详情，提交反馈或建议。";
        String commonUrl = evaluateUrl+id;
        JwTemplateMessageAPI.sendMessage(serverEndTemplateId,token,openId,first,remarks,keywords,commonUrl);
    }


    /**
     * 展厅申请，申请成功之后，给管理员及讲解人发送邮件
     */
    public static String [] sendshowRoomMail(List<File> files,Set<String> tomail,Set<String> ccmail,String number){
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("<br/>Dear all,<br/><br/>");
        stringBuffer.append("You have received a new booking request for the Anting Showroom. Please refer to the document attached for details.");
        stringBuffer.append("<br/><br/>");
        stringBuffer.append("Best regards,<br/>");
        stringBuffer.append("Communications and Branding, Schaeffler Greater China");
        String subjectName = "Anting Showroom - Booking Application";
        return EmailSendMessageUtil.sendMail(files,tomail,ccmail,subjectName,stringBuffer.toString(),showroomFileName+number+pdfSuffix);
    }

    /**
     * 展厅申请，申请成功之后，给申请人发送模板消息
     */
    public  static void sendShowRoomTemplateMessageSuccess(String token,String keyword1,String keyword2,String keyword3,String remarks,String first,Long id,String openId){
        String[] keyword = {keyword1,keyword2,keyword3};
        String showroomUrlTemp = showroomUrl+id;
        JwTemplateMessageAPI.sendMessage(SystemConfig.p.getProperty("showroomTemplateId"), token, openId, first, remarks, keyword, showroomUrlTemp);
    }

    /**
     * 展厅申请，取消服务之后，给相关人发送邮件
     */
    public static void sendCancelShowRoomMailMessage(Set<String> tomail, Set<String> ccmail, AppForm appFormTemp){

        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("<br/>Dear all,<br/><br/>");
        stringBuffer.append(appFormTemp.getName() + " has <font color='red'>cancelled</font> his/her booking request for the Anting Showroom. The original booking info is as below:");
        stringBuffer.append("<br/>");
        stringBuffer.append("<ul>");
        stringBuffer.append("<li>预约人Applicant：" + appFormTemp.getName() + "</li>");
        stringBuffer.append("<li>预约部门Applicant Div./Dep.: " + appFormTemp.getDname() + "</li>");
        stringBuffer.append("<li>预约日期Booking Date：" + appFormTemp.getDate() + "</li>");
        stringBuffer.append("<li>预约时间段Booking Time: " + appFormTemp.getTimeStr() + "</li>");
        stringBuffer.append("<li>状态Status：已取消Cancelled");
        stringBuffer.append("</ul>");
        stringBuffer.append("</br>");
        stringBuffer.append("Best regards,</br>");
        stringBuffer.append("Communications and Branding, Schaeffler Greater China");
        String subjectName = "Anting Showroom - Booking Application Cancelled";
        EmailSendMessageUtil.sendMail(null,tomail,ccmail,subjectName,stringBuffer.toString(),null);
    }

    /**
     * 促销品，职能部门领导pdf,市场部领导pdf数据填充
     */
    public static Map<String,Object> data(TypeAppForm typeAppForm,String approvalPrice){
        Map<String,Object> params = new HashMap<>();
        params.put("approverName",typeAppForm.getAname());
        params.put("name",typeAppForm.getName());
        params.put("org",typeAppForm.getOrg());
        params.put("departmentName",typeAppForm.getDname());
        params.put("costCenter",typeAppForm.getCostCenter());
        params.put("managerName",SystemConfig.p.getProperty("MANAGEREMAIL"));
        params.put("createTime",DateUtils.formatDate(new Date(),"yyyy/MM/dd"));
        params.put("use",typeAppForm.getUname());
        params.put("appPrice", StatisticalCommonExportUtil.parseToThousandBit(typeAppForm.getAppPrice()));
        params.put("approvalPrice",StatisticalCommonExportUtil.parseToThousandBit(StringUtils.isNotBlank(approvalPrice)?approvalPrice:"0.00"));
        params.put("remarks",StringUtils.isNotBlank(typeAppForm.getRemarks())?typeAppForm.getRemarks():"无");
        params.put("address",typeAppForm.getAddress());
        if(StringUtils.isNotBlank(typeAppForm.getItems())){
            List<Map<String,Object>> objList = new ArrayList<Map<String,Object>>();
            String items = ESAPI.encoder().decodeForHTML(typeAppForm.getItems());
            JSONArray array = JSON.parseArray(items);
            for(int i=0;i<array.size();i++){
                JSONObject objJson = array.getJSONObject(i);
                Map<String,Object> obj = new HashMap<>();
                String price = objJson.getString("price");
                String num = objJson.getString("num");
                obj.put("spec","个/只/本");
                BigDecimal bigDecimalP = new BigDecimal(price);
                BigDecimal bigDecimalN = new BigDecimal(num);
                //此商品发放金额
                BigDecimal bigDecimalT = (bigDecimalP.multiply(bigDecimalN)).setScale(2, BigDecimal.ROUND_HALF_UP);
                //不满位数则补0
                String sort = String.format("%02d",i+1);
                obj.put("priceSum",StatisticalCommonExportUtil.parseToThousandBit(bigDecimalT));
                obj.put("name",objJson.getString("name"));
                obj.put("sort",sort);
                obj.put("num",num);
                obj.put("price",StatisticalCommonExportUtil.parseToThousandBit(price));
                objList.add(obj);
            }
            params.put("itemList",objList);
        }
        return params;
    }
    /**
     * 品牌申请管理员接单pdf数据填充
     */
    public static Map<String,Object> handleDataByBrandApplySubmit(BrandApplyVo data){
        Map<String,Object> params = new HashMap<>();
        params.put("name",data.getName());
        params.put("email",data.getEmail());
        params.put("department", StringEscapeUtils.escapeHtml4(data.getDepartmentName()));
        params.put("costCenter",data.getCostCenter());
        params.put("lineManager",data.getLineManager());
        params.put("lineManagerEmail",data.getLineManagerEmail());
        params.put("createTime",DateUtils.formatDate(data.getCreateTime(),"yyyy/MM/dd"));
        params.put("number",data.getNumber());
        params.put("requireSpecify",data.getRequireSpecify());
        String remark="无";
        if(!StringUtils.isEmpty(data.getDescription())){
            remark=data.getRequireSpecify();
        }
        params.put("managerName",data.getAuditName());
        params.put("description",remark);
        params.put("categoryName",StringEscapeUtils.escapeHtml4(data.getCategoryName()));
        List<Map<String,Object>> detailList = new ArrayList<Map<String,Object>>();
        int index=0;
        for(BrandApplyDetailVo detail:data.getDetails()){
            Map<String,Object> obj = new HashMap<>();
            obj.put("needMake",StringUtils.equals("1",data.getIsMaterialObject())&&detail.getQuantity()>0?"Yes":"/");
            obj.put("count",detail.getQuantity()==0?"/":detail.getQuantity());
            obj.put("name",detail.getMaterialName());
            obj.put("index",index);
            detailList.add(obj);
            index++;
        }
        params.put("detailList",detailList);
        params.put("deliveryDate",DateUtils.formatDate(data.getDeliveryDate(),"yyyy-MM-dd"));
        return params;
    }



    /**
     * 品牌申请管理员接单pdf数据填充
     */
    public static Map<String,Object> handleDataByBrandApplyAgreed(BrandApplyVo data){
        Map<String,Object> params = new HashMap<>();
        params.put("name",data.getName());
        params.put("email",data.getEmail());
        params.put("department",StringEscapeUtils.escapeHtml4(data.getDepartmentName()));
        params.put("costCenter",data.getCostCenter());
        params.put("lineManager",data.getLineManager());
        params.put("lineManagerEmail",data.getLineManagerEmail());
        params.put("createTime",DateUtils.formatDate(data.getCreateTime(),"yyyy/MM/dd"));
        params.put("number",data.getNumber());
        params.put("requireSpecify",data.getRequireSpecify());
        String remark="无";
        if(!StringUtils.isEmpty(data.getDescription())){
            remark=data.getRequireSpecify();
        }
        params.put("managerName",data.getAuditName());
        params.put("description",remark);
        params.put("categoryName",StringEscapeUtils.escapeHtml4(data.getCategoryName()));
        params.put("distributionClass",data.getDistributionClass());
        List<Map<String,Object>> detailList = new ArrayList<Map<String,Object>>();
        int makeCount=0;
        for(BrandApplyDetailVo detail:data.getDetails()){
            makeCount=makeCount+detail.getQuantity();
            Map<String,Object> obj = new HashMap<>();
            obj.put("needMake",StringUtils.equals("1",data.getIsMaterialObject())&&detail.getQuantity()>0?"Yes":"No");
            obj.put("count",detail.getQuantity()==0?"No":detail.getQuantity());
            obj.put("name",detail.getMaterialName());
            detailList.add(obj);
        }
        params.put("detailList",detailList);
        params.put("estimatedWorkload",data.getEstimatedWorkload());
        params.put("estimateInternalCosts",data.getEstimateInternalCosts());
        params.put("makeCount",makeCount);
        params.put("estimateExternalCosts",data.getEstimateExternalCosts()!=null?BrandExportUtil.fmtMicrometer(data.getEstimateExternalCosts().toString()):" ");
        params.put("totalCost",data.getQuotedPrice()!=null?BrandExportUtil.fmtMicrometer(data.getQuotedPrice().toString()):" ");
        params.put("intendedDeliveryDate",DateUtils.formatDate(data.getIntendedDeliveryDate(),"yyyy-MM-dd"));
        return params;
    }

    /**
     * 市场部领导审核抄送分工同事
     */
    public static Map<String,Object> handleDataByBrandApplyDivision(BrandApplyVo data){
        Map<String,Object> params = new HashMap<>();
        params.put("name",data.getName());
        params.put("email",data.getEmail());
        params.put("department",StringEscapeUtils.escapeHtml4(data.getDepartmentName()));
        params.put("costCenter",data.getCostCenter());
        params.put("lineManager",data.getLineManager());
        params.put("lineManagerEmail",data.getLineManagerEmail());
        params.put("createTime",DateUtils.formatDate(data.getCreateTime(),"yyyy/MM/dd"));
        params.put("number",data.getNumber());
        params.put("requireSpecify",data.getRequireSpecify());
        String remark="无";
        if(!StringUtils.isEmpty(data.getDescription())){
            remark=data.getRequireSpecify();
        }
        params.put("managerName",data.getAuditName());
        params.put("description",remark);
        params.put("categoryName",StringEscapeUtils.escapeHtml4(data.getCategoryName()));
        params.put("distributionClass",data.getDistributionClass());
        List<Map<String,Object>> detailList = new ArrayList<Map<String,Object>>();
        int makeCount=0;
        for(BrandApplyDetailVo detail:data.getDetails()){
            makeCount=makeCount+detail.getQuantity();
            Map<String,Object> obj = new HashMap<>();
            obj.put("needMake",StringUtils.equals("1",data.getIsMaterialObject())&&detail.getQuantity()>0?"Yes":"No");
            obj.put("count",detail.getQuantity()==0?"No":detail.getQuantity());
            obj.put("name",detail.getMaterialName());
            detailList.add(obj);
        }
        params.put("detailList",detailList);
        //根据分配类别做数据处理 申请分配类别 0 仅设计 1仅制作 2设计和制作
        if(StringUtils.equals("0",data.getDistributionClass())){
            params.put("designerName",data.getEmpName());
        }else if(StringUtils.equals("1",data.getDistributionClass())){
            params.put("supplierName",data.getSupplierName());
        }else{
            params.put("designerName",data.getEmpName());
            params.put("supplierName",data.getSupplierName());
        }
        params.put("intendedDeliveryDate",DateUtils.formatDate(data.getIntendedDeliveryDate(),"yyyy-MM-dd"));
        return params;
    }

    /**
     * 品牌申请完工pdf数据填充
     */
    public static Map<String,Object> handleDataByBrandApplyCompleted(BrandApplyVo data){
        Map<String,Object> params = new HashMap<>();
        params.put("name",data.getName());
        params.put("email",data.getEmail());
        params.put("department",StringEscapeUtils.escapeHtml4(data.getDepartmentName()));
        params.put("costCenter",data.getCostCenter());
        params.put("lineManager",data.getLineManager());
        params.put("lineManagerEmail",data.getLineManagerEmail());
        params.put("createTime",DateUtils.formatDate(data.getCreateTime(),"yyyy/MM/dd"));
        params.put("number",data.getNumber());
        params.put("requireSpecify",data.getRequireSpecify());
        String remark="无";
        if(!StringUtils.isEmpty(data.getDescription())){
            remark=data.getRequireSpecify();
        }
        params.put("managerName",data.getAuditName());
        params.put("description",remark);
        params.put("categoryName",StringEscapeUtils.escapeHtml4(data.getCategoryName()));
        params.put("serviceScore",StringUtils.isNotBlank(data.getServiceScore())?data.getServiceScore():"No");
        params.put("feedback",StringUtils.isNotBlank(data.getFeedback())?data.getFeedback():"No");
        List<Map<String,Object>> detailList = new ArrayList<Map<String,Object>>();
        int detailIndex=0;
        for(BrandApplyDetailVo detail:data.getDetails()){
            Map<String,Object> obj = new HashMap<>();
            obj.put("index",detailIndex);
            obj.put("count",detail.getQuantity()==0?"No need":detail.getQuantity());
            obj.put("name",detail.getMaterialName());
            detailList.add(obj);
            detailIndex++;
        }
        params.put("detailList",detailList);
        String onTime="On time";
        Date now=DateUtils.parseDate(DateUtils.formatDate(new Date(),"yyyy-MM-dd"));
        if(now.compareTo(data.getIntendedDeliveryDate())>0){
            onTime="delayed";
        }
        List<Map<String,Object>> empList = new ArrayList<Map<String,Object>>();
        Map<String,Object> designObj = new HashMap<>();
        designObj.put("name",data.getEmpName());
        designObj.put("cost",data.getInnerCost());
        designObj.put("unit","Hours");
        designObj.put("onTime",onTime);
        designObj.put("score",data.getDesignQuanlityScore());
        Map<String,Object> makeObj = new HashMap<>();
        makeObj.put("name",data.getSupplierName());
        makeObj.put("cost",data.getOuterCost());
        makeObj.put("unit","CNY");
        makeObj.put("onTime",onTime);
        makeObj.put("score",data.getMakeQuanlityScore());
        //根据分配类别做数据处理 申请分配类别 0 仅设计 1仅制作 2设计和制作
        if(StringUtils.equals("0",data.getDistributionClass())){
            empList.add(designObj);
        }else if(StringUtils.equals("1",data.getDistributionClass())){
            empList.add(makeObj);
        }else{
            empList.add(designObj);
            empList.add(makeObj);
        }
        params.put("empList",empList);
        return params;
    }

    /**
     * 发放后留档pdf数据填充
     */
    public static Map<String,Object> grantdata(TypeAppForm typeAppForm,String itemsStr){
        Map<String,Object> params = new HashMap<>();
        params.put("approverName",typeAppForm.getAname());
        params.put("name",typeAppForm.getName());
        params.put("org",typeAppForm.getOrg());
        params.put("departmentName",typeAppForm.getDname());
        params.put("costCenter",typeAppForm.getCostCenter());
        params.put("managerName",SystemConfig.p.getProperty("MANAGEREMAIL"));
        params.put("createTime",DateUtils.formatDate(typeAppForm.getCreateTime(),"yyyy/MM/dd"));
        params.put("use",typeAppForm.getUname());
        params.put("appPrice",typeAppForm.getAppPrice());
        params.put("remarks",StringUtils.isNotBlank(typeAppForm.getRemarks())?typeAppForm.getRemarks():"无");
        if(StringUtils.isNotBlank(itemsStr)){
            List<Map<String,Object>> objList = new ArrayList<Map<String,Object>>();
            String items = ESAPI.encoder().decodeForHTML(itemsStr);
            JSONArray array = JSON.parseArray(items);
            for(int i=0;i<array.size();i++){
                JSONObject objJson = array.getJSONObject(i);
                Map<String,Object> obj = new HashMap<>();
                String price = objJson.getString("price");
                String num = objJson.getString("num");
                if(objJson.containsKey("specifications")){
                    obj.put("spec",objJson.getString("specifications"));
                }else{
                    obj.put("spec",objJson.getString(""));
                }
                BigDecimal bigDecimalP = new BigDecimal(price);
                BigDecimal bigDecimalN = new BigDecimal(num);
                //此商品发放金额
                BigDecimal bigDecimalT = (bigDecimalP.multiply(bigDecimalN)).setScale(2, BigDecimal.ROUND_HALF_UP);
                String sort = "1";
                if((i+1)<10){
                    sort="0"+(i+1);
                }else{
                    sort=String.valueOf((i+1));
                }
                obj.put("priceSum",bigDecimalT.toString());
                obj.put("grantNum",objJson.getString("realityGrantCount"));
                obj.put("sort",sort);
                obj.put("name",objJson.getString("name"));
                obj.put("num",num);
                obj.put("price",price);
                objList.add(obj);
            }
            params.put("itemList",objList);
        }
        return params;
    }

    /**
     * 促销品发放后，pdf归档，发送给管理员
     */
    public static String [] sendManagerMailPdf(String number,List<File> files){
        Set<String> toMails = new HashSet<>();
        toMails.add(SystemConfig.p.getProperty("MANAGEREMAIL"));
        StringBuffer sb = new StringBuffer();
        sb.append("Dear Administrator,<br/><br/>");
        sb.append("Here you have released this application for marketing service. Please see attached for details and archive it.<br/><br/>");
        sb.append("Thank you.<br/><br/>");
        sb.append("Best regards, <br/>");
        sb.append("Communications and Branding, Schaeffler Greater China<br/>");
        String subjectName = "Please archived this released application for marketing service";
        return  EmailSendMessageUtil.sendMail(files,toMails,null,subjectName,sb.toString(),commonFileName+number+pdfSuffix);
    }

    /**
     * 品牌申请提交后发送至管理员抄送市场部领导
     */
    public static String [] sendMailByBrandApplySubmit(Long id,String name,String number,String email,Long auditId,String ccEmail,List<File> files){
        Set<String> toMails = new HashSet<>();
        toMails.add(email);
        Set<String> ccMails = new HashSet<>();
        ccMails.add(ccEmail);
        String baseUri = SystemConfig.p.getProperty("QY_DOMAIN_NAME");
        String okurl = baseUri +"/mp/brandApply/comm/managerAudit?status=1&id="+id+"&auditId="+auditId;
        String notOkUrl = baseUri +"/mp/brandApply/comm/managerAudit?status=0&id="+id+"&auditId="+auditId;
        StringBuffer sb = new StringBuffer();
        sb.append("Dear Mr./Ms. "+name+",<br/><br/>");
//        sb.append("You have received a new application request for <span style='font-weight:bold;'>Branding services</span>. ");
        sb.append("You have received a new service request for Branding Services. ");
        sb.append("Please check the details in the attachment and submit your feedback via the links below：<br/><br/>");
        sb.append("<a href='"+okurl+"'>- 接受Accept</a><br/>");
        sb.append("<a href='"+notOkUrl+"'>- 关闭Close</a><br/><br/>");
        sb.append("Thank you,<br/><br/>");
        sb.append("Communications and Branding, Schaeffler Greater China<br/><br/>");
        sb.append("<span style=\";font-family:Calibri;color:#A5A5A5;font-size:15px\">This is an automated message - please do not reply.</span>");
        String subjectName = "Branding Services – Please accept request";
        String fileName=brandApplyFileName+number+pdfSuffix;
        return  EmailSendMessageUtil.sendMail(files,toMails,ccMails,subjectName,sb.toString(),fileName);
    }

    /**
     * 品牌申请审批同意发送给申请人及抄送给直属领导
     */
    public static String [] sendMailByBrandApplyAgreed(String name,String number,String email,String ccEmail,List<File> files){
        Set<String> toMails = new HashSet<>();
        toMails.add(email);
        Set<String> ccMails = new HashSet<>();
        ccMails.add(ccEmail);
        StringBuffer sb = new StringBuffer();
        sb.append("Dear Mr./Ms. "+name+",<br/><br/>");
        sb.append("Please find attached further information about your application for Branding Services, including estimated costs and delivery date.<br/><br/>");
        sb.append("You will also receive a WeChat notification via the company WeChat account ”舍弗勒Schaeffler”.<br/><br/>");
        sb.append("Please open the WeChat notification to view the details of your application, and \"Confirm\", \"Modify\" or \"Cancel\" your requirements.<br/><br/>");
        sb.append("Thank you,<br/>");
        sb.append("Communications and Branding, Schaeffler Greater China<br/><br/>");
        sb.append("<span style=\";font-family:Calibri;color:#A5A5A5;font-size:15px\">This is an automated message - please do not reply.</span>");
        String subjectName = "Branding Services – Please confirm cost and delivery date";
        String fileName=brandApplyFileName+number+pdfSuffix;
        List<String> fileNames=new ArrayList<String>();
        fileNames.add(fileName);
        fileNames.add("How to confirm on WeChat.jpg");
        return  EmailSendMessageUtil.sendAttachMail(files,toMails,ccMails,subjectName,sb.toString(),fileNames);
    }

    /**
     * 品牌申请完工后发送给市场部领导的
     */
    public static String [] sendMailByBrandApplyCompleted(String name,String email,String number,List<File> files){
        Set<String> toMails = new HashSet<>();
        toMails.add(email);
        StringBuffer sb = new StringBuffer();
        sb.append("Dear Dear Mrs. Li,<br/><br/>");
        sb.append("The application number "+number+" for Branding Services has been completed. Please find the delivery report attached.<br/><br/>");
        sb.append("Thank you,<br/><br/>");
        sb.append("Communications and Branding, Schaeffler Greater China<br/><br/>");
        sb.append("<span style=\";font-family:Calibri;color:#A5A5A5;font-size:15px\">This is an automated message - please do not reply.</span>");
        String subjectName = "Branding Services – Delivery report";
        return  EmailSendMessageUtil.sendMail(files,toMails,null,subjectName,sb.toString(),brandApplyFileName+number+pdfSuffix);
    }

    /**
     * 品牌申请,申请人确认拟交付信息发送至市场部领导
     */
    public static String [] sendMailByEmpToBeConfirmed(String email,Long id, List<File> files,String number){
        Set<String> toMails = new HashSet<>();
        toMails.add(email);
        String baseUri = SystemConfig.p.getProperty("QY_DOMAIN_NAME");
        String okurl = baseUri +"/mobile/brandApply/auditConfirm?id="+id+"&type=0"+"&mold=1";
        String nourl = baseUri +"/mobile/brandApply/auditConfirm?id="+id+"&type=1"+"&mold=1";
        StringBuffer sb = new StringBuffer();
        sb.append("<br/>Dear Mrs. Li,<br/><br/>");
        sb.append("The application number "+number +" for Branding Services has been confirmed by the applicant.<br/> ");
        sb.append("Please check the application details attached and click on the links below to submit your approval.<br/><br/>");
        sb.append("<a href='"+okurl+"'>- 同意Approved</a><br/>");
        sb.append("<a href='"+nourl+"'>- 拒绝申请Not approved</a><br/>");
        sb.append("<br/>");
        sb.append("Thank you,<br/><br/>");
        sb.append("Communications and Branding, Schaeffler Greater China<br/><br/>");
        sb.append("<span style=\";font-family:Calibri;color:#A5A5A5;font-size:15px\">This is an automated message - please do not reply.</span>");

        String subjectNam="Branding Services – Please approve application";
        return  EmailSendMessageUtil.sendMail(files,toMails,null,subjectNam,sb.toString(),brandApplyFileName+number+pdfSuffix);
    }

    /**
     * 品牌申请 市场部领导同意后发送给申请管理员
     */
    public static String [] sendMailByBrandApplyMarketAgreed(String name,String number,String email,Set<String> ccEmails,List<File> files){
        Set<String> toMails = new HashSet<>();
        toMails.add(email);
        StringBuffer sb = new StringBuffer();
        sb.append("Dear Mr./Ms. "+name+",<br/><br/>");
        sb.append("Please find attached a new service request. Application number:");
        sb.append(" "+number+".<br/><br/>");
        sb.append("Thank you,<br/><br/>");
        sb.append("Communications and Branding, Schaeffler Greater China<br/><br/>");
        sb.append("<span style=\";font-family:Calibri;color:#A5A5A5;font-size:15px\">This is an automated message - please do not reply.</span>");
        String subjectName = " Branding Services – You have a new task";
        String fileName=brandApplyFileName+number+pdfSuffix;
        return  EmailSendMessageUtil.sendMail(files,toMails,ccEmails,subjectName,sb.toString(),fileName);
    }
}
