package cn.superdesk.uniorder.controller.accounting.customer;

import cn.hutool.core.io.FileUtil;
import cn.superdesk.uniorder.common.constants.ResponseMsgConstants;
import cn.superdesk.uniorder.common.enums.common.CommonAccountingStateEnum;
import cn.superdesk.uniorder.common.enums.accounting.AccountingOrderDimCreateByEnum;
import cn.superdesk.uniorder.common.excel.ExcelResponse;
import cn.superdesk.uniorder.common.exception.utils.ExceptionUtils;
import cn.superdesk.uniorder.common.json.AnJsonUtils;
import cn.superdesk.uniorder.common.numerical.AnBeanUtils;
import cn.superdesk.uniorder.common.rest.response.R;
import cn.superdesk.uniorder.common.rest.response.ResponseResultOuterUtils;
import cn.superdesk.uniorder.common.security.crypt.SuperdeskUniorderRsaUtils;
import cn.superdesk.uniorder.controller.accounting.utils.ExcelExportAccountingOrderDetailUtils;
import cn.superdesk.uniorder.controller.base.BaseController;
import cn.superdesk.uniorder.dao.entity.accounting.unified.customer.AccountingUnifiedCustomer;
import cn.superdesk.uniorder.dao.entity.base.UnifiedOrder;
import cn.superdesk.uniorder.dao.entity.sys.SysConfig;
import cn.superdesk.uniorder.dto._constant.ResourceConstant;
import cn.superdesk.uniorder.dto.param.accounting.unified.customer.UnifiedCustomerCreateDimOrderParam;
import cn.superdesk.uniorder.dto.vo.accounting.unified.customer.notyet.UnifiedOrderCustomerNotCheckVo;
import cn.superdesk.uniorder.dto.vo.accounting.unified.customer.statement.CustomerStatementOfAccountDetailVo;
import cn.superdesk.uniorder.dto.vo.unified.UnifiedOrderCommonHeadSum;
import cn.superdesk.uniorder.dto.vo.unified.UnifiedOrderJoinGoodsDetailVo;
import cn.superdesk.uniorder.dubbo.consumer._common.ProviderEnvConstantDubboCustomerService;
import cn.superdesk.uniorder.dubbo.consumer.accounting.customer.AccountingUnifiedCustomerDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.order.base.UnifiedOrderDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.order.base.UnifiedOrderReturnDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.organisation.SysEnterpriseDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.organisation.SysOrganizationDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.sys.SysConfigDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.sys.SysInvDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.sys.SysOderUserDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.sys.SysUserDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.unified.UnifiedCustomerDubboConsumerService;
import com.sun.mail.util.MailSSLSocketFactory;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.activation.DataSource;
import javax.activation.URLDataSource;
import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @Description: 客户结算-未对账订单
 * @Author: linjinyu 补充 修改
 * @CreateDate: 4/28/20 3:17 PM
 * @UpdateUser: linjinyu
 * @UpdateDate: 4/28/20 3:17 PM
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Api(value = "客户结算-未对账状态-订单维度", tags = {"客户结算-未对账状态-订单维度"})
@Slf4j
@RestController
@RequestMapping("/accounting/unified/customer/dim/order/notyet")
public class UnifiedCustomerNotYetDimOrderController extends BaseController {


	@Autowired
	private UnifiedCustomerDubboConsumerService unifiedCustomerDubboConsumerService;


	@Autowired
	private UnifiedOrderDubboConsumerService       unifiedOrderDubboConsumerService;
	@Autowired
	private UnifiedOrderReturnDubboConsumerService unifiedOrderReturnDubboConsumerService;

	@Autowired
	private AccountingUnifiedCustomerDubboConsumerService accountingUnifiedCustomerDubboConsumerService;

	@Autowired
	private SysInvDubboConsumerService sysInvDubboConsumerService;


	@Autowired
	private SysConfigDubboConsumerService sysConfigDubboConsumerService;

