package cn.superdesk.uniorder.controller.accounting.supplier.bak;


import cn.superdesk.uniorder.common.enums.common.CommonAccountingStateEnum;
import cn.superdesk.uniorder.common.excel.ExcelResponse;
import cn.superdesk.uniorder.common.exception.utils.ExceptionUtils;
import cn.superdesk.uniorder.common.json.JsonUtils;
import cn.superdesk.uniorder.common.rest.R;
import cn.superdesk.uniorder.controller.base.BaseController;
import cn.superdesk.uniorder.dao.entity.accounting.unified.supplier.AccountingUnifiedSupplier;
import cn.superdesk.uniorder.dto.param.accounting.unified.supplier.UnifiedSupplierCreateDimGoodsParam;
import cn.superdesk.uniorder.dto.vo.accounting.unified.supplier.notyet.SupplierUnAccountingDimGoodsVo;
import cn.superdesk.uniorder.dto.vo.accounting.unified.supplier.notyet.UnifiedOrderSupplierHeadSumVo;
import cn.superdesk.uniorder.dubbo.consumer.accounting.AccountingUnifiedSupplierDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.base.UnifiedOrderDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.unified.UnifiedSupplierDubboConsumerService;
import cn.superdesk.uniorder.utils.BeanUtils;
import cn.superdesk.uniorder.utils.CollectionUtils;
import cn.superdesk.uniorder.utils.numerical.AnStringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Api(value = "供应商对账(结算) - 未对账商品", tags = {"供应商对账(结算) - 未对账商品"})
@Slf4j
@RestController
@RequestMapping(value = "/accounting/unified/supplier/dim/goods/notyet")
public class UnifiedSupplierNotYetDimGoodsController extends BaseController {


	@Autowired
	private UnifiedOrderDubboConsumerService              unifiedOrderDubboConsumerService;
	@Autowired
	private UnifiedSupplierDubboConsumerService           unifiedSupplierDubboConsumerService;
	@Autowired
	private AccountingUnifiedSupplierDubboConsumerService accountingUnifiedSupplierDubboConsumerService;

