package cn.superdesk.uniorder.service.base.impl;

import cn.superdesk.libs.common.json.JsonUtils;
import cn.superdesk.uniorder.common.ResponseResult;
import cn.superdesk.uniorder.common.enums.common.UnifiedServiceEnum;
import cn.superdesk.uniorder.common.enums.order.SuperDeskMallOrderStatus;
import cn.superdesk.uniorder.common.enums.order.UnifiedOrderCompletStateUtils;
import cn.superdesk.uniorder.dao.entity.base.UnifiedOrder;
import cn.superdesk.uniorder.dao.entity.base.UnifiedOrderGoods;
import cn.superdesk.uniorder.dao.entity.base.UnifiedOrderUpdate;
import cn.superdesk.uniorder.dao.mapper.base.*;
import cn.superdesk.uniorder.dao.mapper.unified.UnifiedChannelProfitSyncMapper;
import cn.superdesk.uniorder.dao.mapper.unified.UnifiedChannelProfitSyncMapperEx;
import cn.superdesk.uniorder.dao.mapper.unified.UnifiedOrderProfitMapperEx;
import cn.superdesk.uniorder.dto.vo.unified.*;
import cn.superdesk.uniorder.dto.vo.wechat.WxBillOrder;
import cn.superdesk.uniorder.event.CommonEventPublisher;
import cn.superdesk.uniorder.service.base.UnifiedOrderService;
import cn.superdesk.uniorder.utils.DateHelper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.*;

@Slf4j
@Service
public class UnifiedOrderServiceImpl implements UnifiedOrderService {


	@Autowired
	UnifiedOrderMapper           unifiedOrderMapper;
	@Autowired
	UnifiedOrderMapperEx         unifiedOrderMapperEx;
	@Autowired
	UnifiedOrderMapperExSupplier unifiedOrderMapperExSupplier;

	@Autowired
	UnifiedOrderGoodsMapper   unifiedOrderGoodsMapper;
	@Autowired
	UnifiedOrderGoodsMapperEx unifiedOrderGoodsMapperEx;


	/**
	 * 楼闪送专用 目前是这样 20200706
	 */
	@Autowired
	UnifiedOrderUpdateMapper   unifiedOrderUpdateMapper;
	/**
	 * 楼闪送专用 目前是这样 20200706
	 */
	@Autowired
	UnifiedOrderUpdateMapperEx unifiedOrderUpdateMapperEx;

	@Autowired
	UnifiedOrderProfitMapperEx       unifiedOrderProfitMapperEx;
	@Autowired
	UnifiedChannelProfitSyncMapper   unifiedChannelProfitSyncMapper;
	@Autowired
	UnifiedChannelProfitSyncMapperEx unifiedChannelProfitSyncMapperEx;
	@Autowired
	CommonEventPublisher             commonEventPublisher;

	@Override
	public PageInfo<UnifiedOrder> findByPaging(Map<String, Object> params, Integer pageNo, Integer pageSize) {

		return null;
	}

	@Override
	public void deleteObj(Long id) {


	}

	@Override
	public void updateObj(UnifiedOrder t) {

		unifiedOrderMapper.updateByPrimaryKeySelective(t);
	}

	@Override
	public UnifiedOrder findById(Long id) {

		return unifiedOrderMapper.selectByPrimaryKey(id);
	}

	@Override
	public void addObj(UnifiedOrder t) {


	}

	@Override
	public List<UnifiedOrder> findAll(Map<String, Object> queryMap) {

		return unifiedOrderMapperEx.findAll(queryMap);
	}

