package cn.superdesk.uniorder.controller.kafka;

import cn.hutool.core.date.DateUtil;
import cn.superdesk.uniorder.common.rest.response.R;
import cn.superdesk.uniorder.common.enums.common.CommonEnabledEnum;
import cn.superdesk.uniorder.controller.base.BaseController;
import cn.superdesk.uniorder.dao.entity.sys.SysGood;
import cn.superdesk.uniorder.dao.entity.sys.SysOrder;
import cn.superdesk.uniorder.dao.entity.channel.UnifiedChannelProfitSync;
import cn.superdesk.uniorder.dao.entity.organisation.UnifiedSupplier;
import cn.superdesk.uniorder.dto.receive.consumer.superdeskapp.UnifiedChannelProfitSyncReceiveParam;
import cn.superdesk.uniorder.dubbo.consumer.channel.UnifiedChannelProfitSyncDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.channel.UnifiedChannelProfitXVirtDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.channel.UnifiedChannelSyncDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.order.old.GoodsDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.order.old.OrderDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.sys.SysOderUserDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.organisation.SysEnterpriseDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.organisation.SysOrganizationDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.unified.UnifiedEncourageDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.order.base.UnifiedOrderDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.organisation.SysSupplierDubboConsumerService;
import cn.superdesk.uniorder.common.numerical.AnDateHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
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 java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/kafka")
public class SysKafkaController extends BaseController {


	@Autowired
	private OrderDubboConsumerService           orderDubboService;
	@Autowired
	private GoodsDubboConsumerService           goodsDubboService;
	@Autowired
	private SysOrganizationDubboConsumerService organizatioDubboService;
	@Autowired
	private SysEnterpriseDubboConsumerService   sysEnterpriseDubboConsumerService;
	@Autowired
	private SysOderUserDubboConsumerService     sysOderUserDubboConsumerService;
	@Autowired
	private UnifiedOrderDubboConsumerService    unifiedorderDubboService;


	@Autowired
	private UnifiedEncourageDubboConsumerService          unifiedEncourageDubboConsumerService;
	@Autowired
	private UnifiedChannelProfitSyncDubboConsumerService  unifiedChannelProfitSyncDubboConsumerService;
	@Autowired
	private UnifiedChannelProfitXVirtDubboConsumerService unifiedChannelProfitXVirtDubboConsumerService;
	@Autowired
	private UnifiedChannelSyncDubboConsumerService        unifiedChannelSyncDubboConsumerService;

	@Autowired
	private UnifiedOrderDubboConsumerService unifiedOrderDubboConsumerService;
	@Autowired
	private SysSupplierDubboConsumerService  unifiedSupplierDubboConsumerService;

	int sendnum   = 0;
	int insertNum = 0;

