package cn.superdesk.uniorder.service.order.old.impl;

import cn.hutool.core.date.DateUtil;
import cn.superdesk.uniorder.common.numerical.AnDateHelper;
import cn.superdesk.uniorder.dao.entity.sys.SysGood;
import cn.superdesk.uniorder.dao.entity.sys.SysOrder;
import cn.superdesk.uniorder.dao.mapper.base.*;
import cn.superdesk.uniorder.dao.mapper.channel.UnifiedChannelProfitSyncMapper;
import cn.superdesk.uniorder.dao.mapper.channel.UnifiedChannelProfitSyncMapperEx;
import cn.superdesk.uniorder.dao.mapper.sys.SysGoodMapper;
import cn.superdesk.uniorder.dao.mapper.sys.SysOrderMapper;
import cn.superdesk.uniorder.dao.mapper.unified.UnifiedOrderProfitMapper;
import cn.superdesk.uniorder.dao.mapper.unified.UnifiedOrderProfitMapperEx;
import cn.superdesk.uniorder.event.CommonEventPublisher;
import cn.superdesk.uniorder.service.order.old.SysOrderService;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Slf4j
@Service
public class SysOrderServiceImpl implements SysOrderService {


    @Autowired
    SysOrderMapper sysOrderMapper;
    @Autowired
    SysGoodMapper  sysGoodMapper;

    @Autowired
    UnifiedOrderReturnMapper        unifiedOrderReturnMapper;
    @Autowired
    UnifiedOrderReturnMapperEx      unifiedOrderReturnMapperEx;
    @Autowired
    UnifiedOrderReturnGoodsMapper   unifiedOrderReturnGoodsMapper;
    @Autowired
    UnifiedOrderReturnGoodsMapperEx unifiedOrderReturnGoodsMapperEx;


    @Autowired
    UnifiedOrderMapper        unifiedOrderMapper;
    @Autowired
    UnifiedOrderMapperEx      unifiedOrderMapperEx;
    @Autowired
    UnifiedOrderGoodsMapper   unifiedOrderGoodsMapper;
    @Autowired
    UnifiedOrderGoodsMapperEx unifiedOrderGoodsMapperEx;

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


    @Override
    public SysOrder findById(Long id) {

        return null;
    }

    @Override
    public int insertSelective(SysOrder t) {
        return sysOrderMapper.insertSelective(t);

    }

    @Override
    public int updateByPrimaryKeySelective(SysOrder t) {
        return sysOrderMapper.updateByPrimaryKeySelective(t);

    }

    @Deprecated
    @Override
    public void deleteObj(Long id) {


    }


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