	@Autowired
	private SysUserDubboConsumerService         sysUserDubboConsumerService;
	@Autowired
	private SysOderUserDubboConsumerService     sysOderUserDubboConsumerService;
	@Autowired
	private SysOrganizationDubboConsumerService sysOrganizationDubboConsumerService;
	@Autowired
	private SysEnterpriseDubboConsumerService   sysEnterpriseDubboConsumerService;

	@Autowired
	private TemplateEngine templateEngine;

	@Resource
	private ProviderEnvConstantDubboCustomerService providerEnvConstantDubboCustomerService;

//	@Value("${me.email.dzpath}")
//	private String dzfilepath;

	/**
	 * 客户结算-未对账订单-列表
	 *
	 * @return
	 */
	@ApiOperation(value = "客户结算-未对账订单-列表")
	@RequestMapping(value = "/getnotdzpage", method = RequestMethod.POST)
	@ResponseBody
	public R<List<UnifiedOrderCustomerNotCheckVo>> getNotDzPage() {

		R<List<UnifiedOrderCustomerNotCheckVo>> result = new R<>();

		try {
			Map<String, Object> params = new HashMap<>();

			// 订单编号
			params.put("orderSn", getString("orderSn"));

			params.put("amount", getString("amount"));

			// 对账状态 订单 客户对账状态 未对账
			params.put("accountingStateCustomer", CommonAccountingStateEnum.未对账.getKey());

			// 下单时间 TODO
			params.put("startTime", getString("startTime"));
			params.put("endTime", getString("endTime"));


			// 订单类型
			String serviceNo = getString("serviceNo");
			if (StringUtils.isNotEmpty(serviceNo)) {
				params.put("serviceNo", serviceNo.split(","));
			}
			// 为什么要加这个 mark by linjinyu at 20210315
//			else {
//				serviceNo = "QYNG,FLSC,LNSS";
//				params.put("serviceNo", serviceNo.split(","));
//			}

			// 供应商名称
			params.put("supplierId", getString("supplierId"));
			params.put("supplierName", getString("supplierName"));

			// 企业名称
			params.put("virtId", getLong("virtId"));
			params.put("virtName", getString("virtName"));

			// 下单人姓名
			params.put("purchaseUserId", getString("purchaseUserId"));
			params.put("purchaseUserName", getString("purchaseUserName"));


			result = unifiedOrderDubboConsumerService.getCustomerUnAccountingDimOrderList(getToken(), params, getPageNum(), getPageSize());

			UnifiedOrderCommonHeadSum unifiedOrderCommonHeadSum = unifiedOrderDubboConsumerService.getCustomerUnAccountingDimOrderHeadSum(getToken(), params);

			// 修下为 标记 1
//			unifiedOrderCommonHeadSum.setRealAmount(unifiedOrderCommonHeadSum.getOrderAmount());
//			Map<String, Object> headData = new HashMap<>();
//			headData.put("orderAmount", unifiedOrderCommonHeadSum.getOrderAmount());
//			headData.put("total", unifiedOrderCommonHeadSum.getTotal());
//			headData.put("returnAmount", 0);
//			headData.put("realAmount", unifiedOrderCommonHeadSum.getRealAmount());

			// 标记 1
			Map<String, Object> headData = AnBeanUtils.beanToMap(unifiedOrderCommonHeadSum);

			result.setHeadData(headData);

		} catch (Exception e) {

			result.setCode(String.valueOf(e.hashCode()));
			result.setSuccess(false);
			result.setMessage(e.getMessage());

			log.error(ExceptionUtils.getMessage(e));
			e.printStackTrace();
		}

		return result;
	}