	/**
	 * 新增 统一订单 好像只有楼闪送在用
	 *
	 * @param unifiedOrder
	 * @param unifiedOrderGoodsList
	 * @return
	 */
	@Transactional
	@Override
	public UnifiedOrder addObjTran(UnifiedOrder unifiedOrder, List<UnifiedOrderGoods> unifiedOrderGoodsList) {

		unifiedOrderMapper.insert(unifiedOrder);

		for (UnifiedOrderGoods unifiedOrderGoods : unifiedOrderGoodsList) {
			unifiedOrderGoodsMapper.insert(unifiedOrderGoods);
		}


		// TODO mark by linjinyu 重构 分润 start =================================

		commonEventPublisher.triggerProfitOrderCalculationEvent(unifiedOrder);

		// 1209 -- 计算分润
//		Map<String, Object> profitQuery = new HashMap<>();
//
//		profitQuery.put("projectId", unifiedOrder.getProjectId());
//		profitQuery.put("serviceNo", unifiedOrder.getServiceNo());
//
//		List<UnifiedChannelProfitSync> channelProfitSyncs = unifiedChannelProfitSyncMapperEx.findAll(profitQuery);
//
//		if (channelProfitSyncs != null && channelProfitSyncs.size() > 0) {
//
//			// 插入分润表
//			UnifiedChannelProfitSync channelProfitSync = channelProfitSyncs.get(0);
//
//			UnifiedOrderProfit profit = new UnifiedOrderProfit();
//
//			profit.setBusinessCode(channelProfitSync.getBusinessCode());
//			profit.setChannelId(channelProfitSync.getChannelId());
//			profit.setCreateTime(new Date());
//			profit.setOrgId(channelProfitSync.getOrganizationId());
//
//			profit.setProfitAmount(new BigDecimal(unifiedOrder.getAmount().doubleValue() * channelProfitSync.getProportion().doubleValue() / 100));
//			profit.setProportion(channelProfitSync.getProportion());
//
//			profit.setOrderSn(unifiedOrder.getSn());
//
//			UnifiedOrderProfit unifiedOrderProfit = unifiedOrderProfitMapper.selectBySn(unifiedOrder.getSn());
//
//			if (unifiedOrderProfit != null) {
//				profit.setId(unifiedOrderProfit.getId());
//				unifiedOrderProfitMapper.updateByPrimaryKeySelective(profit);
//			} else {
//				unifiedOrderProfitMapper.insert(profit);
//			}
//		}

		// TODO mark by linjinyu 重构 分润  end  =================================


		return unifiedOrder;
	}

	@Override
	public UnifiedOrder findBySn(String sn) {

		return unifiedOrderMapperEx.selectByPrimaryOrderSn(sn);
	}

	@Transactional
	@Override
	public void updateObjTran(UnifiedOrder update, UnifiedOrderUpdate orderupdate, List<UnifiedOrderGoods> orderGoods) {

		// 更新
		unifiedOrderMapper.updateByPrimaryKeySelective(update);

		unifiedOrderUpdateMapper.insert(orderupdate);

		if (orderGoods != null && orderGoods.size() > 0) {

			unifiedOrderGoodsMapperEx.deleteBySn(orderupdate.getOrderSn());

			for (UnifiedOrderGoods item : orderGoods) {
				unifiedOrderGoodsMapper.insert(item);
			}
		}
	}


	@Override
	public ResponseResult<List<UnifiedOrderSupNC>> getSupplierUnAccountDataPage(Map<String, Object> params, int pageNo, int pageSize) {

		PageHelper.startPage(pageNo, pageSize);

		List<UnifiedOrderSupNC> ls = unifiedOrderMapperExSupplier.getSupplierUnAccountData(params);

		PageInfo<UnifiedOrderSupNC> page = new PageInfo<UnifiedOrderSupNC>(ls);

		PageHelper.clearPage();

		return new ResponseResult<List<UnifiedOrderSupNC>>(page.getPageNum(), page.getPageSize(), (int) page.getTotal(), ls);

	}

	@Override
	public List<UnifiedOrderSupNC> getSupplierUnAccountData(Map<String, Object> params) {

		return unifiedOrderMapperExSupplier.getSupplierUnAccountData(params);
	}

	@Override
	public List<UnifiedOrderSupNCGoods> getSupplierUnAccountDataGoods(Map<String, Object> params) {

		return unifiedOrderMapperExSupplier.getSupplierUnAccountDataGoods(params);
	}

	@Override
	public UnifiedOrderCommonHeadSum getSupplierUnAccountHead(Map<String, Object> params) {

		return unifiedOrderMapperExSupplier.getSupplierUnAccountHead(params);
	}


