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

import cn.hutool.core.date.DateUtil;
import cn.superdesk.uniorder.common.constants.ResponseMsgConstants;
import cn.superdesk.uniorder.common.excel.ExcelResponse;
import cn.superdesk.uniorder.common.exception.utils.ExceptionUtils;
import cn.superdesk.uniorder.common.numerical.AnDateHelper;
import cn.superdesk.uniorder.common.rest.response.R;
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.sys.SysConfig;
import cn.superdesk.uniorder.dao.entity.sys.SysOrder;
import cn.superdesk.uniorder.dto.param.accounting.unified.customer.UnifiedCustomerCreateDimOrderParam;
import cn.superdesk.uniorder.dto.vo.accounting.unified.customer.*;
import cn.superdesk.uniorder.dto.vo.accounting.unified.customer.statement.CustomerStatementOfAccountDetailVo;
import cn.superdesk.uniorder.dto.vo.sys.EmailSend;
import cn.superdesk.uniorder.dto.vo.sys.SysOrderQuery;
import cn.superdesk.uniorder.dubbo.consumer.accounting.customer.AccountingUnifiedCustomerDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.sys.SysConfigDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.sys.SysInvDubboConsumerService;
import com.sun.mail.util.MailSSLSocketFactory;
import io.swagger.annotations.Api;
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.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

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.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;


@Api(value = "", tags = "")
@Slf4j
@RestController
@RequestMapping("/dzmain")
public class SysOldCustomerNotYetController extends BaseController {

	@Autowired
	private AccountingUnifiedCustomerDubboConsumerService accountingUnifiedCustomerDubboConsumerService;
	@Autowired
	private SysConfigDubboConsumerService                 sysConfigDubboConsumerService;
	@Autowired
	private SysInvDubboConsumerService                    sysInvDubboConsumerService;
	@Autowired
	private JavaMailSender                                javaMailSender;

	@Value("${spring.mail.username}")
	private String fromEmail;
	@Value("${me.email.dzpath}")
	private String dzfilepath;


	/**
	 * 返回 对账列表-分页
	 *
	 * @return
	 */
	@PostMapping("/findViewByPage")
	@ResponseBody
	public R<List<DzMainAutoPage>> findViewByPage() {

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

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

			// 时间类型
			if (StringUtils.isNotEmpty(getString("dateType"))) {
				params.put("dateType", Byte.valueOf(getString("dateType")));
			}

			// 企业名称
			params.put("enterpriseName", getString("enterpriseName"));

			// 操作时间
			params.put("startTime", getString("startTime"));
			params.put("endTime", getString("endTime"));

			result = accountingUnifiedCustomerDubboConsumerService.findAllViewPage(getToken(), params, getPageNum(), getPageSize());

		} catch (Exception e) {

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

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

		return result;
	}

	/**
	 * TODO OLD
	 * 返回 未对账订单列表-分页
	 *
	 * @return
	 */
	@PostMapping("/findNotDzOrderByPage")
	@ResponseBody
	public R<List<ViewSysOrder>> findNotDzOrderByPage() {
		R<List<ViewSysOrder>> result = new R<>();
		try {
			Map<String, Object> params = new HashMap<>();

			params.put("isGenBill", Byte.valueOf("0"));

			// dateType 1-发货时间,2-下单时间,3-完成时间
			if (StringUtils.isNotEmpty(getString("dateType"))) {
				params.put("dateType", Byte.valueOf(getString("dateType")));
			}

			if (StringUtils.isNotEmpty(getString("orderType"))) {
				params.put("orderType", getString("orderType"));
			}

			params.put("enterpriseName", getString("enterpriseName"));
			params.put("companyName", getString("companyName"));
			params.put("merchName", getString("merchName"));
			params.put("realname", getString("realname"));
			params.put("addressRealname", getString("addressRealname"));
			params.put("myOrdersn", getString("myOrdersn"));
			params.put("price", getString("price"));

			params.put("startTime", getString("startTime"));
			params.put("endTime", getString("endTime"));

			if (StringUtils.isNotEmpty(getString("orderStatus"))) {
				params.put("orderStatus", Byte.valueOf(getString("orderStatus")));
			}

			result = accountingUnifiedCustomerDubboConsumerService.findOrderViewPage(getToken(), params, getPageNum(), getPageSize());

		} catch (Exception e) {

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

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

		}

		return result;
	}

