package cn.superdesk.uniorder.controller.order;

import cn.superdesk.uniorder.common.excel.ExcelResponse;
import cn.superdesk.uniorder.common.exception.utils.ExceptionUtils;
import cn.superdesk.uniorder.common.pagination.PageQueryParam;
import cn.superdesk.uniorder.common.rest.response.R;
import cn.superdesk.uniorder.controller.base.BaseController;
import cn.superdesk.uniorder.dto.vo.order.Org2VirtStatisticsVo;
import cn.superdesk.uniorder.dto.vo.unified.UnifiedOrderCommonHeadSum;
import cn.superdesk.uniorder.dto.vo.unified.UnifiedOrderGoodsDetailVo;
import cn.superdesk.uniorder.dto.vo.unified.UnifiedOrderGoodsVo;
import cn.superdesk.uniorder.dubbo.consumer.order.base.UnifiedOrderDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.invoice.customer.InvoiceApplyCustomerDubboConsumerService;
import cn.superdesk.uniorder.common.numerical.AnBeanUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
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: 订单管理-订单管理
 * http://192.168.1.223:8282/#/projectOrderManger?id=12
 * @Author: linjinyu
 * @CreateDate: 7/7/20 10:43 AM
 * @UpdateUser: linjinyu
 * @UpdateDate: 7/7/20 10:43 AM
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Api(value = "订单管理-订单管理", tags = {"订单管理-订单管理"})
@Slf4j
@RestController
@RequestMapping("/order")
public class UnifiedOrderManagerController extends BaseController {

	@Autowired
	private UnifiedOrderDubboConsumerService         unifiedOrderDubboConsumerService;
	@Autowired
	private InvoiceApplyCustomerDubboConsumerService invoiceApplyDubboConsumerService;

