package com.sqx.modules.orders.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.orders.vo.CalculatePrice;
import com.sqx.modules.orders.vo.TxDirection;
import com.sqx.modules.orders.dao.OrdersDao;
import com.sqx.modules.orders.dao.PriceRuleDao;
import com.sqx.modules.orders.entity.Orders;
import com.sqx.modules.orders.entity.PriceRule;
import com.sqx.modules.orders.service.OrdersService;
import com.sqx.modules.orders.service.PriceRuleService;
import com.sqx.modules.tbCoupon.entity.TbCoupon;
import com.sqx.modules.tbCoupon.entity.TbCouponUser;
import com.sqx.modules.tbCoupon.service.TbCouponService;
import com.sqx.modules.tbCoupon.service.TbCouponUserService;
import com.sqx.modules.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class PriceRuleServiceImp extends ServiceImpl<PriceRuleDao, PriceRule> implements PriceRuleService {

    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private PriceRuleService priceRuleService;
    @Autowired
    private TbCouponUserService couponUserService;

    @Override
    public CalculatePrice getOrdersPrice(Orders orders){
        BigDecimal couponMoney=BigDecimal.ZERO;
        if(orders.getCouponId()!=null){
            TbCouponUser couponUser = couponUserService.getById(orders.getCouponId());
            couponMoney=couponUser.getMoney();
        }

        //计算距离
        TxDirection txDirection = getDistance(orders.getShipAddressLatitude(), orders.getShipAddressLongitude(), orders.getDeliveryAddressLatitude(), orders.getDeliveryAddressLongitude());
        CalculatePrice calculatePrice=new CalculatePrice();
        //计算公里数
        BigDecimal distance = txDirection.getDistance().divide(new BigDecimal("1000"), 2, RoundingMode.FLOOR);
        calculatePrice.setKmDistance(distance);
        calculatePrice.setDistance(txDirection.getDistance());
        //获取价格列表
        List<PriceRule> priceRuleList = priceRuleService.list(new QueryWrapper<PriceRule>()
                .eq("people_num",orders.getAppointmentNum()).eq("status",1).orderByAsc("start_num"));
        if(priceRuleList.size()==0){
            return null;
        }
        BigDecimal distance1 = calculatePrice.getDistance();
        BigDecimal payMoney=BigDecimal.ZERO;
        for (PriceRule priceRule:priceRuleList){
            //乘客价格
            BigDecimal price=priceRule.getGroupPrice();
            // 获取是独享还是拼座 预约类型 1独享 2拼单
            if(orders.getAppointmentType()==1){
                price=priceRule.getPrice();
            }
            //判断当前公里数 减去当前价格区间公里数后剩余公里数
            BigDecimal num = BigDecimal.valueOf(priceRule.getEndNum()).multiply(BigDecimal.valueOf(1000));
            BigDecimal distance2 = distance1.subtract(num);
            //如果当前公里数已满足 则停止计算
            if(distance2.doubleValue()<=0){
                //判断当前剩下几公里 都按照这个价位计算
                Integer km=0;
                if(distance1.doubleValue()%1000==0){
                    BigDecimal divide = distance1.divide(BigDecimal.valueOf(1000));
                    km=divide.intValue();
                }else{
                    BigDecimal divide = distance1.divide(BigDecimal.valueOf(1000));
                    km=divide.intValue()+1;
                }
                payMoney= payMoney.add(BigDecimal.valueOf(km).multiply(price));
                break;
            }
            distance1 = distance1.subtract(num);
            payMoney= BigDecimal.valueOf(priceRule.getEndNum()).multiply(price);
        }
        calculatePrice.setSumMoney(payMoney.setScale(2, RoundingMode.FLOOR));
        payMoney=payMoney.subtract(couponMoney);
        if(payMoney.doubleValue()<=0){
            payMoney=BigDecimal.valueOf(0.01);
        }
        calculatePrice.setPayMoney(payMoney.setScale(2, RoundingMode.FLOOR));
        calculatePrice.setCouponMoney(couponMoney.setScale(2, RoundingMode.FLOOR));
        return calculatePrice;
    }



    /**
     * @param  
     * @return
     */
    @Override
    public TxDirection getDistance(String lat, String lng, String toLat, String toLng) {
        TxDirection txDirection = new TxDirection();
        CommonInfo one = commonInfoService.findOne(128);
        String url = "https://apis.map.qq.com/ws/direction/v1/driving/";
        Map<String, String> maps = new HashMap<>();
        maps.put("from", lat + "," + lng);
        maps.put("to", toLat + "," + toLng);
        maps.put("key", one.getValue());
        /**
         * get_mp:是否返回多方案，取值：
         * 0 [默认]仅返回一条路线方案
         * 1 返回多方案（最多可返回三条方案供用户备选）
         */
        maps.put("get_mp", "0");
        String data = HttpClientUtil.doGet(url, maps);
        JSONObject jsonObject = JSON.parseObject(data);
        String status = jsonObject.getString("status");
        if ("0".equals(status)) {
            JSONObject result = jsonObject.getJSONObject("result");
            JSONArray routes = result.getJSONArray("routes");
            txDirection.setDistance(new BigDecimal(routes.getJSONObject(0).getString("distance")));
            txDirection.setDuration(new BigDecimal(routes.getJSONObject(0).getString("duration")));
            JSONArray polylineJson = routes.getJSONObject(0).getJSONArray("polyline");

            txDirection.setPolyline(polylineJson.toString());
        } else {
            log.error("路线计算失败:" + jsonObject.getString("message"));
        }
        return txDirection;
    }




}