	/**
	 * 供应商结算 - 未对账商品
	 *
	 * @return
	 * @url : http://order.avic-s.com/#/vendorUnreconOrder?id=71
	 * <p>
	 * /accounting/unified/supplier/dim/goods/notyet/getSupplierUnAccountingDimGoodsList
	 * <p>
	 * 未对账列表分页
	 * , tags = {""}
	 */
	@ApiOperation(value = "供应商对账(结算) - 未对账商品 - 维度 - 商品", notes = "前端新添加页面 - 测试正常")
	@RequestMapping(value = "/getSupplierUnAccountingDimGoodsList", method = RequestMethod.POST)
	@ResponseBody
	public R<List<SupplierUnAccountingDimGoodsVo>> getSupplierUnAccountingDimGoodsList() {

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

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

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

			// 业务系统的订单状态 不是统一订单的统一订单状态 mark by linjinyu at 20210305
			params.put("orderState", getInteger("orderState"));
			params.put("orderStateName", getString("orderStateName"));
			params.put("serviceNo", getString("serviceNo"));


			// 下单人 企业
			params.put("purchaseVirtId", getLong("purchaseVirtId"));
			params.put("purchaseVirtName", getString("purchaseVirtName"));

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

			// 订单金额 =
			params.put("amount", getString("amount"));

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

			params.put("accountingStateSupplier", CommonAccountingStateEnum.未对账.getKey());

			log.info("\n供应商对账(结算) - 未对账商品 - 维度 - 商品 - params {}\n", JsonUtils.toJson(params));

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

			UnifiedOrderSupplierHeadSumVo supplierUnAccountingDimGoodsHeadSum = unifiedOrderDubboConsumerService.getSupplierUnAccountingDimGoodsHeadSum(getToken(), params);

			result.setHeadData(BeanUtils.beanToMap(supplierUnAccountingDimGoodsHeadSum));

		} 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 导出报表 (未对账列表-导出)
	 *
	 * /accounting/unified/supplier/notyet/exportuaccountdata
	 *
	 * http://192.168.1.223:8089/web/accounting/unified/supplier/notyet/exportuaccountdata?orderIds=55032,55031&token=eyJhbGciOiJIUzI1NiJ9.eyJzYWxlaWQiOm51bGwsInZpcnRJZHMiOm51bGwsIm91dExvZ2luIjoiMCIsInVzZXJOYW1lIjoid2FuZ3N5Iiwicm9sZVR5cGUiOiIxIiwib2NpZCI6bnVsbCwiZXhwIjoxNjAxMDAwNzgyLCJ1c2VySWQiOiI2MCIsImlhdCI6MTYwMDkxNDM4Mn0.2L-ZP_c2fdgREcvSVMpLa_HWjoKCY0RLGFnx2BtJoiQ
	 * @return
	 */
	@ApiOperation(value = "供应商对账(结算) - 未对账商品 导出报表 - 维度 - 商品", notes = "未修改")
	@RequestMapping(value = "/exportSupplierUnAccountingDimGoodsList", method = RequestMethod.GET)
	public void exportSupplierUnAccountingDimGoodsList(HttpServletResponse response) throws IOException {

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

			String unifiedOrderGoodsIdsStr = getString("unifiedOrderGoodsIds");

			if (StringUtils.isNotBlank(unifiedOrderGoodsIdsStr)) {

				List<Long> unifiedOrderGoodsIds = AnStringUtils.stringArrayConvertToLongList(unifiedOrderGoodsIdsStr, ",");

				if (CollectionUtils.isNotEmpty(unifiedOrderGoodsIds)) {
					// 订单商品 过来统一订单后的 unifiedOrderGoodsIds
					params.put("unifiedOrderGoodsIds", unifiedOrderGoodsIds);
				} else {
					return;
				}

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

				// 下单人 企业
				params.put("purchaseVirtId", getLong("purchaseVirtId"));
				params.put("purchaseVirtName", getString("purchaseVirtName"));

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

				// 订单金额 =
				params.put("amount", getString("amount"));

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

				// 供应商对账状态  未对账 2
				params.put("accountingStateSupplier", 2);
			}

			log.info("供应商结算 - 未对账订单 opt 导出报表 (未对账列表-导出) params: \n{}", JsonUtils.toJson(params));

			// 这个是从订单维度过来的方法 之前是因为 是 订单维度 的 列表显示 所以不能共用方法，现在这个加的 商品维度 的 列表显示 ，所以是能共用了，这个先屏蔽
//            List<UnifiedOrderSupplierNotCheckDetail2GoodsVo> excelResult = unifiedOrderDubboConsumerService.getSupplierUnAccountingDetailDimOrder2Goods(getToken(), params);

			List<SupplierUnAccountingDimGoodsVo> dataList = unifiedOrderDubboConsumerService.getSupplierUnAccountingDimGoodsList(getToken(), params);

			String[] field = {
					"orderSn", "saleName", "purchaseVirtName",
					"purchaseUserName", "purchasePhone",
					"goodsId", "goodsName", "cateNameLv1", "cateNameLv2", "cateNameLv3", "", "unit", "quantity", "costPrice", "goodsCostAmount", "price", "goodsAmount",
					"taxRate", "taxCode",
					"createTime", "orderStateName",
					"expressCompany", "expressSn", "recUsername", "recUserphone", "recAddress",
					"updateTime",
					"remarks"
			};

			String[] fieldZhCn = {
					"订单编号", "供应商名称", "企业名称",
					"下单人姓名", "下单人手机号",
					"商品Id", "商品名称", "一级分类", "二级分类", "三级分类", "商品规格", "单位", "数量", "成本单价(元)", "成本总价(元)", "销售单价(元)", "销售总价(元)",
					"税率%", "税务编码",
					"下单时间", "订单状态",
					"快递公司", "快递单号", "收货人", "收货手机号", "收货地址",
					"更新时间",
					"备注"
			};

//			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();
		}

	}


	/***
	 * 供应商对账(结算) - 未对账商品 - 创建对账单 - 维度 - 商品
	 * createBills
	 * @return
	 */
	@ApiOperation(value = "供应商对账(结算) - 未对账商品 - 创建对账单 - 维度 - 商品", notes = "")
	@RequestMapping(value = "/createStatementOfAccount", method = RequestMethod.POST)
	@ResponseBody
	public R<AccountingUnifiedSupplier> createStatementOfAccount(UnifiedSupplierCreateDimGoodsParam params) {

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

		try {

			// 没有返回问题信息 mark by linjinyu at 20210305 重构
//			AccountingUnifiedSupplier statementOfAccount = accountingUnifiedSupplierDubboConsumerService.opCreateAccountingDimGoods(getToken(), params);
//			if (statementOfAccount == null) {
//				result.setCode(400);
//				result.setSuccess(false);
//				result.setMessage("可能问题 1. 服务号未配置; 2. 订单包含非[已完成]数据(20210301后添加的逻辑);");
//				return result;
//			}
//			result.setData(statementOfAccount);
			result = accountingUnifiedSupplierDubboConsumerService.opCreateAccountingDimGoods(getToken(), params);


		} 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 btn 编辑对账
	 * 供应商结算 - 对账单 - opt btn 查看详情
	 * /getgoods
	 * @return
	 */
	@ApiOperation(value = "供应商对账(结算) - 对账单 - opt btn 编辑对账 | opt btn 查看详情 - 维度 - 商品", notes = "未整改")
	@RequestMapping(value = "/statementOfAccountDetail", method = RequestMethod.POST)
	@ResponseBody
	public R<List<SupplierUnAccountingDimGoodsVo>> statementOfAccountDetail() {

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

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

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

			List<SupplierUnAccountingDimGoodsVo> unifiedOrderGoodsOfStatementOfAccountList = unifiedOrderDubboConsumerService.getSupplierStatementOfAccountDetailDimGoods2Goods(params);

			result.setData(unifiedOrderGoodsOfStatementOfAccountList);

		} 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;
	}

	/***
	 * 供应商结算 - 未对账订单 - 对账单详情 - 详情导出
	 * /exportgoods
	 * @return
	 */
	@ApiOperation(value = "供应商对账(结算) - 未对账订单 - 对账单详情 - 详情导出 - 维度 - 商品 - 20210413改版", notes = "未整改")
	@RequestMapping(value = "/exportStatementOfAccountDetail", method = RequestMethod.GET)
	public void exportStatementOfAccountDetail(HttpServletResponse response) throws IOException {

		try {

			String accountingOrderSn = getString("accountingOrderSn");

			Map<String, Object> params = new HashMap<>();
			params.put("accountingOrderSn", accountingOrderSn);

			log.info("供应商结算 - 未对账订单 - 对账单详情 - 详情导出 params: \n{}", JsonUtils.toJson(params));




			List<SupplierUnAccountingDimGoodsVo> dataList = unifiedOrderDubboConsumerService.getSupplierStatementOfAccountDetailDimGoods2Goods(params);

//            for (UnifiedOrderGoodsOfStatementOfAccount goodsInfo : unifiedOrderGoodsOfStatementOfAccountList) {
//
//                /****************************************** 企业采购 情况 start ******************************************/
////				String [] arrAddress = goodsInfo.getRecAddress().split(" ");
////
////				goodsInfo.setAddressProvince(arrAddress[0]);
////				goodsInfo.setAddressCity(arrAddress[1]);
////				goodsInfo.setAddressArea(arrAddress[2]);
////				goodsInfo.setAddressTown(arrAddress[3]);
////				goodsInfo.setAddressAddress(arrAddress[4]);
//
//                /****************************************** 企业采购 情况   end ******************************************/
//
//                /****************************************** 福利内购 情况 start ******************************************/
//                /****************************************** 福利内购 情况   end ******************************************/
//
//                /****************************************** 代客下单 情况 start ******************************************/
//                // 20200916_提出人_燕璐_超级前台_统一订单生产环境_对账单_详情_导出问题.md 问题排查出来了
////				大概是2020年4月的时候 运营提出 代客下单 excel 导入时 会带有 手填地址
////				当最终用了这个地址而没有选用商城过来的地址的情况
////				地址为 安徽省合肥市包河区云谷路与环湖北路交叉口安徽创新馆 导致拆分时出错了
////				之前为 安徽 合肥市 滨湖新区 成都路1888号中国农业银行安徽分行
////				是有空格分开的
//                /****************************************** 代客下单 情况   end ******************************************/
//
//                /****************************************** 楼内闪送 情况 start ******************************************/
////				goodsInfo.setAddressAddress(goodsInfo.getRecAddress());// eg : 公寓6号楼B区四川美术学院六号楼
//                /****************************************** 楼内闪送 情况   end ******************************************/
//
//                if (StringUtils.isNotBlank(goodsInfo.getRecAddress())) {
//
//                    String[] arrAddress = goodsInfo.getRecAddress().split(" ");
//                    if (arrAddress.length >= 5) {
//                        goodsInfo.setAddressProvince(arrAddress[0]);
//                        goodsInfo.setAddressCity(arrAddress[1]);
//                        goodsInfo.setAddressArea(arrAddress[2]);
//                        goodsInfo.setAddressTown(arrAddress[3]);
//                        goodsInfo.setAddressAddress(arrAddress[4]);
//                    } else {
//                        goodsInfo.setAddressAddress(goodsInfo.getRecAddress());
//                    }
//
//                }
//
//            }

//            String[] field = {
//                    "purchaseUserId", "purchaseUserName", "purchasePhone", "recUserName", "recUserPhone", "addressProvince", "addressCity", "addressArea", "addressTown", "addressAddress",
//                    "orderSn", "saleName", "purchaseVirtName",
//                    "goodsId",
//                    "goodsName", "cateNameLv3", "unit", "quantity",
//                    "costPrice", "costAmount",
//                    "price", "amount",
//                    "createTime",
//                    "expressCompany", "expressSn", "transportAmount"
//            };
//
//            String[] fieldZhCn = {
//                    "用户账号", "下单人", "下单人电话", "收货人", "收货人电话", "省", "市", "区", "街道", "详细地址",// add 20200819
//                    "订单编号", "供应商名称", "企业名称",
//                    "商品SKU",// add 20200819
//                    "商品名称", "商品规格", "单位", "数量",
//                    "成本单价", "成本总价",
//                    "销售单价", "销售总价",// add 20200819
//                    "下单时间",
//                    "物流公司", "物流单号", "运费",// add 20200819
//            };

//			String[] field = {
//					"orderSn", "saleName", "purchaseVirtName",
//					"purchaseUserName", "purchasePhone",
//					"goodsId", "goodsName", "cateNameLv1", "cateNameLv2", "cateNameLv3", "selfOption", "unit", "quantity", "costPrice", "goodsCostAmount", "price", "goodsAmount",
//					"taxRate", "taxCode",
//					"createTime", "orderStateName",
//					"expressCompany", "expressSn", "recUsername", "recUserphone", "recAddress",
//					"updateTime",
//					"remarks"
//			};
//
//			String[] fieldZhCn = {
//					"订单编号", "供应商名称", "企业名称",
//					"下单人姓名", "下单人手机号",
//					"商品Id", "商品名称", "一级分类", "二级分类", "三级分类", "商品规格", "单位", "数量", "成本单价(元)", "成本总价(元)", "销售单价(元)", "销售总价(元)",
//					"税率%", "税务编码",
//					"下单时间", "订单状态",
//					"快递公司", "快递单号", "收货人", "收货手机号", "收货地址",
//					"更新时间",
//					"备注"
//			};

//			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") + accountingOrderSn + "_.xls");
//			//刷新缓冲
//			response.flushBuffer();
//
//			//workbook将Excel写入到response的输出流中,供页面下载
//			workbook.write(response.getOutputStream());

//			ExcelResponse.out(dataList, fieldZhCn, field, "商品", "供应商结算(对账)" + "_" + "电子账单" + "_" + accountingOrderSn, response);

		} catch (Exception e) {

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

	}
}
