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

import cn.hutool.json.JSONUtil;
import cn.superdesk.uniorder.common.excel.ExcelResponse;
import cn.superdesk.uniorder.common.exception.utils.ExceptionUtils;
import cn.superdesk.uniorder.common.numerical.AnStringUtils;
import cn.superdesk.uniorder.common.rest.response.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.SuplierStatementOfAccountDetailQueryCriteria;
import cn.superdesk.uniorder.dto.param.accounting.unified.supplier.UnifiedSupplierCreateDimOrderParam;
import cn.superdesk.uniorder.dto.vo.accounting.unified.supplier.notyet.UnifiedOrderJoinGoodsOfSupplierStatementOfAccountVo;
import cn.superdesk.uniorder.dto.vo.accounting.unified.supplier.notyet.UnifiedOrderSupplierHeadSumVo;
import cn.superdesk.uniorder.dto.vo.unified.UnifiedOrderSupplierDimOrderNotCheckVo;
import cn.superdesk.uniorder.dto.vo.unified.UnifiedOrderSupplierNotCheckDetail2GoodsVo;
import cn.superdesk.uniorder.dubbo.consumer.accounting.supplier.AccountingUnifiedSupplierDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.order.base.UnifiedOrderDubboConsumerService;
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.*;

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


/**
 * @Description: Java类作用描述
 * @Author: linjinyu
 * @CreateDate: 2020/11/3 下午5:41
 * @UpdateUser: linjinyu
 * @UpdateDate: 2020/11/3 下午5:41
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Api(value = "[对账单]-供应商结算-未对账订单", tags = {"[对账单]-供应商结算-未对账订单"})
@Slf4j
@RestController
@RequestMapping("/accounting/unified/supplier/notyet")
public class UnifiedSupplierNotYetDimOrderController extends BaseController {

	@Autowired
	private UnifiedOrderDubboConsumerService unifiedOrderDubboConsumerService;

	@Autowired
	private AccountingUnifiedSupplierDubboConsumerService accountingUnifiedSupplierDubboConsumerService;

	/**
	 * 供应商结算-未对账订单
	 *
	 * @return
	 * @url : http://order.avic-s.com/#/vendorUnreconOrder?id=71
	 * <p>
	 * 未对账列表分页
	 */
	@ApiOperation(value = "供应商结算-未对账商品-维度-订单", notes = "供应商结算0.0,不带数据脱敏")
	@PostMapping("/getuaccountdatapage")
	@ResponseBody
	public R<List<UnifiedOrderSupplierDimOrderNotCheckVo>> getSupplierUnAccountingDimOrderList() {

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

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

			// 订单编号
			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"));

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

//			<!-- 供应商结算-未对账订单 Head -->
//			<select id="getSupplierUnAccountHead" resultMap="cn.superdesk.uniorder.dao.mapper.base.UnifiedOrderMapperEx.UnifiedOrderCommonHeadSumResultMap">
//							SELECT
//					count(uo.id) as total,
//					IFNULL(sum(uo.amount),0) order_amount,
//							IFNULL(sum(uo.cost_amount),0) cost_amount,
//							IFNULL(sum(uo.transport_amount),0) transport_amount,
//							IFNULL(sum(uor.amount),0) as return_amount
//					from
//					unified_order uo
//					LEFT JOIN unified_order_return uor on uo.order_sn = uor.order_sn
//							<where>
//					<include refid="supplierUnAccountWhereIf"></include>
//				</where>
//			</select>
			UnifiedOrderSupplierHeadSumVo suphead = unifiedOrderDubboConsumerService.getSupplierUnAccountingDimOrderHeadSum(params, getToken());
//			suphead.setRealAmount(suphead.getOrderAmount().subtract(suphead.getReturnAmount()));

			Map<String, Object> headData = new HashMap<>();
			// 订单数 (不包含退单数)
			headData.put("total", suphead.getTotal());
			headData.put("orderAmount", suphead.getOrderAmount());
			headData.put("orderCostAmount", suphead.getOrderCostAmount());
			headData.put("goodsCostAmount", suphead.getGoodsCostAmount());
			headData.put("transportCostAmount", suphead.getTransportCostAmount());
			headData.put("refundCostAmount", suphead.getRefundCostAmount());

//			headData.put("realAmount", suphead.getRealAmount());

			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 导出报表 (未对账列表-导出)
	 *
	 * /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 = "供应商结算-未对账订单-opt 导出报表-维度-订单", notes = "供应商结算0.0,不带数据脱敏")
	@Deprecated
	@RequestMapping(value = "/exportuaccountdata",method = RequestMethod.POST)
	public void exportSupplierUnAccountingDimOrderList(HttpServletResponse response) throws IOException {

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

			String orderIdsStr = getString("orderIds");

			if (StringUtils.isNotBlank(orderIdsStr)) {

				Object[] orderIds = AnStringUtils.stringArrayConvertToLongList(getString("orderIds"), ",").toArray();

				if (orderIds.length > 0) {
					// 订单Ids
					params.put("orderIds", orderIds);
				} 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"));
			}


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

			List<UnifiedOrderSupplierNotCheckDetail2GoodsVo> dataList = unifiedOrderDubboConsumerService.getSupplierUnAccountingDetailDimOrder2Goods(params, getToken());

			String[] field = {
					"orderSn", "saleName", "purchaseVirtName",
					"goodsName", "", "unit", "quantity",
					"costPrice", "goodsCostAmount", "createTime"};

			String[] fieldZhCn = {
					"订单编号/退货单号",
					"供应商名称",
					"企业名称",
					"商品名称",
					"商品规格", "单位", "数量",
					"成本价格(元)", "成本金额(元)", "下单时间/退货时间"};

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

		} catch (Exception e) {

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

	}


	@ApiOperation(value = "供应商结算-未对账商品-创建对账单-维度-订单", notes = "伪表单计划整改")
	@PostMapping("/createbills")
	@ResponseBody
	public R<AccountingUnifiedSupplier> createStatementOfAccount(UnifiedSupplierCreateDimOrderParam add) {

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

		try {

			AccountingUnifiedSupplier statementOfAccount = accountingUnifiedSupplierDubboConsumerService.opCreateAccountingDimOrder(getToken(), add);

			if (statementOfAccount == null) {
				result.setCode(400);
				result.setSuccess(false);
				result.setMessage("服务号不存在！");
				return result;
			}

			result.setData(statementOfAccount);

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

	/**
	 * 已添加 数据脱敏逻辑 20211203
	 * 供应商结算-对账单-opt btn 编辑对账
	 * 供应商结算-对账单-opt btn 查看详情
	 *
	 * @return
	 */
	@ApiOperation(value = "供应商结算-对账单-opt btn 编辑对账 | opt btn 查看详情-维度-订单", notes = "供应商结算2.0,数据脱敏,伪表单整改")
	@PostMapping("/getgoods")
	@ResponseBody
	public R<List<UnifiedOrderJoinGoodsOfSupplierStatementOfAccountVo>> statementOfAccountDetail(@RequestBody SuplierStatementOfAccountDetailQueryCriteria queryCriteria) {

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

		try {

			// 已添加 数据脱敏逻辑 20211203
			List<UnifiedOrderJoinGoodsOfSupplierStatementOfAccountVo> unifiedOrderGoodsOfStatementOfAccountList = unifiedOrderDubboConsumerService.getSupplierStatementOfAccountDetailDimOrder2Goods(queryCriteria, getToken());

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

	/**
	 * 已添加 数据脱敏逻辑 20211203
	 * 供应商结算-未对账订单-对账单详情-详情导出
	 *
	 * @return
	 */
	@ApiOperation(value = "供应商结算-对账单-对账单详情-详情导出-维度-订单-带出商品", notes = "供应商结算2.0,数据脱敏,伪表单整改")
	@PostMapping("/exportgoods")
	public void exportStatementOfAccountDetail(@RequestBody SuplierStatementOfAccountDetailQueryCriteria queryCriteria, HttpServletResponse response) throws IOException {

		try {

//			String accountingOrderSn = getString("accountingOrderSn");
//
//			// TODO 添加较验
//
//			Map<String, Object> params = new HashMap<>();
//			params.put("accountingOrderSn", accountingOrderSn);

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

			// 已添加 数据脱敏逻辑 20211203
			List<UnifiedOrderJoinGoodsOfSupplierStatementOfAccountVo> dataList = unifiedOrderDubboConsumerService.getSupplierStatementOfAccountDetailDimOrder2Goods(queryCriteria, getToken());

			for (UnifiedOrderJoinGoodsOfSupplierStatementOfAccountVo goodsInfo : dataList) {


				/****************************************** 企业采购 情况 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
			};

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

		} catch (Exception e) {

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

	}


	/**
	 * 供应商结算-未对账列表-前端说未用到
	 * @return
	 */
	@Deprecated
	@PostMapping("/getuaccountdata")
	@ResponseBody
	public R<List<UnifiedOrderSupplierDimOrderNotCheckVo>> getuAccountData() {

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

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

			params.put("sn", getString("sn"));
			params.put("virtname", getString("virtname"));

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

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

			params.put("startime", getString("startime"));
			params.put("endtime", getString("endtime"));

			List<UnifiedOrderSupplierDimOrderNotCheckVo> ls = unifiedOrderDubboConsumerService.getSupplierUnAccountingDimOrderList(params, getToken());
			result.setData(ls);
			UnifiedOrderSupplierHeadSumVo suphead = unifiedOrderDubboConsumerService.getSupplierUnAccountingDimOrderHeadSum(params, getToken());

//			suphead.setRealAmount(suphead.getOrderAmount().subtract(suphead.getReturnAmount()));

			Map<String, Object> headData = new HashMap<>();
			headData.put("total", suphead.getTotal());
			headData.put("orderAmount", suphead.getOrderAmount());
			headData.put("orderCostAmount", suphead.getOrderCostAmount());
			headData.put("goodsCostAmount", suphead.getGoodsCostAmount());
			headData.put("transportCostAmount", suphead.getTransportCostAmount());
			headData.put("refundCostAmount", suphead.getRefundCostAmount());

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


}