	/**
	 * 商城 订单 正常 同步 已证实为 - 企业采购 - 福利内购
	 *
	 * @param jsonMap
	 * @param goodsList
	 */
	@Transactional
	@Override
	public void kafkaUnifiedOrderReceive(Map jsonMap, List goodsList) {


		log.info("##################### kaFkaOrderSync start #####################");
		log.info("params Map jsonMap:\n" + JsonUtils.toPrettyJson(jsonMap));
		log.info("params List goodsList:\n" + JsonUtils.toPrettyJson(goodsList));


		UnifiedOrder unifiedOrder = new UnifiedOrder();

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

		// TODO 写死
		unifiedOrder.setAccountingStateCustomer(2);
		unifiedOrder.setAmount(new BigDecimal(jsonMap.get("price").toString()));

		// TODO 写死
		unifiedOrder.setAppraiseState(2);

		// TODO 写死
		unifiedOrder.setCostAmount(new BigDecimal("0"));

		unifiedOrder.setCreateTime(DateHelper.parseToDate((String) jsonMap.get("createtime"), DateHelper.DATE_TIME_STRING));
		unifiedOrder.setCreateUserId(null);


		// TODO 未确认 linjinyu 订单状态 start
		// 状态 -1:已关闭,0:待付款,1:待发货,2:待收货,3:已完成
		Integer status = Integer.valueOf(jsonMap.get("status").toString());

		unifiedOrder.setOrderState(status);
		unifiedOrder.setOrderStateName(SuperDeskMallOrderStatus.getDesc(status));
		// TODO 未确认 linjinyu 订单状态 end

		Integer deleted = Integer.valueOf(jsonMap.get("deleted").toString());

		unifiedOrder.setCompletState(UnifiedOrderCompletStateUtils.convertBySuperDeskMallOrderStatus(status, deleted));


		// TODO 设定 订单来源
		unifiedOrder.setServiceNo(UnifiedServiceEnum.getServiceNo(Integer.valueOf(jsonMap.get("order_type").toString())));
		unifiedOrder.setServiceName(UnifiedServiceEnum.getServiceName(Integer.valueOf(jsonMap.get("order_type").toString())));

		Map<String, String> otherParams = new HashMap<>();
		otherParams.put("sendtime", jsonMap.get("sendtime").toString());
		unifiedOrder.setOtherParams(otherParams.toString());

		unifiedOrder.setOrderSnOutTrade(jsonMap.get("ordersn").toString());

		unifiedOrder.setPayType(Integer.valueOf(jsonMap.get("paytype").toString()));

		// TODO 写死 标记20200708
		unifiedOrder.setPayState(2);

		// TODO TAPD 这个有可能为空 福利商城 For input string: ""
		Long projectId = Long.parseLong(jsonMap.get("organizationId") == null || "".equals(jsonMap.get("organizationId")) ? "0" : jsonMap.get("organizationId").toString());
		unifiedOrder.setProjectId(projectId);

		unifiedOrder.setProjectName(jsonMap.get("organization_name").toString());

		Long realnameId = Long.parseLong(jsonMap.get("realnameId").toString());
		unifiedOrder.setPurchaseUserId(realnameId);

		unifiedOrder.setPurchaseUserName(jsonMap.get("realname") == null ? "" : jsonMap.get("realname").toString());
		Long enterpriseId = Long.parseLong(jsonMap.get("enterpriseId").toString());
		unifiedOrder.setPurchaseVirtId(enterpriseId);
		unifiedOrder.setPurchaseVirtName(jsonMap.get("enterprise_name").toString());

		// TODO 写死
		unifiedOrder.setAccountingStateSupplier(2);

		Long merchid = jsonMap.get("merchid") == null ? null : Long.parseLong(jsonMap.get("merchid").toString());
		unifiedOrder.setSaleId(merchid);


		unifiedOrder.setSaleName(jsonMap.get("merch_name") == null ? null : jsonMap.get("merch_name").toString());


		// TODO 写死
		unifiedOrder.setSettlementType(2);
		unifiedOrder.setOrderSn(jsonMap.get("ordersn").toString());

		// TODO 写死
		unifiedOrder.setSourceChannel(1);
		unifiedOrder.setTransportAmount(new BigDecimal(jsonMap.get("dispatchprice").toString()));
		unifiedOrder.setUpdateTime(DateHelper.parseToDate(jsonMap.get("finishtime").toString(), DateHelper.DATE_TIME_STRING));

		// TODO 写死
		unifiedOrder.setUpdateUserId(1L);
		unifiedOrder.setUserName("系统");

		// TODO 写死
		unifiedOrder.setUserType("2");

		// 新增 dz 19-09-10
		if (jsonMap.get("mobile") != null) {
			unifiedOrder.setPurchasePhone(jsonMap.get("mobile").toString());
		}

		if (jsonMap.get("address_address") != null) {
			unifiedOrder.setRecAddress(jsonMap.get("address_address").toString());
		}

		// order.setRecUserid(recUserid);
		if (jsonMap.get("address_realname") != null) {
			unifiedOrder.setRecUsername(jsonMap.get("address_realname").toString());
		}

		if (jsonMap.get("address_mobile") != null) {
			unifiedOrder.setRecUserphone(jsonMap.get("address_mobile").toString());
		}

		if (jsonMap.get("remark") != null) {
			unifiedOrder.setRemarks(jsonMap.get("remark").toString());
		}


		BigDecimal costAmount = new BigDecimal(0);

		// TODO 开票资料保存--待完成

		// 商品信息
		List<UnifiedOrderGoods> unifiedOrderGoodsArrayList = new ArrayList<>();
		for (int i = 0; i < goodsList.size(); i++) {

			UnifiedOrderGoods unifiedOrderGoods = new UnifiedOrderGoods();

			Map goodMap = (Map) goodsList.get(i);


			unifiedOrderGoods.setGoodsName(goodMap.get("title") == null ? "" : goodMap.get("title").toString());

			Map<String, String> goodsParams = new HashMap<>();
			goodsParams.put("taxCode", goodMap.get("taxCode") == null ? "" : goodMap.get("taxCode").toString());
			goodsParams.put("fiscal_code", goodMap.get("fiscal_code") == null ? "" : goodMap.get("fiscal_code").toString());

			unifiedOrderGoods.setGoodsParams(goodsParams.toString());

			Long goodsId = goodMap.get("good_id") == null ? null : Long.parseLong(goodMap.get("good_id").toString());

			unifiedOrderGoods.setGoodsId(goodsId);


			// 关联问题 TAPD_ID_1000681_ 订单管理-导出报表-导出成本EXCEL中添加商品单位（添加至商品数量列后面）.md
			// add by linjinyu 20200514 算了就这样修改吧
			unifiedOrderGoods.setUnit(goodMap.get("unit") == null ? "没有传过来哦" : goodMap.get("unit").toString());

			BigDecimal unitPrice = new BigDecimal(goodMap.get("unit_price") == null ? "0" : goodMap.get("unit_price").toString());
			unifiedOrderGoods.setPrice(unitPrice);

			// add costprice 成本价
			BigDecimal costPrice = new BigDecimal(goodMap.get("costprice") == null ? "0" : goodMap.get("costprice").toString());
			unifiedOrderGoods.setCostPrice(costPrice);

			// 数量
			unifiedOrderGoods.setQuantity(goodMap.get("total") == null ? 0 : (int) Double.parseDouble(goodMap.get("total").toString()));

			// 业务系统 的 订单sn
			unifiedOrderGoods.setOrderSn(unifiedOrder.getOrderSn());


			// TODO 写死
			unifiedOrderGoods.setCreateUserId(1L);
			unifiedOrderGoods.setCreateTime(new Date());
			// TODO 写死
			unifiedOrderGoods.setUpdateUserId(1L);
			unifiedOrderGoods.setUpdateTime(new Date());


			unifiedOrderGoodsArrayList.add(unifiedOrderGoods);

			// 计算成本金额合计
			costAmount = costAmount.add(new BigDecimal(unifiedOrderGoods.getQuantity().doubleValue() * unifiedOrderGoods.getCostPrice().doubleValue()));
		}

		// add 20191122 成本金额
		unifiedOrder.setCostAmount(costAmount);

		// add 20190925 将运费转换为商品
		if (unifiedOrder.getTransportAmount().doubleValue() > 0) {

			UnifiedOrderGoods unifiedOrderGoods = new UnifiedOrderGoods();

			BigDecimal unitPrice = new BigDecimal(unifiedOrder.getTransportAmount().doubleValue());

			unifiedOrderGoods.setOrderSn(unifiedOrder.getOrderSn());

			unifiedOrderGoods.setGoodsName("运费");

			unifiedOrderGoods.setPrice(unitPrice);
			unifiedOrderGoods.setCostPrice(unitPrice);

			unifiedOrderGoods.setQuantity(1);

			unifiedOrderGoods.setUnit("运费");

			// TODO 写死
			unifiedOrderGoods.setCreateUserId(1L);
			unifiedOrderGoods.setCreateTime(new Date());
			// TODO 写死
			unifiedOrderGoods.setUpdateUserId(1L);
			unifiedOrderGoods.setUpdateTime(new Date());

			unifiedOrderGoodsArrayList.add(unifiedOrderGoods);

		}

		//状态 -1:已关闭,0:待付款,1:待发货,2:待收货,3:已完成
		UnifiedOrder checkExistUnifiedOrder = unifiedOrderMapperEx.selectByPrimaryOrderSn(unifiedOrder.getOrderSn());


		// TODO ??只接待收货 已完成订单 戴智的注释 进雨??
		// 没有的订单id才可以保存
		if (checkExistUnifiedOrder == null) {

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

				// TODO 重新计算运费等等 change dz 1105
//				if(order.getTransportAmount().doubleValue()>0) {
//					BigDecimal new_amount = order.getAmount().add(order.getTransportAmount());
//					order.setAmount(new_amount);
//				}

				// 保存订单数据
				unifiedOrderMapper.insert(unifiedOrder);
				for (UnifiedOrderGoods unifiedOrderGoods : unifiedOrderGoodsArrayList) {
					unifiedOrderGoodsMapper.insert(unifiedOrderGoods);
				}
			}

		} else {

			// TODO 重新计算运费等等
//			if(order.getTransportAmount().doubleValue()>0) {
//				BigDecimal new_amount = order.getAmount().add(order.getTransportAmount());
//				order.setAmount(new_amount);
//			}

			unifiedOrder.setUpdateTime(new Date());
			unifiedOrder.setId(checkExistUnifiedOrder.getId());//要先set id 在更新
			unifiedOrder.setAccountingStateCustomer(checkExistUnifiedOrder.getAccountingStateCustomer());
			unifiedOrder.setAccountingStateSupplier(checkExistUnifiedOrder.getAccountingStateSupplier());

			unifiedOrderMapper.updateByPrimaryKeySelective(unifiedOrder);

			// 有订单时 先删除在保存商品
			unifiedOrderGoodsMapperEx.deleteBySn(unifiedOrder.getOrderSn());
			for (UnifiedOrderGoods unifiedOrderGoods : unifiedOrderGoodsArrayList) {
				unifiedOrderGoodsMapper.insertSelective(unifiedOrderGoods);
			}

		}


