package com.bjtdba.order.controller;

import com.alibaba.fastjson.JSON;
import com.bjtdba.entity.order.StoreCart;
import com.bjtdba.order.service.LogService;
import com.bjtdba.order.service.StoreCartService;
import com.bjtdba.order.service.StoreOrderService;
import com.bjtdba.order.util.gong.GongApiRequest;
import com.bjtdba.order.vo.*;
import com.bjtdba.utils.DateUtils;
import com.bjtdba.utils.ResponseUtil;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("order_service/orderService/order")
public class StoreOrderController {
    @Autowired
    public StoreOrderService storeOrderService;
    @Autowired
    public StoreCartService storeCartService;
    @Autowired
    public LogService logService;
    public static GongApiRequest gongApiRequest;
    /**
     * 订单列表
     * @param Hmap
     * @param map
     * @return
     */
    @GetMapping("/list")
   public Object lst(@RequestHeader Map<String,String> Hmap,@RequestParam Map<String,String> map){
       Map<String,Object> data=new HashMap<String,Object>();
        if(!Hmap.containsKey("uid")){
            return ResponseUtil.fail("uid 参数错误");
        }
        if(!map.containsKey("status")||!map.containsKey("page")||!map.containsKey("limit")){
            return ResponseUtil.fail("参数错误");
        }
        Long uid=Long.parseLong(Hmap.get("uid"));
        Integer paid=1;
        Integer status=Integer.parseInt(map.get("status"));
        Integer page=Integer.parseInt(map.get("page"));
        Integer limit = Integer.parseInt(map.get("limit"));
        Integer[] merids=storeOrderService.getMeridsMerchantType(2);
        //分页设置
        PageHelper.startPage(page,limit);
        //查询所有订单
        List<StoreOrderVo> storeOrderVoList=storeOrderService.queryStoreOrderList(uid,status,paid,merids);
        Integer[] meridsIn=new Integer[limit];
        Integer[] storeOrderIds=new Integer[limit];
        int i=0;
        if (storeOrderVoList!=null&&storeOrderVoList.size()>0){
            for (StoreOrderVo so: storeOrderVoList) {
                meridsIn[i]=Integer.parseInt(so.getMer_id()+"");
                storeOrderIds[i]=Integer.parseInt(so.getOrder_id()+"");
                i++;
            }
        }
        //查看店铺信息，把店铺信息添加到订单中
        int num=0;
        Date dateNew=new Date();
        List<MerchantVo> merchantVoList=storeCartService.getMerchantVo(meridsIn);
        List<StoreOrderProductVo> storeOrderProductVoList=storeOrderService.getStoreOrderPorduct(storeOrderIds);
        if (storeOrderVoList!=null&&storeOrderVoList.size()>0){
            for (StoreOrderVo so: storeOrderVoList) {
                for (MerchantVo merchantvo: merchantVoList) {
                    Long mmerid=Long.parseLong(merchantvo.getMer_id()+"");
                    if(so.getMer_id().equals(mmerid)){
                        //订单对应的商家信息
                        storeOrderVoList.get(num).setMerchant(merchantvo);
                    }
                }

                for (StoreOrderProductVo sopVO: storeOrderProductVoList) {
                    if(sopVO.getOrder_id().equals(so.getOrder_id())){
                        //订单对应的商品信息
                        storeOrderVoList.get(num).getOrderProduct().add(sopVO);
                    }
                }
                //查询订单操作的信息
                Date changeTime=storeOrderService.getChangeTime(so.getOrder_id());
                if(changeTime!=null){
                    long dayNum=DateUtils.getDistinceDay(changeTime,dateNew);
                    if (dayNum<7){
                        storeOrderVoList.get(num).setAfter(2);
                    }else{
                        storeOrderVoList.get(num).setAfter(1);
                    }
                }else{
                    storeOrderVoList.get(num).setAfter(1);
                }


                num++;


            }
        }


        data.put("list",storeOrderVoList);

       return ResponseUtil.ok(data);
   }


   @GetMapping("/group_order_list")
    public Object groupOrderList(@RequestHeader Map<String,String> Hmap,@RequestParam Map<String,String> map){
        if (Hmap.containsKey("uid")){
            ResponseUtil.fail("uid 参数错误");
        }
        Integer paid=0;
        Integer isdel=0;
        Long uid=Long.parseLong(Hmap.get("uid"));
       List<StoreGroupOrderVo>  storeGroupOrderVoList= storeOrderService.getStoreGroupOrder(uid,paid,isdel);
       if (storeGroupOrderVoList!=null&&storeGroupOrderVoList.size()>0){
           //orderListVo 赋值
           int num=0;
           for (StoreGroupOrderVo sgo: storeGroupOrderVoList) {
               Integer[] orderIds= storeOrderService.getOrderIds(sgo.getGroup_order_id());
               List<StoreOrderProductVo> storeOrderProductVoList=storeOrderService.getStoreOrderPorduct(orderIds);
               OrderListVo  orderListVoObj=new OrderListVo();
               for(int i=0;i<orderIds.length;i++){
                   for (StoreOrderProductVo sop: storeOrderProductVoList) {
                       Long orderid=Long.parseLong(orderIds[i]+"");
                       if(sop.getOrder_id().equals(orderid)||sop.getOrder_id()==orderid){
                           orderListVoObj.setOrder_id(orderid);
                           orderListVoObj.getOrderProduct().add(sop);
                           orderListVoObj.setGroup_order_id(sgo.getGroup_order_id());
                           storeGroupOrderVoList.get(num).getOrderList().add(orderListVoObj);

                       }
                   }
               }

            //merchant
               Integer[] merid=new Integer[1];
               merid[0]=Integer.parseInt(sgo.getMer_id()+"");
                List<MerchantVo> merchantVoList=storeCartService.getMerchantVo(merid);
                if(merchantVoList!=null&&merchantVoList.size()>0){
                    storeGroupOrderVoList.get(num).setMerchant(merchantVoList.get(0));
                }
            num++;
           }

       }



       Map<String,Object> data=new HashMap<String,Object>();
       data.put("list",storeGroupOrderVoList);
       return  ResponseUtil.ok(data);
   }