	/***
	 * 客户结算-未对账订单-opt 导出表格
	 * @param response
	 * @throws IOException
	 */
	@Deprecated
	@ApiOperation(value = "客户结算-未对账订单-opt 导出表格")
	@RequestMapping(value = "/getnotdzexcel", method = RequestMethod.GET)
	public void getNotDzOrderExcel(HttpServletResponse response) throws IOException {
		try {

			Map<String, Object> params = new HashMap<>();

			// 订单编号
			params.put("orderSn", getString("orderSn"));

			params.put("amount", getString("amount"));

			// 对账状态 订单 客户对账状态 未对账
			params.put("accountingStateCustomer", CommonAccountingStateEnum.未对账.getKey());

			// 下单时间 TODO
			params.put("startTime", getString("startTime"));
			params.put("endTime", getString("endTime"));


			// 订单类型
			String serviceNo = getString("serviceNo");
			if (StringUtils.isNotEmpty(serviceNo)) {
				params.put("serviceNo", serviceNo.split(","));
			}
			// 为什么要加这个 mark by linjinyu at 20210315
//			else {
//				serviceNo = "QYNG,FLSC,LNSS";
//				params.put("serviceNo", serviceNo.split(","));
//			}

			// 供应商名称
			params.put("supplierId", getString("supplierId"));
			params.put("supplierName", getString("supplierName"));

			// 企业名称
			params.put("virtId", getLong("virtId"));
			params.put("virtName", getString("virtName"));

			// 下单人姓名
			params.put("purchaseUserId", getString("purchaseUserId"));
			params.put("purchaseUserName", getString("purchaseUserName"));


			List<UnifiedOrderJoinGoodsDetailVo> dataList = unifiedOrderDubboConsumerService.getUnifiedOrderJoinGoodsDetailVoList(params, getToken());

			String[] field = {"orderSn", "projectName", "purchaseVirtName", "amount", "payTypeName", "orderStateName", "purchaseUserName",
					"purchasePhone", "recAddress", "createTime", "saleName", "remarks", "", "goodsName", "quantity", "price",
					"goodsAmount", "recUserName", "recUserPhone", "updateTime", "updateTime", "", "invoiceNumber", "", "invoiceStatusName", "invoiceApplySn"
			};

			String[] fieldZhCn = {"订单编号", "会员所属项目", "会员所属企业(动态)", "订单金额", "支付方式", "订单状态", "下单人姓名",
					"下单人电话", "收货地址", "下单时间", "供应商名称", "买家备注", "卖家备注", "商品信息", "商品数量", "商品单价(折扣后)",
					"商品总价(折扣后)", "收货人姓名", "收货人手机号", "发货时间", "完成时间", "回款状态", "发票号", "开票时间", "发票状态", "开票申请编号"};


			ExcelResponse.out(dataList, fieldZhCn, field, "未对账订单(商品)", "客户结算" + "_" + "未对账订单(商品)", response);

		} catch (Exception e) {

			log.error(ExceptionUtils.getMessage(e));
			e.printStackTrace();
		}
	}


	/***
	 * 客户结算-未对账订单-opt 导出表格-新版
	 * @param response
	 * @throws IOException
	 */
	@ApiOperation(value = "客户结算-未对账订单-opt 导出表格-新版")
	@RequestMapping(value = "/exportExcelAccountingCustomerNotYetDimOrder", method = RequestMethod.POST)
	public R<String> exportExcelAccountingCustomerNotYetDimOrder() throws IOException {


		Map<String, Object> params = new HashMap<>();

		// 订单编号
		params.put("orderSn", getString("orderSn"));

		params.put("amount", getString("amount"));

		// 对账状态 订单 客户对账状态 未对账
		params.put("accountingStateCustomer", CommonAccountingStateEnum.未对账.getKey());

		// 下单时间 TODO
		params.put("startTime", getString("startTime"));
		params.put("endTime", getString("endTime"));


		// 订单类型
		String serviceNo = getString("serviceNo");
		if (StringUtils.isNotEmpty(serviceNo)) {
			params.put("serviceNo", serviceNo.split(","));
		}
		// 为什么要加这个 mark by linjinyu at 20210315
//			else {
//				serviceNo = "QYNG,FLSC,LNSS";
//				params.put("serviceNo", serviceNo.split(","));
//			}

		// 供应商名称
		params.put("supplierId", getString("supplierId"));
		params.put("supplierName", getString("supplierName"));

		// 企业名称
		params.put("virtId", getLong("virtId"));
		params.put("virtName", getString("virtName"));

		// 下单人姓名
		params.put("purchaseUserId", getString("purchaseUserId"));
		params.put("purchaseUserName", getString("purchaseUserName"));

		log.info("客户结算-未对账订单-opt 导出表格-新版 params: \n{}", AnJsonUtils.toJson(params));

//		List<UnifiedOrderJoinGoodsDetailVo> dataList = unifiedOrderDubboConsumerService.getUnifiedOrderJoinGoodsDetailVoList(getToken(), params);

		return new R<String>(unifiedOrderDubboConsumerService.exportExcelAccountingCustomerNotYetDimOrder(params, getToken()));

	}