		// TODO mark by linjinyu 重构 分润 start =================================
		commonEventPublisher.triggerProfitOrderCalculationEvent(unifiedOrder);
		// TODO mark by linjinyu 重构 分润  end  =================================


		log.info("##################### kaFkaOrderSync end #####################");
	}


	@Override
	public ResponseResult<List<UnifiedOrderCusNC>> getCustomerNotDzPage(Map<String, Object> params,
																		int pageNo,
																		int pageSize) {

		PageHelper.startPage(pageNo, pageSize);

		List<UnifiedOrderCusNC> ls = unifiedOrderMapperEx.getCustomerNotDzData(params);

		PageInfo<UnifiedOrderCusNC> page = new PageInfo<UnifiedOrderCusNC>(ls);
		PageHelper.clearPage();

		return new ResponseResult<List<UnifiedOrderCusNC>>(page.getPageNum(), page.getPageSize(), (int) page.getTotal(), ls);
	}

	@Override
	public UnifiedOrderCommonHeadSum getCustomerNotDzHS(Map<String, Object> params) {

		return unifiedOrderMapperEx.getCustomerNotDzHead(params);
	}

	@Override
	public UnifiedOrderCommonHeadSum getOrderManagerGoodsPageHead(Map<String, Object> params) {

		return unifiedOrderMapperEx.getOrderManagerGoodsPageHead(params);
	}

	@Override
	public ResponseResult<List<ViewUnifiedOrderGoods>> getOrderManagerGoodsByPage(Map<String, Object> params,
																				  int pageNo,
																				  int pageSize) {

		PageHelper.startPage(pageNo, pageSize);

		List<ViewUnifiedOrderGoods> ls = unifiedOrderMapperEx.getOrderManagerGoodsView(params);

		PageInfo<ViewUnifiedOrderGoods> page = new PageInfo<ViewUnifiedOrderGoods>(ls);
		PageHelper.clearPage();

		return new ResponseResult<List<ViewUnifiedOrderGoods>>(page.getPageNum(), page.getPageSize(), (int) page.getTotal(), ls);
	}

	@Override
	public List<ViewUnifiedOrderGoods> getOrderManagerGoodsView(Map<String, Object> params) {

		return unifiedOrderMapperEx.getOrderManagerGoodsView(params);
	}


	@Override
	public BigDecimal getPayAmount(Map<String, Object> upaymap) {

		return unifiedOrderMapperEx.getPayAmount(upaymap);
	}

	@Override
	public BigDecimal getAmount(Map<String, Object> query) {

		return unifiedOrderMapperEx.getAmount(query);
	}

	@Override
	public List<WxBillOrder> getVirtOrder(Map<String, Object> params) {
		return unifiedOrderMapperEx.getVirtOrder(params);
	}

	@Override
	public List<UnifiedOrder> getUnifiedOrderByDzId(Map<String, Object> params) {
		return unifiedOrderMapperEx.findAll(params);
	}

	@Override
	public Integer getOrderCount(Map<String, Object> queryMap) {
		return unifiedOrderMapperEx.getOrderCount(queryMap);
	}

}
