package com.bjtdba.order.service.impl;

import com.bjtdba.order.dao.OrderMerchantDao;
import com.bjtdba.order.dao.StoreOrderDao;
import com.bjtdba.order.dao.StoreRefundOrderDao;
import com.bjtdba.order.service.OrderService;
import com.bjtdba.order.util.redis.RedisUtil;
import com.bjtdba.order.vo.OrderList;
import com.bjtdba.order.vo.OrderUserNameList;
import com.bjtdba.utils.ResponseUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {

    /**
     * 正向订单
     */
    @Autowired
    private StoreOrderDao orderDao;

    /**
     * 逆向订单
     */
    @Autowired
    private StoreRefundOrderDao storeRefundOrder;

    @Autowired
    private OrderMerchantDao orderMerchantDao;
    @Autowired
    private StoreOrderDao storeOrderDao;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public Object orderStstusAmount(String mer_id) {
        Map<String, Object> data = new HashMap<>();
           //以支付订单数量  0 1 2 3
//        Integer orderPayment = orderDao.selectNumber(mer_id,new int[]{0,1,2,3});
//        //实际金额  pay_price   这个金额受订单的实际支付的金额
//        Double payPrice = orderDao.selectPayPriceSum(mer_id,new int[]{0,1,2,3});
//        //退款金额   状态 0:待审核 -1:审核未通过 1:待退货 2:待收货 3:已退款   退款金额只显示已退款状态下的
//        Double refundPrice = storeRefundOrder.selectRefundPriceSum(mer_id,new int[]{3});
//        //待付款   5    acction
//        Integer orderPrepPayment = orderDao.selectNumber(mer_id,new int[]{5});
//        //待发货   0
//        Integer orderForDelivery = orderDao.selectNumber(mer_id,new int[]{0});
//        //待收货      1
//        Integer orderForReceived = orderDao.selectNumber(mer_id,new int[]{1});
//        //待评价   2
//        Integer orderForSpeech = orderDao.selectNumber(mer_id,new int[]{2});
//        //以完成   3
//        Integer orderComplete = orderDao.selectNumber(mer_id,new int[]{3});
//        //以申请退款   4
//        Integer orderApplyRefund = orderDao.selectNumber(mer_id,new int[]{4});
//        //以退款   -1
//        Integer orderRefund = orderDao.selectNumber(mer_id,new int[]{-1});


        //优化 准备放到redis换成中，防止频繁请求 设置为1分钟有限时间

        String resCounts="0,0,0,0,0,0,0,0,0,0";
        try {
//            redisUtil.del("ordermerId"+mer_id);
//            System.out.println("redisUtil.get(\"ordermerId\"+mer_id)==="+redisUtil.get("ordermerId"+mer_id));
            Object ob=redisUtil.get("ordermerId"+mer_id);
            if(ob!=null){
                  return ResponseUtil.ok(redisUtil.get("ordermerId"+mer_id));
            }
            resCounts=orderDao.selectOrderCount(mer_id);
            String[] resvalue=resCounts.split(",");
            Integer orderPayment =Integer.parseInt(resvalue[0]) ;
            //实际金额  pay_price   这个金额受订单的实际支付的金额
            Double payPrice = Double.parseDouble(resvalue[1]);
            //退款金额   状态 0:待审核 -1:审核未通过 1:待退货 2:待收货 3:已退款   退款金额只显示已退款状态下的
            Double refundPrice = Double.parseDouble(resvalue[2]);
            //待付款   5    acction
            Integer orderPrepPayment = Integer.parseInt(resvalue[3]) ;
            //待发货   0
            Integer orderForDelivery = Integer.parseInt(resvalue[4]) ;
            //待收货      1
            Integer orderForReceived = Integer.parseInt(resvalue[5]) ;
            //待评价   2
            Integer orderForSpeech =Integer.parseInt(resvalue[6]) ;
            //以完成   3
            Integer orderComplete = Integer.parseInt(resvalue[7]) ;
            //以申请退款   4
            Integer orderApplyRefund = Integer.parseInt(resvalue[8]) ;
            //以退款   -1
            Integer orderRefund = Integer.parseInt(resvalue[9]) ;

            data.put("orderPayment",orderPayment);
            data.put("payPrice",payPrice);
            data.put("refundPrice",refundPrice);
            data.put("orderPrepPayment",orderPrepPayment);
            data.put("orderForDelivery",orderForDelivery);
            data.put("orderForReceived",orderForReceived);
            data.put("orderForSpeech",orderForSpeech);
            data.put("orderComplete",orderComplete);
            data.put("orderApplyRefund",orderApplyRefund);
            data.put("orderRefund",orderRefund);
            redisUtil.set("ordermerId"+mer_id,data,120);//设置为2分钟
//            redisUtil.del("ordermerId"+mer_id);
            return ResponseUtil.ok(data);

        }catch (Exception e){
            e.printStackTrace();
            resCounts="0,0,0,0,0,0,0,0,0,0";
            String[] resvalue=resCounts.split(",");
            Integer orderPayment =Integer.parseInt(resvalue[0]) ;
            //实际金额  pay_price   这个金额受订单的实际支付的金额
            Double payPrice = Double.parseDouble(resvalue[1]);
            //退款金额   状态 0:待审核 -1:审核未通过 1:待退货 2:待收货 3:已退款   退款金额只显示已退款状态下的
            Double refundPrice = Double.parseDouble(resvalue[2]);
            //待付款   5    acction
            Integer orderPrepPayment = Integer.parseInt(resvalue[3]) ;
            //待发货   0
            Integer orderForDelivery = Integer.parseInt(resvalue[4]) ;
            //待收货      1
            Integer orderForReceived = Integer.parseInt(resvalue[5]) ;
            //待评价   2
            Integer orderForSpeech =Integer.parseInt(resvalue[6]) ;
            //以完成   3
            Integer orderComplete = Integer.parseInt(resvalue[7]) ;
            //以申请退款   4
            Integer orderApplyRefund = Integer.parseInt(resvalue[8]) ;
            //以退款   -1
            Integer orderRefund = Integer.parseInt(resvalue[9]) ;

            data.put("orderPayment",orderPayment);
            data.put("payPrice",payPrice);
            data.put("refundPrice",refundPrice);
            data.put("orderPrepPayment",orderPrepPayment);
            data.put("orderForDelivery",orderForDelivery);
            data.put("orderForReceived",orderForReceived);
            data.put("orderForSpeech",orderForSpeech);
            data.put("orderComplete",orderComplete);
            data.put("orderApplyRefund",orderApplyRefund);
            data.put("orderRefund",orderRefund);
            return ResponseUtil.ok(data);
        }



    }

    /**
     * 状态 0:待审核 -1:审核未通过 1:待退货 2:待收货 3:已退款
     * @param mer_id
     * @return
     */
    @Override
    public Object refundOrderStstusAmount(String mer_id) {
        Map<String, Object> data = new HashMap<>();
        //待审核
        int refundOrderExamine = storeRefundOrder.selectNumber(mer_id,0);
        //审核未通过
        int refundOrderFailed = storeRefundOrder.selectNumber(mer_id,-1);
        ////待退货
        int refundOrderReturned = storeRefundOrder.selectNumber(mer_id,1);
        //待收货
        int refundOrderToBe = storeRefundOrder.selectNumber(mer_id,2);
        //已退货
        int refundOrderReceived = storeRefundOrder.selectNumber(mer_id,3);
        data.put("refundOrderExamine",refundOrderExamine);
        data.put("refundOrderFailed",refundOrderFailed);
        data.put("refundOrderReturned",refundOrderReturned);
        data.put("refundOrderToBe",refundOrderToBe);
        data.put("refundOrderReceived",refundOrderReceived);
        return ResponseUtil.ok(data);
    }

    /**
     * 需要做一个商品总价的计算   商品单价*商品数量（暂时解决方案）
     * @param pageNum
     * @param pageSize
     * @param uid
     * @param mer_id
     * @param status
     * @return
     */
    @Override
    public Object orderList(Integer pageNum, Integer pageSize, String uid, String mer_id, String status) {
        Map<String, Object> data = new HashMap<>();
        PageHelper.startPage(pageNum,pageSize);
        PageInfo<OrderList> pageInfo = null;
//        List<OrderList> orders = orderDao.selectOrederList(uid,mer_id,status);
        Object ob=redisUtil.get("orderList"+mer_id+"_"+status+"_"+pageNum);
        List<OrderList> orders=new ArrayList<OrderList>();
        if(ob!=null){
            return ResponseUtil.ok(redisUtil.get("orderList"+mer_id+"_"+status+"_"+pageNum));
        }else{
            orders = orderDao.selectOrederListNew(uid,mer_id,status);
            pageInfo = new PageInfo<OrderList>(orders);
            if(pageInfo.getPages()<pageNum){
                PageHelper.startPage(0,0);
                List<OrderList> order = new ArrayList<>();
                pageInfo = new PageInfo<>(order);
            }
            data.put("pageInfo",pageInfo);
            redisUtil.set("orderList"+mer_id+"_"+status+"_"+pageNum,data,120);//2分钟
            return ResponseUtil.ok(data);
        }
    }

    /**
     *
     * @param order_sn
     * @return
     */
    @Override
    public Object getOrderDetails(String order_sn) {
        Map<String, Object> data = new HashMap<>();
//        OrderList order = orderDao.selectOrderDetails(order_sn);
        //最新调整何海强
        Object ob=redisUtil.get("OrderDetails_"+order_sn);
        if(ob!=null){
            return ResponseUtil.ok(redisUtil.get("OrderDetails_"+order_sn));
        }else{
            OrderList order =orderDao.selectOrderDetailsNew(order_sn);
            data.put("order",order);
            redisUtil.set("OrderDetails_"+order_sn,data,120);//2分钟
            return ResponseUtil.ok(data);
        }
    }

    @Override
    public Object onLineOrdeSun(String mer_id, String start_time, String end_time) {
        //线上订单
        Map<String,String> orderLineOrderSun = orderDao.onLineOrdeSun(mer_id,start_time,end_time);
        //线下订单
        //Map<String,String> belowTheLineSum = orderMerchantDao.belowTheLineSum(mer_id,start_time,end_time);
        return orderLineOrderSun;
    }

    /**
     * 通过门店id查询当前门店下的锁定用户信息
     * @param merId
     * @return
     */
    @Override
    public Object queryMerchantUserOrder(int merId,int pageNum ,int pageSize){
        Map<String,Object> data=new HashMap<String,Object>();
        List<OrderUserNameList> ouListAll=new ArrayList<OrderUserNameList>();//当前商户下的全部用户订单。（线上+下线订单）
        List<OrderUserNameList> orderUserNameMerchantList=new ArrayList<OrderUserNameList>();//线下订单
        List<OrderUserNameList> orderUserNameStore=new ArrayList<OrderUserNameList>();//线上订单

        orderUserNameMerchantList=orderMerchantDao.queryOrderUserNameList(merId);//查询线下订单
        orderUserNameStore=storeOrderDao.queryStroeOrderUser(merId);//查询上线订单
        BigDecimal zongMoney=new BigDecimal(0);
        if((orderUserNameMerchantList!=null&&orderUserNameMerchantList.size()!=0)&&(orderUserNameStore!=null&&orderUserNameStore.size()!=0)){
            for (OrderUserNameList orderUserMerchantListObj: orderUserNameMerchantList ) {
                for (int i=0;i<orderUserNameStore.size();i++ ) {
                    OrderUserNameList storeUserObj = orderUserNameStore.get(i);
                    if (orderUserMerchantListObj.getUid()==storeUserObj.getUid()) {
                        //如果线上线下有相同用户，1 判断时间，找到最早的时间，2金额=线上金额+线下金额
                        OrderUserNameList newObj=new OrderUserNameList();
                        String date=null;
                        System.out.println("orderUserMerchantListObj.getCreateTime().getTime()+"+orderUserMerchantListObj.getLoketime().getTime()+"==="+"storeUserObj.getCreateTime().getTime()+"+storeUserObj.getLoketime().getTime());
                        if(orderUserMerchantListObj.getLoketime().getTime()>storeUserObj.getLoketime().getTime()){
                            date=orderUserMerchantListObj.getCreateTime();
                        }else{
                            date=storeUserObj.getCreateTime();
                        }
                        System.out.println("uid==="+storeUserObj.getUid()+"======"+orderUserMerchantListObj.getMoney());
                         zongMoney=storeUserObj.getMoney().add(orderUserMerchantListObj.getMoney());
                       // newObj.setMoney(zongMoney);
                        orderUserMerchantListObj.setMoney(zongMoney);
                        orderUserMerchantListObj.setCreateTime(date);
                        orderUserNameStore.remove(i);//删除已经存在的数据换成

                    }
//
//
//                }
//                System.out.println("===========");
//                Iterator<OrderUserNameList> it=orderUserNameStore.iterator();
//
//                while (it.hasNext()){
//                    OrderUserNameList storeUserObj=new OrderUserNameList();
//                    storeUserObj=it.next();
//                    if (storeUserObj!=null&&orderUserMerchantListObj.getUid()==storeUserObj.getUid()) {
////                        //如果线上线下有相同用户，1 判断时间，找到最早的时间，2金额=线上金额+线下金额
//                        OrderUserNameList newObj=new OrderUserNameList();
//                        Date date=null;
//                        System.out.println("orderUserMerchantListObj.getCreateTime().getTime()+"+orderUserMerchantListObj.getCreateTime().getTime()+"==="+"storeUserObj.getCreateTime().getTime()+"+storeUserObj.getCreateTime().getTime());
//                        if(orderUserMerchantListObj.getCreateTime().getTime()>storeUserObj.getCreateTime().getTime()){
//                            date=orderUserMerchantListObj.getCreateTime();
//                        }else{
//                            date=storeUserObj.getCreateTime();
//                        }
//                        System.out.println("uid==="+storeUserObj.getUid()+"======"+orderUserMerchantListObj.getMoney());
//                         zongMoney=zongMoney.add(orderUserMerchantListObj.getMoney());
//                       // newObj.setMoney(zongMoney);
//                        orderUserMerchantListObj.setMoney(zongMoney);
//                        orderUserMerchantListObj.setCreateTime(date);
//                        orderUserNameStore.remove(storeUserObj);//删除已经存在的数据换成
//
//                    }
                }

//                orderUserNameListObj.getUid()
            }
            ouListAll.addAll(orderUserNameMerchantList);
            ouListAll.addAll(orderUserNameStore);


        }
        if(orderUserNameMerchantList==null){
            ouListAll.addAll(orderUserNameStore);
        }
        if(orderUserNameStore==null){
            ouListAll.addAll(orderUserNameMerchantList);
        }

        int total = ouListAll.size();//
        PageInfo<OrderUserNameList> pageInfo = null;
        if(total/pageSize+1>= pageNum){
            Page page = new Page(pageNum, pageSize);
            page.setTotal(total);
            //计算当前需要显示的数据下标起始值
            int startIndex = (pageNum - 1) * pageSize;
            int endIndex = Math.min(startIndex + pageSize,total);
            //从链表中截取需要显示的子链表，并加入到Page
            page.addAll(ouListAll.subList(startIndex,endIndex));
            pageInfo = new PageInfo<>(page);
        }else{
            Page page = new Page(0, 0);
            page.setTotal(0);
            List<OrderUserNameList> a = new ArrayList<>();
            pageInfo = new PageInfo<>(a);
        }
        data.put("pageInfo",pageInfo);

        return  ResponseUtil.ok( data);

    }

    public Integer seckillOrderCounut(String productId,Long uid){
        return storeOrderDao.seckillOrderCounut(productId,uid);
    }

    public Integer getDayPayCount(Long productId,Long uid){
        Integer once_pay_count=orderDao.getOncePayCount(productId);
        if(once_pay_count!=0){
            return storeOrderDao.seckillOrderCounut(productId+"",uid);
        }else{
            return 0;
        }
    }

    public Integer getPayCount(Long productId,Long uid){
        Integer All_pay_count=orderDao.getAllePayCount(productId);
        if(All_pay_count!=0){
            return storeOrderDao.seckillOrderCounut(productId+"",uid);
        }else{
            return 0;
        }
    }


}