	/**
	 * 客户结算-未对账订单-创建对账单 preview
	 * 大概的流程就是在未对账订单 选择订单 出商品列表
	 * /accounting/unified/customer/notyet/createAccountingPreview
	 *
	 * @return
	 */
	@ApiOperation(value = "客户结算 -> 未对账订单-创建对账单 preview")
	@RequestMapping(value = "/createAccountingPreview", method = RequestMethod.POST)
	@ResponseBody
	public R<List<UnifiedOrderJoinGoodsDetailVo>> createAccountingPreview(String ids) {

		R<List<UnifiedOrderJoinGoodsDetailVo>> result = new R<>();

		try {

			String[] orderIds = ids.split(",");

			if (orderIds.length == 0) {
				result.setMessage("请选择至少 1 条订单！");
				return result;
			}

			Map<String, Object> params = new HashMap<>();

			params.put("ids", orderIds);
			params.put("accountingStateCustomer", CommonAccountingStateEnum.未对账.getKey());

			List<UnifiedOrderJoinGoodsDetailVo> dataList = unifiedOrderDubboConsumerService.getUnifiedOrderJoinGoodsDetailVoList(params, getToken());

			result.setData(dataList);

		} catch (Exception e) {

			result.setCode(String.valueOf(e.hashCode()));
			result.setSuccess(false);
			result.setMessage("系统查找失败！");

			log.error(ExceptionUtils.getMessage(e));
			e.printStackTrace();

		}

		return result;
	}