	/**
	 * 寄票登记或确认开票
	 * 只有已确认未开票,已确认部分开票的账单可以进行开票登记 前端控制
	 *
	 * @param
	 * @return
	 */
	@PostMapping("/sendOrder")
	@ResponseBody
	//@Transactional
	public R mailTickRegister() {
		R result = new R<>();


		String orderJsonStr = request.getParameter("orderJsonStr");//申请放行物品列表
		++sendnum;

		System.out.println("orderJsonStr===>" + orderJsonStr);
		System.out.println("orderJsonStr sendnum===>" + sendnum);

		// List<Map> mailTickRegisterList=com.alibaba.fastjson.JSON.parseArray(mailTickRegisterListJson,Map.class);

		try {
			Map<String, Object> jsonMap = com.alibaba.fastjson.JSONObject.parseObject(orderJsonStr);
			UnifiedSupplier     oe      = new UnifiedSupplier();

			ConvertUtils.register(new org.apache.commons.beanutils.converters.DateConverter(null),
					java.util.Date.class);//添加这一行代码,重新注册一个转换器,也可以自定义


			BeanUtils.copyProperties(oe, jsonMap);
			//if (!data.key().equals("sw-un-businesspor-delete")) {

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

			query.put("saleId", oe.getSaleId());
			query.put("serviceNo", oe.getServiceNo());

			List<UnifiedSupplier> suppliers = unifiedSupplierDubboConsumerService.findAll(query);

			// 存在 update
			if (suppliers != null && suppliers.size() > 0) {

				oe.setId(suppliers.get(0).getId());
				oe.setUpdateTime(DateUtil.date());
				oe.setUpdateUserId(1L);

				unifiedSupplierDubboConsumerService.updateObj(oe);

			}
			// insert
			else {
				oe.setCreateTime(DateUtil.date());
				oe.setCreateUserId(1L);
				oe.setEnabled(CommonEnabledEnum.启用.getKey());
				unifiedSupplierDubboConsumerService.addObj(oe);
			}
			//} else {
//				Map<String,Object> query = new HashMap<>();
//				query.put("saleId",oe.getSaleId());
//				query.put("serviceNo",oe.getServiceNo());
//				List<UnifiedSupplier> suppliers = unifiedSupplierDubboConsumerService.findAll(query);
//				if (suppliers!= null&&suppliers.size()>0) {//存在
//					oe.setId(suppliers.get(0).getId());
//					oe.setEnabled((byte)0);
//					oe.setUpdateTime(DateUtil.date());
//					oe.setUpdateUserId(1L);
//					unifiedSupplierDubboConsumerService.updateObj(oe);
//				}
			//}


//			Map jsonMap=com.alibaba.fastjson.JSON.parseObject(orderJsonStr, Map.class);
//			//List goodsList=(List<Map>)jsonMap.get("goods");
//
//			unifiedOrderDubboConsumerService.kaFkaOrderStateUpdate(jsonMap);
			//KafkaOrderUtil util=new KafkaOrderUtil();
			//util.kaFkaSendOrder(jsonMap, goodsList);
			//kaFkaSendOrder(jsonMap, goodsList);
			//orderDubboService.kaFkaSendOrder(jsonMap, goodsList);//加了事务
			//unifiedorderDubboService.kaFkaOrderSync(jsonMap, goodsList);//dai add 20190903

			result.setSuccess(true);

		} catch (Exception e) {

			result.setCode(String.valueOf(e.hashCode()));
			result.setSuccess(false);
			result.setMessage("系统提示" + e.getMessage());

			log.error(e.getMessage(), e);

			e.printStackTrace();
		}
		return result;
	}


	@PostMapping("/sendprofit")
	@ResponseBody
	//@Transactional
	public R sendprofittest() {
		R result = new R<>();

		String orderJsonStr = request.getParameter("orderJsonStr");

		try {

			Map jsonMap = com.alibaba.fastjson.JSON.parseObject(orderJsonStr, Map.class);

			UnifiedChannelProfitSyncReceiveParam oe = new UnifiedChannelProfitSyncReceiveParam();
			ConvertUtils.register(new org.apache.commons.beanutils.converters.DateConverter(null),
					java.util.Date.class);//添加这一行代码,重新注册一个转换器,也可以自定义
			BeanUtils.copyProperties(oe, jsonMap);


			UnifiedChannelProfitSync channelSync = new UnifiedChannelProfitSync();

			channelSync.setBeginDate(oe.getBeginDate());
			channelSync.setBusinessCode(oe.getBusinessCode());
			channelSync.setChannelId(oe.getComapanyId());
			channelSync.setCreateTime(oe.getCreatedAt());
			channelSync.setCreateUserId(1L);
			channelSync.setEndDate(oe.getEndDate());
			channelSync.setOrganizationId(oe.getOrganizationId());
			channelSync.setProportion(oe.getProportion());
			channelSync.setSyncId(oe.getId());
			channelSync.setSyncTime(DateUtil.date());
			channelSync.setUpdateTime(DateUtil.date());
			channelSync.setUpdateUserId(1L);

			UnifiedChannelProfitSync channelSyncs = unifiedChannelProfitSyncDubboConsumerService.findUnifiedChannelProfitSyncBySyncId(oe.getId());

			if (channelSyncs != null) {//存在 update
				channelSync.setId(channelSyncs.getId());
				unifiedChannelProfitSyncDubboConsumerService.updateUnifiedChannelProfitSync(channelSync);
			} else {//insert
				unifiedChannelProfitSyncDubboConsumerService.addUnifiedChannelProfitSync(channelSync);
			}

			result.setSuccess(true);

		} catch (Exception e) {

			result.setCode(String.valueOf(e.hashCode()));
			result.setSuccess(false);
			result.setMessage("系统提示" + e.getMessage());

			log.error(e.getMessage(), e);

			e.printStackTrace();
		}
		return result;
	}