	/***
	 * 订单管理-订单管理
	 * @return
	 */
	@ApiOperation(value = "订单管理-订单管理-列表", notes = "")
	@PostMapping("/page")
	@ResponseBody
	public R<List<UnifiedOrderGoodsVo>> getnotdzpage() {

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

		try {

			// 筛选条件
			Map<String, Object> params = new HashMap<>();

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

			// 商品名称 搜索 like '%${goodsName}%'
			params.put("goodsName", getString("goodsName"));

			// 项目名称
			params.put("projectId", getString("projectId"));
			params.put("projectName", getString("projectName"));

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

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

			// 订单类型
			params.put("serviceNo", getString("serviceNo"));

			// 订单状态 业务方的 与 订单类型 联动 web/uservice/page
			params.put("orderStateName", getString("orderStateName"));

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

			// 支付方式
			params.put("payType", getString("payType"));

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


			// 处理到这里 已经把 table list 的数据填充了
			result = unifiedOrderDubboConsumerService.getOrderManagerGoodsByPage(params, getPageNum(), getPageSize(), getToken());


			/** 先注释 验证后删除 // TODO mark by linjinyu at 2022-06-21 14:07:42 -
			 * {@link cn.superdesk.uniorder.service.base.impl.UnifiedOrderServiceImpl#getOrderManagerGoodsViewAdditional}
			for (UnifiedOrderGoodsVo viewUnifiedOrderGoods : result.getData()) {

				viewUnifiedOrderGoods.setGoodsAmount(new BigDecimal(viewUnifiedOrderGoods.getPrice().doubleValue() * viewUnifiedOrderGoods.getQuantity()));

				// 付款状态
//				viewUnifiedOrderGoods.setPayStateName(UnifiedOrderMixPayAboutName.getPayStateName(viewUnifiedOrderGoods.getServiceNo(), viewUnifiedOrderGoods.getPayState()));

				// 支付方式 TODO
//				viewUnifiedOrderGoods.setPayTypeName(UnifiedOrderMixPayAboutName.getPayTypeName(viewUnifiedOrderGoods.getServiceNo(), viewUnifiedOrderGoods.getPayType()));

				// 开发票 发票状态 //	uo.inv_state AS inv_state,
				viewUnifiedOrderGoods.setInvoiceStatusName(UnifiedOrderInvoiceStateEnum.getDesc(viewUnifiedOrderGoods.getInvoiceStatus()));

				// ---- start 临时 查找发票信息
//				Map<String, Object> invQuery = new HashMap<>();
//				invQuery.put("orderSn", viewUnifiedOrderGoods.getOrderSn());
//				List<InvoiceApply> applies = invoiceApplyDubboConsumerService.findInvoiceByOrderSn(invQuery);
//				if (AnCollectionUtils.isNotEmpty(applies)) {
//					viewUnifiedOrderGoods.setInvNumber(applies.get(0).getInvoiceNumber());
//					viewUnifiedOrderGoods.setInvSn(applies.get(0).getInvoiceNo());
//					viewUnifiedOrderGoods.setInvStateName("已开票");
//				}
				// ----  end  临时 查找发票信息
			}
			 **/


//			订单数:131 订单金额:¥ 117566.6 应收金额:¥ 99055 退货金额:¥ 18511.6
			UnifiedOrderCommonHeadSum unifiedOrderCommonHeadSum = unifiedOrderDubboConsumerService.getOrderManagerGoodsPageHead(params, getToken());

			// 修下为 标记 1
//			unifiedOrderCommonHeadSum.setRealAmount(unifiedOrderCommonHeadSum.getOrderAmount());
//			unifiedOrderCommonHeadSum.setOrderAmount(unifiedOrderCommonHeadSum.getOrderAmount().add(unifiedOrderCommonHeadSum.getReturnAmount()));
//			Map<String, Object> headData = new HashMap<>();
//			// 订单金额:¥ 22
//			headData.put("orderAmount", unifiedOrderCommonHeadSum.getOrderAmount());
//			// 订单数:1
//			headData.put("total", unifiedOrderCommonHeadSum.getTotal());
//			// 退货金额:¥ 0
//			headData.put("returnAmount", unifiedOrderCommonHeadSum.getReturnAmount());
//			// 应收金额:¥ 22
//			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;
	}

	@ApiOperation(value = "订单管理-订单管理-统计查询", notes = "")
	@RequestMapping(value = "/org/virt/statistics", method = RequestMethod.POST)
	@ResponseBody
	public R<List<Org2VirtStatisticsVo>> getOrg2VirtStatistics(@RequestBody PageQueryParam param) {

//		orgId

		R<List<Org2VirtStatisticsVo>> response = new R<>();


		response = unifiedOrderDubboConsumerService.getOrg2VirtStatistics(getToken(), param.getConditions(), param.getPageNo(), param.getPageSize());


		return response;


	}

	/**
	 * 订单管理-订单管理-opt 导出报表 excel 2007
	 *
	 * @param response
	 * @throws IOException
	 */
	@Deprecated
	@ApiOperation(value = "订单管理-订单管理-opt 导出报表 excel 2007", notes = "")
	@RequestMapping(value = "/getexcel", method = RequestMethod.GET)
	public void exportOrderData(HttpServletResponse response) throws IOException {

		try {

			// 筛选条件
			Map<String, Object> params = new HashMap<>();

			// 订单编号
			params.put("orderSn", getString("orderSn"));
			// 商品名称 搜索 like '%${goodsName}%'
			params.put("goodsName", getString("goodsName"));

			// 项目名称
			params.put("projectId", getString("projectId"));
			params.put("projectName", getString("projectName"));

			// 企业名称
			params.put("purchaseVirtId", getLong("purchaseVirtId"));
			params.put("purchaseVirtName", getString("purchaseVirtName"));

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

			// 订单类型
			params.put("serviceNo", getString("serviceNo"));

			// 订单状态 业务方的 与 订单类型 联动 web/uservice/page
			params.put("orderStateName", getString("orderStateName"));

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

			// 支付方式
			params.put("payType", getString("payType"));

			// 下单时间
			params.put("startTime", getString("startTime"));
			params.put("endTime", getString("endTime"));
			// 查询条件 end


			/**
			 * 只是查了uo uog 两个表
			 */
			List<UnifiedOrderGoodsVo> dataList = unifiedOrderDubboConsumerService.getOrderManagerGoodsView(getToken(), params);

			String[] field = {"orderSn",

					"serviceName", // fix
					"projectName", "purchaseVirtName", "amount", "payTypeName", "orderStateName", "purchaseUserName",
					"purchasePhone", "recAddress", "createTime",
//					"saleName",
					"remarks", "", "goodsName",

					"unit", "price", "quantity", "goodsAmount",

					"recUserName", "recUserPhone",
					"payStateName", "payTime", "sendTime", "finishTime", "updateTime",
					"invoiceNumber", "invApplyTime", "invoiceStatusName", "invoiceApplySn", "invMakeInvoiceTime"
			};

			String[] fieldZhCn = {"订单编号",
					"订单类型", // fix
					"会员所属项目", "会员所属企业(动态)", "订单金额(总价)(包含运费)", "支付方式", "订单状态", "下单人姓名",
					"下单人电话", "收货地址", "下单时间",
//					"供应商名称",
					"买家备注", "卖家备注", "商品信息",

					"商品单位", "商品单价(折扣后)", "商品数量", "商品总价(折扣后)",

					"收货人姓名", "收货人手机号",
					"付款状态", "付款时间", "发货时间", "完成时间", "最后更新时间",
					"发票号", "开票申请时间", "发票状态", "开票申请编号", "开票登记时间"};

			ExcelResponse.out(dataList, fieldZhCn, field, "订单(商品)", "订单管理" + "_" + "导出报表" + "_" + "", response);

		} catch (Exception e) {

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

		}
	}

	/**
	 * 订单管理-订单管理-opt 导出成本 excel 2007
	 *
	 * @param response
	 * @throws IOException
	 */
	@Deprecated
	@ApiOperation(value = "订单管理-订单管理-opt 导出成本 excel 2007", notes = "")
	@RequestMapping(value = "/getcostpriceexcel", method = RequestMethod.GET)
	public void exportCostPrice(HttpServletResponse response) throws IOException {
		try {

			// 筛选条件
			Map<String, Object> params = new HashMap<>();

			// 订单编号
			params.put("orderSn", getString("orderSn"));
			// 商品名称 搜索 like '%${goodsName}%'
			params.put("goodsName", getString("goodsName"));

			// 项目名称
			params.put("projectId", getString("projectId"));
			params.put("projectName", getString("projectName"));

			// 企业名称
			params.put("purchaseVirtId", getLong("purchaseVirtId"));
			params.put("purchaseVirtName", getString("purchaseVirtName"));

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

			// 订单类型
			params.put("serviceNo", getString("serviceNo"));

			// 订单状态 业务方的 与 订单类型 联动 web/uservice/page
			params.put("orderStateName", getString("orderStateName"));

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

			// 支付方式
			params.put("payType", getString("payType"));

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


			/**
			 * 只是查了uo uog 两个表
			 */
			List<UnifiedOrderGoodsVo> dataList = unifiedOrderDubboConsumerService.getOrderManagerGoodsView(getToken(), params);

			String[] field = {
					"orderSn", "serviceName", "projectName", "purchaseVirtName", "amount", "payTypeName", "orderStateName", "purchaseUserName",
					"purchasePhone", "recAddress", "createTime", "saleName", "remarks", "",

					"goodsName", "unit", "price", "costPrice", "quantity", "goodsAmount",

					"recUserName", "recUserPhone",
					"payStateName", "payTime", "sendTime", "finishTime", "updateTime",
					"invoiceNumber", "", "invoiceStatusName", "invoiceApplySn", "invMakeInvoiceTime"
			};

			String[] fieldZhCn = {
					"订单编号", "订单类型", "会员所属项目", "会员所属企业(动态)", "订单金额(总价)(包含运费)", "支付方式", "订单状态", "下单人姓名",
					"下单人电话", "收货地址", "下单时间", "供应商名称", "买家备注", "卖家备注",

					"商品信息", "商品单位", "商品单价(折扣后)", "成本价格", "商品数量", "商品总价(折扣后)",

					"收货人姓名", "收货人手机号",
					"付款状态", "付款时间", "发货时间", "完成时间", "最后更新时间",
					"发票号", "开票申请时间", "发票状态", "开票申请编号", "开票登记时间"
			};


			ExcelResponse.out(dataList, fieldZhCn, field, "订单(商品)", "订单管理" + "_" + "导出成本" + "_" + "", response);

		} catch (Exception e) {

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

	/***
	 * 订单详情
	 * @return
	 */
	@ApiOperation(value = "订单管理-订单管理-opt 订单详情", notes = "")
	@RequestMapping(value = "/detail", method = RequestMethod.POST)
	@ResponseBody
	public R<UnifiedOrderGoodsDetailVo> getDetail(Long id) {

		R<UnifiedOrderGoodsDetailVo> result = new R<>();
		try {

			UnifiedOrderGoodsDetailVo detail = unifiedOrderDubboConsumerService.getGoodsDetail(id, getToken());
			result.setData(detail);

		} catch (Exception e) {

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

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


}