	/**
	 * 客户结算-未对账订单-创建对账单
	 *
	 * @param unifiedCustomerCreateDimOrderParam
	 * @return
	 */
	@ApiOperation(value = "客户结算 -> 未对账订单-创建对账单")
	@RequestMapping(value = "/createAccounting", method = RequestMethod.POST)
	@ResponseBody
	public R<AccountingUnifiedCustomer> createAccounting(@RequestBody UnifiedCustomerCreateDimOrderParam unifiedCustomerCreateDimOrderParam) {

		R<AccountingUnifiedCustomer> result = new R<>();

		try {

			// 订单的 ids
			String[] ids = unifiedCustomerCreateDimOrderParam.getIds().split(",");

			if (ids.length == 0) {
				result.setSuccess(false);
				result.setMessage("您没有选择订单！");
				return result;
			}

//			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//			Date starDate = sdf.parse(unifiedCustomerCreateDimOrderParam.getStartTime());
//			Date endDate  = sdf.parse(unifiedCustomerCreateDimOrderParam.getEndTime());

			Map<String, Object> queryMap = new HashMap<>();
			queryMap.put("ids", ids);

			List<UnifiedOrder> unifiedOrderList = unifiedOrderDubboConsumerService.findAll(queryMap, getToken());


			/****************************************** TODO 重构 mark by linjinyu at 202012242024 start ******************************************/
			Long enterpriseId = unifiedOrderList.get(0).getPurchaseVirtId();

			if (enterpriseId == null) {
				result.setSuccess(false);
				result.setMessage("订单无企业信息,无法对账！");
				return result;
			}

			double dzMoney = 0;

			for (UnifiedOrder unifiedOrder : unifiedOrderList) {

				dzMoney += unifiedOrder.getAmount().doubleValue();

				if (unifiedOrder.getAccountingStateCustomer().equals(1)) {
					result.setSuccess(false);
					result.setMessage("订单存在已对账,请重新生成！");
					return result;
				}

				if (!enterpriseId.equals(unifiedOrder.getPurchaseVirtId())) {
					result.setSuccess(false);
					result.setMessage("订单不是同一企业！");
					return result;
				}
			}

			unifiedCustomerCreateDimOrderParam.setDzMoney(new BigDecimal(dzMoney));
			/****************************************** TODO 重构 mark by linjinyu at 202012242024   end ******************************************/

			AccountingUnifiedCustomer accountingUnifiedCustomer = accountingUnifiedCustomerDubboConsumerService.opCreateAccountingDimOrder(getToken(), unifiedOrderList, unifiedCustomerCreateDimOrderParam);

			if (accountingUnifiedCustomer.getId() > 0) {

				result.setSuccess(true);
				result.setData(accountingUnifiedCustomer);

				Map<String, Object> headMap = new HashMap<>();

				headMap.put("encrypt_id", SuperdeskUniorderRsaUtils.encode(accountingUnifiedCustomer.getId().toString()));

				result.setHeadData(headMap);

			} else {

				result.setSuccess(false);
				result.setMessage("创建对账单失败！");

			}

		} catch (Exception e) {

			result.setSuccess(false);
			result.setMessage(ResponseMsgConstants.ERROR_UNKNOW);
			log.error(ExceptionUtils.getMessage(e));
			e.printStackTrace();
		}

		return result;
	}