	@PostMapping("/sendsup")
	@ResponseBody
	//@Transactional
	public R sendsup() {

		R result = new R<>();

		String orderJsonStr = request.getParameter("orderJsonStr");

		try {

			Map jsonMap = com.alibaba.fastjson.JSON.parseObject(orderJsonStr, Map.class);

			UnifiedSupplier oe = new UnifiedSupplier();
			ConvertUtils.register(new org.apache.commons.beanutils.converters.DateConverter(null),
					java.util.Date.class);//添加这一行代码,重新注册一个转换器,也可以自定义
			BeanUtils.copyProperties(oe, jsonMap);


			Map<String, Object> query = new HashMap<>();
			query.put("saleId", oe.getSaleId());
			query.put("serviceNo", oe.getServiceNo());

			List<UnifiedSupplier> suppliers = unifiedSupplierDubboConsumerService.findAll(query);

			if (suppliers != null && suppliers.size() > 0) {//存在 update
				oe.setId(suppliers.get(0).getId());
				oe.setUpdateTime(DateUtil.date());
				oe.setUpdateUserId(1L);
				unifiedSupplierDubboConsumerService.updateObj(oe);
			} else {//insert
				oe.setCreateTime(DateUtil.date());
				oe.setCreateUserId(1L);
				oe.setEnabled(CommonEnabledEnum.启用.getKey());
				unifiedSupplierDubboConsumerService.addObj(oe);
			}

			result.setSuccess(true);
		} catch (Exception e) {
			result.setCode(String.valueOf(e.hashCode()));
			result.setSuccess(false);
			result.setMessage("系统提示" + e.getMessage());
			log.error(e.getMessage(), e);
			e.printStackTrace();
		}
		return result;
	}