   @PostMapping("/create")
   public Object createOrder(@RequestHeader Map<String,String> Hmap,@RequestBody Map<String,String> bmap){

        if(     !bmap.containsKey("address_id")||!bmap.containsKey("coupon")
                ||!bmap.containsKey("take")||!bmap.containsKey("mark")
                ||!bmap.containsKey("share_id")||!bmap.containsKey("'mer_id'")
                ||!bmap.containsKey("type")||!bmap.containsKey("table_id")
                ||!bmap.containsKey("dacang_id")||!bmap.containsKey("distribution_mode")
                ||!bmap.containsKey("distribution_addres")||!bmap.containsKey("cart_id")
        ){
            ResponseUtil.fail("参数错误");
        }
        if(!Hmap.containsKey("uid")){
            ResponseUtil.fail("uid 参数错误");
        }

       String cartIdStr = bmap.get("cart_id");
       Integer addressId = Integer.parseInt(bmap.get("address_id")+"");
       String coupon = bmap.get("coupon");
       String take = bmap.get ("take");
       String mark = bmap.get("mark");
       String payType =bmap.get("pay_type");
       Integer share_id =Integer.parseInt(bmap.get("share_id"));//分享id
       Long mer_id = Long.parseLong(bmap.get("mer_id"));//分享id
       Integer psType = Integer.parseInt(bmap.get("type"));
       Integer table_id = Integer.parseInt(bmap.get("table_id"));
       Integer dacang_id = Integer.parseInt(bmap.get("dacang_id"));//大仓ID
       String distribution_mode = bmap.get("distribution_mode");//配送方式
       String ziti_address = bmap.get("distribution_address");//自提地址
       Long uid = Long.parseLong(Hmap.get("uid"));
       String[] cartId=cartIdStr.split(",");
//       $gong = app()->make(ProductAttrValueRepository::class);
       //插入购物车日志
       logService.insert("购物车ID---"+cartId);
       BigDecimal price=new BigDecimal(0);
//        if (!in_array($payType, StoreOrderRepository::PAY_TYPE))
//            return app('json')->fail('请选择正确的支付方式');
       Long product_mer_id=storeCartService.queryByUidCartId(null,Long.parseLong(cartId[0]+"")).getMer_id();
//               .getMer_id()  Db::name('store_cart')->where('cart_id',$cartId[0])->value('mer_id');
//       Db::name('log')->insert(['data'=>'商品商户ID---'.$product_mer_id]);
       logService.insert("商品商户ID---"+product_mer_id);
//       Db::name('log')->insert(['data'=>'商户ID---'.$mer_id]);
       logService.insert("商户ID---"+mer_id);
       if(payType.equals("5")){
           if(mer_id==null||product_mer_id!=148){
               return ResponseUtil.fail("此商户不支持积分支付");
           }
           logService.insert("购物车ID"+ JSON.parseArray(cartIdStr));

//           $cartIds=Db::name('store_cart')->where('cart_id','in',$cartId)->select()->toArray();
           List<StoreCart> cartIds =storeCartService.getStoreCartList(cartId);
//           Db::name('log')->insert(['data'=>'购物车数据'.json_encode($cartIds)]);
           logService.insert("购物车数据"+JSON.toJSONString(cartIds));
//           for (StoreCart storecart: cartIds) {
//                //校验
//               gongApiRequest.
//           }
//           foreach ($cartIds as $k=>$item){
//               $checkGong = $gong -> checkGong($item['product_id'],$item['product_attr_unique'],$item['cart_num'],$uid,$addressId);
//               if(isset($checkGong['code']) && $checkGong['code'] == -1) return app('json')->fail($checkGong['message']);
//               $money=Db::name('store_product_attr_value')->where('unique',$item['product_attr_unique'])->value('price');
//               $price+=bcmul($money,$item['cart_num'],2);
//           }
////            $have_money=Db::name('entropy_barter_user_'.$mer_id)->where('uid',$uid)->value('integral');
//           $have_money = Db::name('user') -> where('uid',$uid) -> value('score');
//           if($have_money<$price*30){
//               return app('json')->fail('支付不足不能支付');
//           }


       }
       return ResponseUtil.ok();

   }

}