	/**
	 * 客户结算-对账单-对账单详情 opt 发送邮件
	 * <p>
	 * <p>
	 * 发送对账单邮件-更新二维码地址
	 * <p>
	 * TODO 正解?20200630 彩娇说目前是用这个
	 *
	 * @param id
	 * @param toEmailAddress
	 * @param WxQRCodeUrl
	 * @param htmlContent
	 * @return
	 */
	@ApiOperation(value = "客户结算 -> 对账单-对账单详情 opt 发送邮件")
	@SuppressWarnings("restriction")
	@RequestMapping(value = "/sendEmailAndUpdate", method = RequestMethod.POST)
	@ResponseBody
	public R<AccountingUnifiedCustomer> sendEmailAndUpdate(Long id, String toEmailAddress, String WxQRCodeUrl, String htmlContent, int sendWxQRCode) {


		log.info("客户结算-对账单-对账单详情 opt 发送邮件 params-id            : {}", id);
		log.info("客户结算-对账单-对账单详情 opt 发送邮件 params-toEmailAddress: {}", toEmailAddress);
		log.info("客户结算-对账单-对账单详情 opt 发送邮件 params-WxQRCodeUrl   : {}", WxQRCodeUrl);
		log.info("客户结算-对账单-对账单详情 opt 发送邮件 params-sendWxQRCode  : {}", sendWxQRCode);


		R<AccountingUnifiedCustomer> result = new R<>();

		if (StringUtils.isBlank(toEmailAddress)) {
			return ResponseResultOuterUtils.createErrorResult("500", "邮箱地址不能为空");
		}

		try {

			if (StringUtils.isNotEmpty(WxQRCodeUrl)) {
				AccountingUnifiedCustomer dzMain = new AccountingUnifiedCustomer();
				dzMain.setId(id);
				dzMain.setWxQrcodeImgurl(WxQRCodeUrl);
				accountingUnifiedCustomerDubboConsumerService.updateObj(getToken(), dzMain);
			}

//			CustomerStatementOfAccountDetailVo dzMainDetail = accountingUnifiedCustomerDubboConsumerService.getCustomerStatementOfAccountDetailDimOrder2Goods(id);

			// TODO 20210223_功能测试_发现缺失兼容_客户结算_对账单_对账单详情_opt导出报表.md
			AccountingUnifiedCustomer accountingUnifiedCustomer = accountingUnifiedCustomerDubboConsumerService.findById(id);

			CustomerStatementOfAccountDetailVo customerStatementOfAccountDetailVo = null;

			if (null != accountingUnifiedCustomer) {
				switch (AccountingOrderDimCreateByEnum.get(accountingUnifiedCustomer.getDimCreateBy())) {
					case 订单:
						customerStatementOfAccountDetailVo = accountingUnifiedCustomerDubboConsumerService.getCustomerStatementOfAccountDetailDimOrder2Goods(id);
						break;
					case 商品:
						customerStatementOfAccountDetailVo = accountingUnifiedCustomerDubboConsumerService.getCustomerStatementOfAccountDetailDimGoods2Goods(id);
						break;
					case 流水:
						break;
					default:
						break;
				}
			}

			// 优化一下这个解决 如果这个对账单是 已拒绝 也是找不到的
			if (null == customerStatementOfAccountDetailVo) {
				result.setSuccess(false);
				result.setMessage("对账单信息为空,请先选择对账单！");
				return result;
			}


			// 利用 Thymeleaf 模板构建 html 文本
			Context templateEngineContext = new Context();
			// 给模板的参数的上下文
			templateEngineContext.setVariable("emailParam", customerStatementOfAccountDetailVo);
			// 执行模板引擎,执行模板引擎需要传入模板名、上下文对象
			// Thymeleaf的默认配置期望所有HTML文件都放在 **resources/templates ** 目录下,以.html扩展名结尾。
			// String emailText = templateEngine.process("email/templates", ctx);
			htmlContent = templateEngine.process("mail", templateEngineContext);


//			result.setSuccess(true);
//			result.setMessage(htmlContent);
//
//			return result;

			// TODO 20200709 清理过
			HSSFWorkbook workbook = ExcelExportAccountingOrderDetailUtils.unified(customerStatementOfAccountDetailVo);


			/****************************************** 生成附件 地址问题 start ******************************************/
			// 生成附件
			SysConfig emailConfig = sysConfigDubboConsumerService.findByCode("EMAIL");
//
//			String tmpFileFullPath = dzfilepath + customerStatementOfAccountDetailVo.getAccountingOrderSn() + ".xls";


			/****************************************** 生成附件 地址问题   end ******************************************/

			/****************************************** 生成附件 新地址 start ******************************************/

			String accountingOrderSn = customerStatementOfAccountDetailVo.getAccountingOrderSn();

			ResourceConstant excelExportConstant = providerEnvConstantDubboCustomerService.getResourceConstant();

			String excelExportPathRoot             = excelExportConstant.getPathRoot();
			String excelExportRelativePathTemplate = excelExportConstant.getPathTemplate();
			String excelExportRelativePathStorage  = excelExportConstant.getPathStorage();

			String relativePath = File.separator + "excel" + File.separator + "accounting" + File.separator + "unified" + File.separator + "customer" + File.separator;

			String targetFullPath          = excelExportPathRoot + excelExportRelativePathStorage;
			String targetFileName          = "客户结算_" + "电子对账单_" + accountingOrderSn + ExcelResponse.addTail() + ".xlsx";
			String targetWriteFileFullPath = targetFullPath + relativePath + targetFileName;


			FileUtil.touch(targetWriteFileFullPath);

//			if (!FileUtil.exist(targetFullPath)) {
//				FileUtil.mkdir(targetFullPath);
//			}

			/****************************************** 生成附件 新地址   end ******************************************/


			FileOutputStream fos = new FileOutputStream(new File(targetWriteFileFullPath));
			workbook.write(fos);
			workbook.close();
			fos.close();
			SimpleDateFormat sdfm = new SimpleDateFormat("yyyy年MM月");
			SimpleDateFormat sdfd = new SimpleDateFormat("yyyy年MM月dd日");

			String tilte = "超级前台-" + customerStatementOfAccountDetailVo.getAccountingOrderSn() + "-" + (customerStatementOfAccountDetailVo.getEnterpriseName()) + "." + sdfd.format(customerStatementOfAccountDetailVo.getStartTime()) + "-" + sdfd.format(customerStatementOfAccountDetailVo.getEndTime()) + "对账单";


			// TODO 好像没什么用
//			Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

			final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
			// 设置邮件会话参数
			Properties props = new Properties();
			// 邮箱的发送服务器地址
			props.setProperty("mail.smtp.host", emailConfig.getValueStr1());
			props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
			props.setProperty("mail.smtp.socketFactory.fallback", "false");
			// 邮箱发送服务器端口,这里设置为465端口
			props.setProperty("mail.smtp.port", emailConfig.getValueInt().toString());
			props.setProperty("mail.smtp.socketFactory.port", emailConfig.getValueInt().toString());
			props.put("mail.smtp.auth", "true");

			JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
			senderImpl.setHost(emailConfig.getValueStr1());
			senderImpl.setPort(465);
			senderImpl.setUsername(emailConfig.getValueStr2());
			senderImpl.setPassword(emailConfig.getValueStr3());
			senderImpl.setDefaultEncoding("UTF-8");
			Properties           prop = new Properties();
			MailSSLSocketFactory sf   = new MailSSLSocketFactory();
			sf.setTrustAllHosts(true);
			prop.put("mail.smtp.ssl.enable", "true");
			prop.put("mail.smtp.ssl.socketFactory", sf);
			prop.put("mail.smtp.auth", "true");
			prop.put("mail.smtp.timeout", "80000");
			senderImpl.setJavaMailProperties(prop);
			MimeMessage       mail   = senderImpl.createMimeMessage();
			MimeMessageHelper helper = new MimeMessageHelper(mail, true, "UTF-8");
			helper.setTo(toEmailAddress.split(",")[0]); // 收件人
			if (toEmailAddress.split(",").length > 1) {
				String[]     Ccs = toEmailAddress.split(",");
				List<String> ls  = new ArrayList<>();
				for (int i = 1; i < Ccs.length; i++) {
					ls.add(Ccs[i]);
				}
				// 抄送
				helper.setCc(ls.toArray(new String[ls.size()]));
			}


			helper.setFrom(emailConfig.getValueStr2()); // 发件人

			FileSystemResource file = new FileSystemResource(new File(targetWriteFileFullPath));
//			helper.addAttachment(customerStatementOfAccountDetailVo.getAccountingOrderSn() + ".xls", file);
			helper.addAttachment(targetFileName, file);

			if (StringUtils.isNotEmpty(WxQRCodeUrl)) {
				URL        url        = new URL(WxQRCodeUrl);
				DataSource dataSource = new URLDataSource(url);
				helper.addAttachment(MimeUtility.encodeText("微信支付二维码.png"), dataSource);
			}

			// 保存至收件箱start
			helper.setSubject(tilte);
			helper.setText(htmlContent, true);
			senderImpl.send(mail);

		} catch (Exception e) {

			result.setSuccess(false);
			result.setMessage("发送邮件失败,请联系管理员！");

			log.error(ExceptionUtils.getMessage(e));
			e.printStackTrace();
		}

		return result;
	}

	/**
	 * @param tranAmountLs
	 * @param item
	 * @return
	 */
	private boolean checkExist(List<UnifiedOrderJoinGoodsDetailVo> tranAmountLs, UnifiedOrderJoinGoodsDetailVo item) {

		for (UnifiedOrderJoinGoodsDetailVo unifiedOrderDetail : tranAmountLs) {
			if (item.getOrderSn().equals(unifiedOrderDetail.getOrderSn())) {
				return true;
			}
		}

		return false;
	}


}