	public void kaFkaSendOrder(Map jsonMap, List goodsList) {
		SysOrder sysOrder = new SysOrder();

		ConvertUtils.register(new org.apache.commons.beanutils.converters.DateConverter(null),
				java.util.Date.class);//添加这一行代码,重新注册一个转换器,也可以自定义

		try {
			BeanUtils.copyProperties(sysOrder, jsonMap);

			//状态 -1:已关闭,0:待付款,1:待发货,2:待收货,3:已完成
			/*if(sysOrder.getStatus().equals(Byte.decode("3"))){//只接入完成的订单--不判断状态

			}else{
				return;
			}*/

			//其他代"-" 字段处理
			//Long orderid=Long.valueOf((String)jsonMap.get("orderid"));
			Long orderid = Long.valueOf((Integer) jsonMap.get("orderid"));

			sysOrder.setOrderId(orderid);
			//sysOrder.setParentOrderId(Integer.valueOf((String)jsonMap.get("parent_order_id")));
			sysOrder.setParentOrderId((Integer) jsonMap.get("parent_order_id"));
			sysOrder.setParentOrdersn((String) jsonMap.get("parent_ordersn"));
			sysOrder.setDetailUrl((String) jsonMap.get("detail_url"));
			sysOrder.setSearchField1((String) jsonMap.get("expresssn"));
			sysOrder.setSyncTime(DateUtil.date());

			sysOrder.setAddressRealname((String) jsonMap.get("address_realname"));
			sysOrder.setAddressMobile((String) jsonMap.get("address_mobile"));
			sysOrder.setAddressAddress((String) jsonMap.get("address_address"));
			sysOrder.setCreatetime(AnDateHelper.parseToDate((String) jsonMap.get("createtime"), AnDateHelper.DATE_TIME_STRING));
			sysOrder.setPaytime(AnDateHelper.parseToDate((String) jsonMap.get("paytime"), AnDateHelper.DATE_TIME_STRING));
			sysOrder.setSendtime(AnDateHelper.parseToDate((String) jsonMap.get("sendtime"), AnDateHelper.DATE_TIME_STRING));
			sysOrder.setFinishtime(AnDateHelper.parseToDate((String) jsonMap.get("finishtime"), AnDateHelper.DATE_TIME_STRING));
			sysOrder.setSyncTime(DateUtil.date());

			//sysOrder.setOrganizationId(Long.decode("1"));//项目ID
			//sysOrder.setEnterpriseId(Long.decode("1"));//企业ID
			//sysOrder.setRealnameId(1);//下单人
			//sysOrder.setExamineId(1);//审批人
			//sysOrder.setOrganizationId(Long.decode(((Integer)jsonMap.get("organizationId")).toString()));//项目ID
			//sysOrder.setEnterpriseId(Long.decode(((Integer)jsonMap.get("enterpriseId")).toString()));//企业ID
			//sysOrder.setRealnameId(Integer.decode((String)jsonMap.get("realnameId")));//下单人
			//sysOrder.setExamineId(Integer.decode((String)jsonMap.get("examineId")));//审批人


			sysOrder.setCompanyname((String) jsonMap.get("companyName"));
			sysOrder.setTaxpayersidcode((String) jsonMap.get("taxpayersIDcode"));
			sysOrder.setInvoiceaccount((String) jsonMap.get("invoiceAccount"));
			sysOrder.setInvoicebank((String) jsonMap.get("invoiceBank"));
			sysOrder.setMerchName((String) jsonMap.get("merch_name"));

			//sysOrder.setInvoicetype(Byte.decode(new BigDecimal((String)jsonMap.get("invoiceType")).intValue()));
			sysOrder.setInvoicetype(Byte.decode((String) jsonMap.get("invoiceType")));
			Byte order_type = Byte.decode((String) jsonMap.get("order_type"));
			sysOrder.setOrderType(order_type);

			BigDecimal dispatchprice = new BigDecimal((String) jsonMap.get("dispatchprice"));

			//默认值
			sysOrder.setMyOrdersn((String) jsonMap.get("ordersn"));
			sysOrder.setMyOrderId(order_type.toString() + "-" + orderid.toString());

			//主订单编码 系统唯一订单ID 处理
			/*int parent_order_id=(Integer)jsonMap.get("parent_order_id");
			String parent_ordersn=(String)jsonMap.get("parent_ordersn");
			if(parent_order_id!=0 && !StringUtils.isEmpty(parent_ordersn)){
				sysOrder.setMyOrderId(order_type.toString()+"-"+parent_order_id);
				sysOrder.setMyOrdersn(parent_ordersn);
			}*/


			List<SysOrder> listOrders = orderDubboService.findByOrderId(sysOrder.getMyOrderId());

			if (listOrders.size() == 0) {//没有的订单id才可以保存
				//if(true){//没有的订单id才可以保存

				//没有商品 不保存订单数据
				if (goodsList.size() >= 1) {
					//保存订单数据
					orderDubboService.add(sysOrder);
				}


				//获得最大小计
				boolean    isInsertDispatchPrice = false;
				BigDecimal max_price             = BigDecimal.ZERO;
				for (int k = 0; k < goodsList.size(); k++) {

					Map        goodMap    = (Map) goodsList.get(k);
					BigDecimal good_price = new BigDecimal((String) goodMap.get("price"));
					if (good_price.compareTo(max_price) == 1) {//good_price > max_price
						max_price = good_price;
					}
				}

				SysGood sysGood = null;
				for (int i = 0; i < goodsList.size(); i++) {
					sysGood = new SysGood();
					Map goodMap = (Map) goodsList.get(i);
					BeanUtils.copyProperties(sysGood, goodMap);
					System.out.println("sysGood===>" + goodMap.toString());

					BigDecimal unit_price = new BigDecimal((String) goodMap.get("unit_price"));
					BigDecimal good_price = new BigDecimal((String) goodMap.get("price"));

					//分录保存订单ID
					//sysGood.setSysOrderId(Long.decode((String)jsonMap.get("orderid")));
					sysGood.setSysOrderId(sysOrder.getMyOrderId());
					sysGood.setUnitPrice(unit_price);
					sysGood.setTaxCode((String) goodMap.get("taxCode"));
					sysGood.setFiscalCode((String) goodMap.get("fiscal_code"));

					sysGood.setTotalPrice(good_price);//先默认小计==加运费小计
					sysGood.setDispatchPrice(BigDecimal.ZERO);
					sysGood.setOtherField1((String) goodMap.get("title"));//占坑 商品名称


					//运费处理(分在最大价格的商品上
					//运费不等0  没有插入运费 最大小计==商品分录.小计
					if (BigDecimal.ZERO.compareTo(dispatchprice) != 0 && !isInsertDispatchPrice && max_price.equals(good_price)) {
						sysGood.setDispatchPrice(dispatchprice);
						sysGood.setTotalPrice(good_price.add(dispatchprice));//总价等于小计加运费

						isInsertDispatchPrice = true;
					}

					goodsDubboService.add(sysGood);
					sysGood = null;
				}
			} else if (listOrders.size() == 1) {//有时只改状态
				SysOrder yetSysOrder = listOrders.get(0);
				sysOrder.setId(yetSysOrder.getId());
				orderDubboService.update(sysOrder);//只修改订单信息 修改商品信息

			}

		} catch (Exception e) {
			log.error("kaFkaSendOrder error===>" + e.getMessage());
			log.error(e.getMessage(), e);
		}
	}

}