        return null;
    }

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

        return null;
    }

    @Override
    public List<SysOrder> findByOrderId(String orderId) {
        return sysOrderMapper.findByOrderId(orderId);
    }

    /**
     * 订单通道
     * <p>
     * 订单为正: 企业采购 福利内购 代客下单 楼闪送 才有的 目前 20200423 mark by linjinyu
     * 订单为负: 代客下单(原因是代客是没有维权订单一说, 只能做对充单) 才有的 目前 20200423 mark by linjinyu
     *
     * @param jsonMap
     * @param goodsList
     */
    @Override
    @Transactional
    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 order_dispatchprice = new BigDecimal((String) jsonMap.get("dispatchprice"));//订单运费
            BigDecimal order_price         = new BigDecimal((String) jsonMap.get("price"));//订单金额

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

            sysOrder.setPrice(order_price);//订单金额合计(有包含运费

            //del
            //获得最大小计
            //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;
				}
			}*/

            //查父单
			/*List<SysOrder> listParentOrders=orderMapper.findByParentOrderId(sysOrder.getParentOrderId());
			boolean isExistParentOrder=false;
			if(listParentOrders.size()>=1) {
				isExistParentOrder=true;
			}*/


            //BigDecimal orderTotalPrie=BigDecimal.ZERO;

            List<SysGood> sysGoodList = new ArrayList<SysGood>();

            for (int i = 0; i < goodsList.size(); i++) {

                SysGood 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.setOtherField1((String) goodMap.get("title"));//占坑 商品名称

                sysGood.setPrice(good_price);
                sysGood.setDispatchPrice(BigDecimal.ZERO);//商品默认运费为0


                // 如果订单有运费,只赋值给第一个商品
                if (i == 0) {
                    if (order_dispatchprice.compareTo(BigDecimal.ZERO) == 1) {
                        sysGood.setDispatchPrice(order_dispatchprice);
                    } else {
                        sysGood.setDispatchPrice(BigDecimal.ZERO);
                    }
                }

                sysGood.setTotalPrice(sysGood.getDispatchPrice().add(sysGood.getPrice()));//加运费后商品小计=商品小计+运费


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

					if(!isExistParentOrder) {//子单才分配运费
						sysGood.setDispatchPrice(dispatchprice);
						sysGood.setTotalPrice(good_price.add(dispatchprice));//总价等于小计加运费

						isInsertDispatchPrice=true;
					}

				}*/

                //orderTotalPrie=orderTotalPrie.add(sysGood.getTotalPrice());
                //goodMapper.insertSelective(sysGood);
                sysGoodList.add(sysGood);
            }
            //del
			/*if(orderTotalPrie.compareTo(sysOrder.getPrice())==1) {//orderTotalPrie>sysOrder.getPrice()
				sysOrder.setPrice(orderTotalPrie);
				log.info("orderDubboService. sysOrder.setPrice(orderTotalPrie) ======>订单金额使用商品的金额汇总");
			}*/

            //主订单编码 系统唯一订单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);
			}*/


            log.info("orderDubboService. sysOrder.getMyOrderId() ======>" + sysOrder.getMyOrderId());

            List<SysOrder> sysOrderList = sysOrderMapper.findByOrderId(sysOrder.getMyOrderId());


            log.info("orderDubboService. listOrders.size() ======>" + sysOrderList.size());

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

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

			}else if(listOrders.size()==1){//有时只改状态
				SysOrder yetSysOrder=listOrders.get(0);
				yetSysOrder.setStatus(sysOrder.getStatus());
				orderMapper.updateByPrimaryKeySelective(yetSysOrder);
				log.info("orderDubboService.update======>");

			}*/

            // 删除的订单 设为已经关闭
            String deleted = (String) jsonMap.get("deleted");

            log.info("orderDubboService.deleted======>" + deleted);

            if (StringUtils.isNotEmpty(deleted) && "1".equals(deleted)) {

                log.info("orderDubboService.deleted======>" + deleted);

                sysOrder.setStatus(Byte.valueOf("-1"));
            }

            log.info("status======>" + sysOrder.getStatus());

            // 只接待收货 已完成订单
//			if(sysOrder.getStatus().intValue()==0 || sysOrder.getStatus().intValue()==1 || sysOrder.getStatus().intValue()==2 || sysOrder.getStatus().intValue()==3 || sysOrder.getStatus().intValue()==-1) {

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

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

                    log.info("orderDubboService.add======>");

                } else {

                    log.info("orderDubboService.not add======>没有插入订单");

                }

                for (SysGood sg : sysGoodList) {
                    sysGoodMapper.insertSelective(sg);
                }

            } else if (sysOrderList.size() == 1) {

                SysOrder yetSysOrder = sysOrderList.get(0);
                sysOrder.setId(yetSysOrder.getId());//要先set id 在更新
                sysOrder.setIsGenBill(yetSysOrder.getIsGenBill());//是否生成对帐单不能覆盖 因订单可能会重推


                sysOrderMapper.updateByPrimaryKeySelective(sysOrder);

                // 非完成的订单 才更新商品
                //if(yetSysOrder.getStatus().intValue()!=3) {

                // 有订单时 先删除在保存商品
                sysGoodMapper.deleteGoodBySysOrderId(sysOrder.getMyOrderId());

                for (SysGood sg : sysGoodList) {
                    sysGoodMapper.insertSelective(sg);
                }

                //}


                log.info("orderDubboService.update======>");

            }
//			}else {
//				log.info("orderDubboService. 非待收货 已完成订单======>");
//			}

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

}