	/***
	 * TODO OLD
	 * 导出未对账订单列表
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/getNotDzOrderExcel")
	public void getNotDzOrderExcel(HttpServletResponse response) throws IOException {


		try {

			/****************************************** 处理条件 start ******************************************/
			Map<String, Object> params = new HashMap<>();

			params.put("isGenBill", Byte.valueOf("0"));

			// dateType 1-发货时间,2-下单时间,3-完成时间
			if (StringUtils.isNotEmpty(getString("dateType"))) {
				params.put("dateType", Byte.valueOf(getString("dateType")));
			}

			if (StringUtils.isNotEmpty(getString("orderType"))) {
				params.put("orderType", getString("orderType"));
			}

			params.put("enterpriseName", getString("enterpriseName"));
			params.put("companyName", getString("companyName"));
			params.put("merchName", getString("merchName"));
			params.put("realname", getString("realname"));
			params.put("addressRealname", getString("addressRealname"));
			params.put("myOrdersn", getString("myOrdersn"));
			params.put("price", getString("price"));

			params.put("startTime", getString("startTime"));
			params.put("endTime", getString("endTime"));

			if (StringUtils.isNotEmpty(getString("orderStatus"))) {
				params.put("orderStatus", Byte.valueOf(getString("orderStatus")));
			}

			/****************************************** 取得数据 start ******************************************/

			List<ExpSysOrder> dataList = accountingUnifiedCustomerDubboConsumerService.findOrderViewExcel(getToken(), params);

			/****************************************** 数据合成 start ******************************************/
			String[] field = {"parentOrdersn", "", "ordersn", "organizationName", "enterpriseName", "price", "paytypeName", "statusName", "realname",
					"mobile", "addressAddress", "createtime", "merchName", "remark", "", "otherField1", "taxCode", "optionname", "total", "unitPrice",
					"totalPrice", "unit", "taxCode", "addressRealname", "addressMobile", "invoicetype", "sendtime", "dispatchPrice", "", "", "finishtime", "", "", "", "", ""
			};

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


			// TODO 待删除 mark by lionjinyu at 20210203
//			HSSFWorkbook workbook = ExcelExportModePoiHssfUtils.createWorkbook(dataList, fieldZhCn, field, "未对账订单");
//
//			/****************************************** 输出 start ******************************************/
//
//			response.reset();
//			// 准备将Excel的输出流通过response输出到页面下载
//			// 二进制输出流
//			response.setContentType("application/octet-stream");
//			response.setCharacterEncoding("UTF-8");
//			// 这后面可以设置导出Excel的名称
//			response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("未对账订单", "UTF-8") + ".xls");
//			// 刷新缓冲
//			response.flushBuffer();
//
//			// workbook将Excel写入到response的输出流中,供页面下载
//			workbook.write(response.getOutputStream());

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

		} catch (Exception e) {

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


	}


	/**
	 * TODO OLD
	 * 未对账订单 详细-创建订单-json结构
	 *
	 * @return
	 */
	@PostMapping("/findNotDzOrderDetail")
	@ResponseBody
	public R<List<ViewSysOrderGoods>> findNotDzOrderDetail(SysOrderQuery query) {

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

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

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

//			Map<String, Object> params=new HashMap<>();
//			params.put("orderIds", orderIds);
//			params.put("isGenBill", Byte.valueOf("0"));

			query.setIsGenBill(0);
			query.setOrderIds(orderIds);

			List<ViewSysOrderGoods> ls = accountingUnifiedCustomerDubboConsumerService.findOrderViewGoods(getToken(), query);

			result.setData(ls);

		} catch (Exception e) {

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

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

	/**
	 * TODO OLD
	 * 未对账订单-详细
	 * 供应商结算 未对账订单 创建对账单 预览
	 *
	 * @return
	 */
	@PostMapping("/findNotDzOrderDetailTb")
	@ResponseBody
	public R<List<ViewSysOrderJoinGoods>> findNotDzOrderDetailTb(String ids) {

		R<List<ViewSysOrderJoinGoods>> 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("orderIds", orderIds);
			params.put("isGenBill", Byte.valueOf("0"));
			List<ViewSysOrderJoinGoods> ls = accountingUnifiedCustomerDubboConsumerService.findOrderViewGoodsTb(getToken(), params);

			result.setData(ls);

		} catch (Exception e) {

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

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

		return result;
	}

	/**
	 * TODO OLD
	 * 未对账订单 头部数据
	 *
	 * @param
	 * @return
	 */
	@PostMapping("/getNotDzShowData")
	@ResponseBody
	public R<ReportOrderQA> getNotDzShowData() {

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

		try {

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

			params.put("isGenBill", Byte.valueOf("0"));

			//dateType 1-发货时间,2-下单时间,3-完成时间
			if (StringUtils.isNotEmpty(getString("dateType"))) {
				params.put("dateType", Byte.valueOf(getString("dateType")));
			}

			if (StringUtils.isNotEmpty(getString("orderType"))) {
				params.put("orderType", getString("orderType"));
			}

			params.put("enterpriseName", getString("enterpriseName"));
			params.put("companyName", getString("companyName"));
			params.put("merchName", getString("merchName"));
			params.put("realname", getString("realname"));
			params.put("addressRealname", getString("addressRealname"));
			params.put("myOrdersn", getString("myOrdersn"));
			params.put("price", getString("price"));
			params.put("startTime", getString("startTime"));
			params.put("endTime", getString("endTime"));

			if (StringUtils.isNotEmpty(getString("orderStatus"))) {
				params.put("orderStatus", Byte.valueOf(getString("orderStatus")));
			}

			ReportOrderQA reportQA = accountingUnifiedCustomerDubboConsumerService.getReportOrder(getToken(), params);

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

		} catch (Exception e) {

			result.setSuccess(false);
			result.setMessage(ResponseMsgConstants.ERROR_UNKNOW);

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

		return result;
	}


	/**
	 * TODO OLD
	 * 客户结算 > 创建对账单
	 * TODO 旧版 对账单创建 弃用?
	 * <p>
	 * 从前端看 ---- createdz:'/web/ucustomer/createdz',//创建对账单-确认 才是新版 创建对账单
	 * <p>
	 * 两个创建对账单分别到了客户与供供应商那了
	 *
	 * @param
	 * @return
	 */
	@Deprecated
	@SuppressWarnings("restriction")
	@PostMapping("/create")
	@ResponseBody
	public R<AccountingUnifiedCustomer> createProduce(UnifiedCustomerCreateDimOrderParam model) {

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

		try {

			// 未对账订单 ids
			String[] ids = model.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(model.getStartTime());
//			Date             endDate  = sdf.parse(model.getEndTime());

			Map<String, Object> queryMap = new HashMap<>();
			queryMap.put("ids", ids);
			List<SysOrder> orders = accountingUnifiedCustomerDubboConsumerService.findAllFromOrder(getToken(), queryMap);

			Long enterpriseId = orders.get(0).getEnterpriseId();
			//Integer realnameId = orders.get(0).getRealnameId();

			for (SysOrder sysOrder : orders) {

				Boolean timeCheck = true;

				if (model.getDateType() == 1) {
					//发货时间
					if (sysOrder.getSendtime().getTime() < model.getStartTime().getTime() ||
							sysOrder.getSendtime().getTime() > model.getEndTime().getTime()) {
						timeCheck = false;
					}
				} else if (model.getDateType() == 2) {
					if (sysOrder.getCreatetime().getTime() < model.getStartTime().getTime() ||
							sysOrder.getCreatetime().getTime() > model.getEndTime().getTime()) {
						timeCheck = false;
					}
				} else {
					if (sysOrder.getFinishtime().getTime() < model.getStartTime().getTime() ||
							sysOrder.getFinishtime().getTime() > model.getEndTime().getTime()) {
						timeCheck = false;
					}
				}

				if (!timeCheck) {
					result.setSuccess(false);
					result.setMessage("时间周期与所选订单不匹配,请重新生成！");
					return result;
				}
				if (sysOrder.getIsGenBill() == 1) {
					result.setSuccess(false);
					result.setMessage("订单存在已对账,请重新生成！");
					return result;
				}
				if (!enterpriseId.equals(sysOrder.getEnterpriseId())) {
					result.setSuccess(false);
					result.setMessage("订单不是同一企业！");
					return result;
				}
//				if(!realnameId.equals(item.getRealnameId())) {
//					result.setSuccess(false);
//					result.setMessage("订单不是同一下单人！");
//					return result;
//				}
			}
			AccountingUnifiedCustomer dzMain = accountingUnifiedCustomerDubboConsumerService.createProduce(
					getToken(),
					orders,
					DateUtil.format(model.getStartTime(), AnDateHelper.DATE_TIME_STRING),
					DateUtil.format(model.getEndTime(), AnDateHelper.DATE_TIME_STRING),
					model.getDateType(),
					model.getIsSendEmail()
			);

			if (dzMain.getId() > 0) {

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

				if (model.getIsSendEmail().equals(1)) {

					CustomerStatementOfAccountDetailVo dzMainDetail = accountingUnifiedCustomerDubboConsumerService.getCustomerStatementOfAccountDetailDimOrder2Goods(dzMain.getId());

					if (StringUtils.isEmpty(model.getEmailAddress()) && StringUtils.isEmpty(dzMainDetail.getBillEmail())) {

						result.setSuccess(false);
						result.setMessage("创建对账单成功,但是下单人无邮箱信息,无法发送邮件！");
						return result;

					}

					String toEmailAddress = dzMainDetail.getBillEmail();
					if (!StringUtils.isEmpty(model.getEmailAddress())) {
						toEmailAddress = model.getEmailAddress();
					}

					// TODO 20200709 清理过 135-20070078
					HSSFWorkbook workbook = ExcelExportAccountingOrderDetailUtils.unified(dzMainDetail);

					//生成附件
					SysConfig        emailConfig = sysConfigDubboConsumerService.findByCode("EMAIL");
					String           fullpath    = dzfilepath + dzMainDetail.getAccountingOrderSn() + dzMainDetail.getEnterpriseName() + ".xls";
					FileOutputStream fos         = new FileOutputStream(new File(fullpath));
					workbook.write(fos);
					workbook.close();
					fos.close();
					SimpleDateFormat sdfm = new SimpleDateFormat("yyyy年MM月");
					SimpleDateFormat sdfd = new SimpleDateFormat("yyyy年MM月dd日");
					String tilte = "超级前台——" + dzMainDetail.getAccountingOrderSn() + "-" + dzMainDetail.getEnterpriseName() + "." +
							sdfd.format(dzMainDetail.getStartTime()) + "-" + sdfd.format(dzMainDetail.getEndTime()) + "对账单";
					String content = "尊敬的客户:\r\n" +
							" 以下是贵单位" + sdfm.format(dzMainDetail.getStartTime()) + "采购订单,请协助核对确认,如有疑问,请随时回复邮件,或者拨打电话 。此电子版对账单作为结算依据,请在三个工作日内核对并邮件回复核对结果" +
							"\r\n——正确无误的请回复`正确无异议`;同时请协助告知开票要求,如无要求,默认账单开一张发票,如有开票要求(例如拆分开票,发票抬头等),请协助邮件告知,谢谢！" +
							"\r\n——如有异议的请协助回复邮件或者电话19926590027沟通账单异议地方" +
							"\r\n超时未回复则默认项目对账单无异议,平台按此开票,如账单无误,请收到发票后于五个工作日内提交财务请款,非常感谢。";
					//邮件内容:
//					尊敬的客户:
//					以下是贵单位2019年03月采购订单,请协助核对确认,如有疑问,请随时回复邮件,或者拨打电话。此电子版对账单作为结算依据,请在三个工作日内核对并邮件回复核对结果
//					——正确无误的请回复"正确无异议";同时请协助告知开票要求,如无要求,默认账单开一张发票,如有开票要求(例如拆分开票,发票抬头等),请协助邮件告知,谢谢！
//					——如有异议的请协助回复邮件或者电话19926590027沟通账单异议地方
//					超时未回复则默认项目对账单无异议,平台按此开票,如账单无误,请收到发票后于五个工作日内提交财务请款,非常感谢。

//					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); // 收件人

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

					FileSystemResource file  = new FileSystemResource(new File(fullpath));
					String             fname = (dzMainDetail.getEnterpriseName() + ".xls");
					helper.addAttachment(dzMainDetail.getAccountingOrderSn() + MimeUtility.encodeText(fname), file);

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


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

		} catch (Exception e) {

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

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

	/**
	 * TODO OLD
	 * 对账 单头部 数据
	 *
	 * @param
	 * @return
	 */
	@PostMapping("/getDzShowData")
	@ResponseBody
	public R<ReportOrderQA> getDzShowData() {
		R<ReportOrderQA> result = new R<>();
		try {

			Map<String, Object> params = new HashMap<>();
			if (StringUtils.isNotEmpty(getString("dateType"))) {
				params.put("dateType", Byte.valueOf(getString("dateType")));
			}

			params.put("dzSn", getString("dzSn"));
			params.put("enterpriseName", getString("enterpriseName"));
			params.put("companyName", getString("companyName"));
			//params.put("merchName", getString("merchName"));
			params.put("realname", getString("realname"));
			params.put("startTime", getString("startTime"));
			params.put("endTime", getString("endTime"));
			if (StringUtils.isNotEmpty(getString("dzStatus"))) {
				params.put("dzStatus", Byte.valueOf(getString("dzStatus")));
			}
			if (StringUtils.isNotEmpty(getString("dzInvstatus"))) {
				params.put("dzInvstatus", Byte.valueOf(getString("dzInvstatus")));
			}
			ReportOrderQA reportQA = accountingUnifiedCustomerDubboConsumerService.getDzReportOrder(getToken(), params);
			result.setSuccess(true);
			result.setData(reportQA);
		} catch (Exception e) {

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

	/**
	 * TODO OLD
	 * 客户结算-对账单列表-分页
	 *
	 * @param
	 * @return
	 */
	@PostMapping("/getDzMainViewByPage")
	@ResponseBody
	public R<List<CustomerStatementOfAccountDetailVo>> getDzMainViewByPage() {
		R<List<CustomerStatementOfAccountDetailVo>> result = new R<>();
		try {
			Map<String, Object> params = new HashMap<>();
			if (StringUtils.isNotEmpty(getString("dateType"))) {
				params.put("dateType", Byte.valueOf(getString("dateType")));
			}

			params.put("dzSn", getString("dzSn"));
			params.put("enterpriseName", getString("enterpriseName"));
			params.put("companyName", getString("companyName"));
			if (StringUtils.isNotEmpty(getString("isEmail"))) {
				params.put("isEmail", Byte.valueOf(getString("isEmail")));
			}

			params.put("realname", getString("realname"));
			params.put("startTime", getString("startTime"));
			params.put("endTime", getString("endTime"));
			if (StringUtils.isNotEmpty(getString("dzStatus"))) {
				params.put("dzStatus", Byte.valueOf(getString("dzStatus")));
			}
			if (StringUtils.isNotEmpty(getString("dzInvstatus"))) {
				params.put("dzInvstatus", Byte.valueOf(getString("dzInvstatus")));
			}
			result = accountingUnifiedCustomerDubboConsumerService.getDzMainViewByPage(getToken(), params, getPageNum(), getPageSize());

		} catch (Exception e) {

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


	/**
	 * 返回订单列表-分页
	 * @param role
	 * @return
	 */
//	@PostMapping("/getOrderViewByPage")
//	@ResponseBody
//	public ResponseResult<List<ViewSysOrderGoods>> getOrderViewByPage(SysOrderQuery query){
//		ResponseResult<List<ViewSysOrderGoods>> result = new ResponseResult<>();
//		//Date dts = DateUtil.date();
//		try {
//
//			//System.out.println(dts.getTime());
//
//			result = mainDubboService.getOrderViewByPage(getToken(), query, getPageNum(), getPageSize());
//
//		} catch (Exception e) {
//
//			result.setSuccess(false);
//			result.setMessage(ResponseMsgConstants.ERROR_UNKNOW);
//			log.error(ExceptionUtils.getMessage(e));
//e.printStackTrace();
//		}
//		return result;
//	}

	/**
	 * 返回订单列表-分页
	 *
	 * @param query
	 * @return
	 */
	@PostMapping("/getOrderViewByPage")
	@ResponseBody
	public R<List<ExpSysOrder>> getOrderViewByPage(SysOrderQuery query) {
		R<List<ExpSysOrder>> result = new R<>();
		try {
			result = accountingUnifiedCustomerDubboConsumerService.getOrderViewByPage(getToken(), query, getPageNum(), getPageSize());
		} catch (Exception e) {

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

	/**
	 * 返回订单列表-分页-项目用19-0710
	 *
	 * @param query
	 * @return
	 */
	@PostMapping("/getOrderViewByPageProject")
	@ResponseBody
	public R<List<ExpSysOrder>> getOrderViewByPageProject(SysOrderQuery query) {
		R<List<ExpSysOrder>> result = new R<>();
		try {
			result = accountingUnifiedCustomerDubboConsumerService.getOrderViewByPageProject(getToken(), query, getPageNum(), getPageSize());
		} catch (Exception e) {

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


	/***
	 * 导出订单列表
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/getOrderViewExcel")
	public void getOrderViewExcel(HttpServletResponse response) throws IOException {
		try {

			SysOrderQuery query = new SysOrderQuery();
			query.setGetDD(getString("getDD"));

			query.setMyOrdersn(getString("myOrdersn"));
			query.setOrdersn(getString("ordersn"));
			query.setParentOrderSn(getString("parentOrdersn"));
			query.setEnterpriseName(getString("enterpriseName"));
			query.setEnterpriseId(getLong("enterpriseId"));
			query.setDispatchname(getString("dispatchname"));
			if (!StringUtils.isEmpty(getString("dateType"))) {
				query.setDateType(Integer.valueOf(getString("dateType")));
			}
			query.setStartTime(getString("startTime"));
			query.setEndTime(getString("endTime"));
			query.setRealname(getString("realname"));
			query.setMobile(getString("mobile"));
			query.setAddressRealname(getString("addressRealname"));

			query.setAddressMobile(getString("addressMobile"));
			query.setAddressAddress(getString("addressAddress"));
			query.setMerchName(getString("merchName"));

			if (!StringUtils.isEmpty(getString("serviceName"))) {
				query.setServiceName(getString("serviceName"));
			}

			if (!StringUtils.isEmpty(getString("paytype"))) {
				query.setPayType(Integer.valueOf(getString("paytype")));
			}

			if (!StringUtils.isEmpty(getString("isGenBill"))) {
				query.setIsGenBill(Integer.valueOf(getString("isGenBill")));
			}

			List<ExpSysOrder> dataList = accountingUnifiedCustomerDubboConsumerService.getOrderViewExcel(getToken(), query);

			String[] field = {"parentOrdersn", "", "ordersn", "organizationName", "enterpriseName", "price", "paytypeName", "statusName", "realname",
					"mobile", "addressAddress", "createtime", "merchName", "remark", "", "otherField1", "taxCode", "optionname", "total", "unitPrice",
					"totalPrice", "unit", "taxCode", "addressRealname", "addressMobile", "sendtime", "dispatchPrice", "companyName", "expressNo", "finishtime", "", "invoiceNumber", "invoiceTime", "invoiceStatusName", "", "invoiceCompanyName", "invoicetypeName"
			};

			String[] fieldZhCn = {"父单编号", "父单金额", "订单编号", "会员所属项目", "会员所属企业(动态)", "订单金额", "支付方式", "订单状态", "下单人姓名",
					"下单人电话", "收货地址", "下单时间", "供应商名称", "买家备注", "卖家备注", "商品信息", "商品编码", "商品规格", "商品数量", "商品单价(折扣后)",
					"商品价格(折扣后)", "商品单位", "财务代码", "收货人姓名", "收货人手机号", "发货时间", "运费", "快递公司", "快递单号", "完成时间", "回款状态", "发票号", "开票时间", "发票状态", "开票申请编号", "发票抬头", "发票种类"};

//			HSSFWorkbook workbook = ExcelExportModePoiHssfUtils.createWorkbook(dataList, fieldZhCn, field, "订单报表");
//			//准备将Excel的输出流通过response输出到页面下载
//			response.reset();
//			//二进制输出流
//			response.setContentType("application/octet-stream");
//			response.setCharacterEncoding("UTF-8");
//			//这后面可以设置导出Excel的名称,此例中名为student.xls
//			response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("订单报表", "UTF-8") + ".xls");
//			//刷新缓冲
//			response.flushBuffer();
//
//			//workbook将Excel写入到response的输出流中,供页面下载
//			workbook.write(response.getOutputStream());

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

		} catch (Exception e) {

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


	}

	/**
	 * 返回订单列表统计数据
	 *
	 * @param query
	 * @return
	 */
	@PostMapping("/getOrderShowData")
	@ResponseBody
	public R<ReportOrderQA> getOrderShowData(SysOrderQuery query) {
		R<ReportOrderQA> result = new R<>();
		try {

			ReportOrderQA data = accountingUnifiedCustomerDubboConsumerService.getOrderReportData(getToken(), query);
			result.setData(data);
			result.setSuccess(true);
		} catch (Exception e) {

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

	/**
	 * 返回订单列表统计数据--写死
	 *
	 * @param query
	 * @return
	 */
	@PostMapping("/getOrderShowDataDeath")
	@ResponseBody
	public R<ReportOrderQA> getOrderShowDataDeath(SysOrderQuery query) {

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

		try {

			ReportOrderQA data = accountingUnifiedCustomerDubboConsumerService.getOrderReportDataDeath(getToken(), query);
			result.setData(data);
			result.setSuccess(true);

		} catch (Exception e) {

			result.setSuccess(false);
			result.setMessage(ResponseMsgConstants.ERROR_UNKNOW);

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

		return result;
	}

	/**
	 * 发送邮件
	 *
	 * @param model
	 * @return
	 */
	@PostMapping("/sendEmail")
	@ResponseBody
	public R<?> sendEmail(EmailSend model) {

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

		try {
			String[] ids = model.getIds().split(",");

			for (int i = 0; i < ids.length; i++) {
				SysConfig                          emailConfig  = sysConfigDubboConsumerService.findByCode("EMAIL");
				CustomerStatementOfAccountDetailVo dzMainDetail = accountingUnifiedCustomerDubboConsumerService.getCustomerStatementOfAccountDetailDimOrder2Goods(Long.parseLong(ids[i]));

				if (StringUtils.isEmpty(model.getEmailAddress()) && StringUtils.isEmpty(dzMainDetail.getBillEmail())) {
					result.setSuccess(false);
					result.setMessage("下单人无邮箱信息,无法发送邮件！");
					return result;

				}
				String toEmailAddress = dzMainDetail.getBillEmail();
				if (!StringUtils.isEmpty(model.getEmailAddress())) {
					toEmailAddress = model.getEmailAddress();
				}

				// TODO 20200709 清理过
				HSSFWorkbook workbook = ExcelExportAccountingOrderDetailUtils.unified(dzMainDetail);
				//生成附件
				//dzfilepath = "E:/upload/";
				String           fullpath = dzfilepath + dzMainDetail.getAccountingOrderSn() + dzMainDetail.getEnterpriseName() + ".xls";
				FileOutputStream fos      = new FileOutputStream(new File(fullpath));
				workbook.write(fos);
				workbook.close();
				fos.close();
				SimpleDateFormat sdf  = new SimpleDateFormat("yyyy年MM月");
				SimpleDateFormat sdfd = new SimpleDateFormat("yyyy年MM月dd日");
				String tilte = "超级前台——" + dzMainDetail.getAccountingOrderSn() + "-" + dzMainDetail.getEnterpriseName() + "." +
						sdfd.format(dzMainDetail.getStartTime()) + "-" + sdfd.format(dzMainDetail.getEndTime()) + "对账单";
				String content = "尊敬的客户:\r\n" +
						" 以下是贵单位" + sdf.format(dzMainDetail.getStartTime()) + "采购订单,请协助核对确认,如有疑问,请随时回复邮件,或者拨打电话 。此电子版对账单作为结算依据,请在三个工作日内核对并邮件回复核对结果\r\n" +
						"——正确无误的请回复`正确无异议`;同时请协助告知开票要求,如无要求,默认账单开一张发票,如有开票要求(例如拆分开票,发票抬头等),请协助邮件告知,谢谢！\r\n" +
						"——如有异议的请协助回复邮件或者电话沟通账单异议地方\r\n" +
						"超时未回复则默认项目对账单无异议,平台按此开票,如账单无误,请收到发票后于五个工作日内提交财务请款,非常感谢。";

				switch (model.getSendType()) {
					case "simple":
						SimpleMailMessage message = new SimpleMailMessage();
						message.setFrom(emailConfig.getValueStr2());
						message.setTo(toEmailAddress);
						message.setSubject(tilte);
						message.setText(content);

						javaMailSender.send(message);
						break;
					case "subject":

						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); // 收件人

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

						FileSystemResource file = new FileSystemResource(new File(fullpath));
						String fname = (dzMainDetail.getEnterpriseName() + ".xls");
						helper.addAttachment(dzMainDetail.getAccountingOrderSn() + MimeUtility.encodeText(fname), file);

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

//					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");
//		            final String username = emailConfig.getValueStr2();
//		            final String password = emailConfig.getValueStr3();
//		            //获取到邮箱会话,利用匿名内部类的方式,将发送者邮箱用户名和密码授权给jvm
//		            Session session = Session.getDefaultInstance(props, new Authenticator() {
//		                protected PasswordAuthentication getPasswordAuthentication() {
//		                    return new PasswordAuthentication(username, password);
//		                }
//		            });
//		            //通过会话,得到一个邮件,用于发送
//		            MimeMessage mimeMessage = new MimeMessage(session);
//
//		            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true,"utf-8");
//
//
//		            helper.setFrom(emailConfig.getValueStr2());
//					helper.setTo(toEmailAddress);
//					helper.setSubject(tilte);
//					helper.setText(content);

						//调用Transport的send方法去发送邮件
						//Transport.send(mimeMessage);

						//更新对账单邮件发送时间
						accountingUnifiedCustomerDubboConsumerService.updateEmailTime(getToken(), Long.parseLong(ids[i]));
						//设置发件人
//		            msg.setFrom(new InternetAddress("13066855659@163.com"));
//		            //设置收件人,to为收件人,cc为抄送,bcc为密送
//		            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(dzMainDetail.getBillEmail(), false));
////		            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(to, false));
////		            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(to, false));
//		            msg.setSubject(tilte);
//		            //设置邮件消息
//		            msg.setText(content);
//		            //设置发送的日期
//		            msg.setSentDate(DateUtil.date());
//					MimeMessage mimeMessage = mailSender.createMimeMessage();
//
//					MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true,"utf-8");
//					helper.setFrom(fromEmail);
//					helper.setTo(dzMainDetail.getBillEmail());
//					helper.setSubject(tilte);
//					helper.setText(content);
//					FileSystemResource file = new FileSystemResource(new File(fullpath));
//					String fname = (dzMainDetail.getEnterpriseName()+".xls");
//					helper.addAttachment(dzMainDetail.getDzSn()+MimeUtility.encodeText(fname), file);
//
//					mailSender.send(mimeMessage);
						break;
					default:

						break;
				}
			}


			result.setSuccess(true);

		} catch (Exception e) {

			result.setSuccess(false);
			result.setMessage(e.getMessage());

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

	/**
	 * 对账单导出EXCEL
	 *
	 * @param response
	 * @return
	 */
	@RequestMapping("/excelTest")
	public R<?> excelTest(HttpServletResponse response) {
		R<?> result = new R<>();
		try {
			Map<String, Object> params = new HashMap<>();
			if (StringUtils.isNotEmpty(getString("dateType"))) {
				params.put("dateType", Byte.valueOf(getString("dateType")));
			}

			params.put("dzSn", getString("dzSn"));
			params.put("enterpriseName", getString("enterpriseName"));
			params.put("companyName", getString("companyName"));
			//params.put("merchName", getString("merchName"));
			params.put("realname", getString("realname"));
			params.put("startTime", getString("startTime"));
			params.put("endTime", getString("endTime"));
			if (StringUtils.isNotEmpty(getString("dzStatus"))) {
				params.put("dzStatus", Byte.valueOf(getString("dzStatus")));
			}
			if (StringUtils.isNotEmpty(getString("dzInvstatus"))) {
				params.put("dzInvstatus", Byte.valueOf(getString("dzInvstatus")));
			}
			List<CustomerStatementOfAccountDetailVo> dataList = accountingUnifiedCustomerDubboConsumerService.getDzMainView(getToken(), params);
			String[] fieldZhCn = {"金额", "数量", "id",
					"时间类型",
					"对账单号",
					"对账状态",
					"发票状态",
					"enterpriseId",
					"realnameId",
					"companyname",
					"taxpayersidcode",
					"invoicetype",
					"address",
					"isEmail",
					"emailTime",
					"startTime",
					"endTime",
					"backAccountStatus",
					"createTime",
					"createUserId",
					"updateTime",
					"updateUserId",
					"enterpriseName",
					"realname"};
			String[] field = {"dzMoney", "dzQuantity", "id",
					"dzDatetype",
					"dzSn",
					"dzStatus",
					"dzInvstatus",
					"enterpriseId",
					"realnameId",
					"companyname",
					"taxpayersidcode",
					"invoicetype",
					"address",
					"isEmail",
					"emailTime",
					"startTime",
					"endTime",
					"backAccountStatus",
					"createTime",
					"createUserId",
					"updateTime",
					"updateUserId",
					"enterpriseName",
					"realname"};

//			HSSFWorkbook workbook = ExcelExportModePoiHssfUtils.createWorkbook(ls, fieldZhCn, field, "对账单");
//			//准备将Excel的输出流通过response输出到页面下载
//			response.reset();
//			//二进制输出流
//			response.setContentType("application/octet-stream");
//
//			//这后面可以设置导出Excel的名称,此例中名为student.xls
//			response.setHeader("Content-disposition", "attachment;filename=student.xls");
//
//			//刷新缓冲
//			response.flushBuffer();
//
//			//workbook将Excel写入到response的输出流中,供页面下载
//			workbook.write(response.getOutputStream());

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

			result.setSuccess(true);
		} catch (Exception e) {

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


	/**
	 * 测试
	 *
	 * @param
	 * @return
	 */
	@PostMapping("/test")
	@ResponseBody
	public R<SysConfig> test() {
		R<SysConfig> result = new R<>();
		try {

			if (!StringUtils.isEmpty(getString("code"))) {
				SysConfig config = sysConfigDubboConsumerService.findByCode(getString("code"));
				result.setData(config);
			}
			result.setSuccess(true);
		} catch (Exception e) {

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

}
