<?php

namespace Home\Model;

use Think\Model;

/**
 * 同城配送模型
 * @author fish
 *
 */

class LocaltownDeliveryModel {

    public $table = 'pin';
    public $state_arr = array(
        0 =>'未付款，未配送',
        1=>'已付款，未被抢',
        2=>'已付款，待配送，已被抢单',
        3=>'已拿货，配送中',
        4=>'已送达',
        5=>'已取消'
    );

    /**
     * 计算大约送达时间
     * 大约送达时间的总和为 ：出单时间 + 配送时间
     */
    public function get_order_dispatchtime($seller_goodss)
    {
        $delivery_time = "";
        $total_time = 0;

        foreach($seller_goodss as $store_id=>$v){
            if($store_id == 0){
                $localtown_outorder_time =  D('Home/Front')->get_config_by_name('localtown_outorder_time');//出单时长 分钟

                $localtown_outorder_time = isset($localtown_outorder_time) && $localtown_outorder_time > 0 ? $localtown_outorder_time:0;

                $localtown_delivery_time = D('Home/Front')->get_config_by_name('localtown_delivery_time');

                $localtown_delivery_time = isset($localtown_delivery_time) && $localtown_delivery_time > 0 ? $localtown_delivery_time : 0;

                $total_time_txt = $localtown_outorder_time + $localtown_delivery_time;

                if($total_time_txt > $total_time){
                    $total_time = $total_time_txt;
                }
            }else{
                $localtown_outorder_time =  D('Home/Front')->get_supply_config_by_name('localtown_outorder_time',$store_id);//出单时长 分钟

                $localtown_outorder_time = isset($localtown_outorder_time) && $localtown_outorder_time > 0 ? $localtown_outorder_time:0;

                $localtown_delivery_time = D('Home/Front')->get_supply_config_by_name('localtown_delivery_time',$store_id);

                $localtown_delivery_time = isset($localtown_delivery_time) && $localtown_delivery_time > 0 ? $localtown_delivery_time : 0;

                $total_time_txt = $localtown_outorder_time + $localtown_delivery_time;

                if($total_time_txt > $total_time){
                    $total_time = $total_time_txt;
                }
            }
        }
        //营业时间段是否开启
        $localtown_business_hours_status = D('Home/Front')->get_config_by_name('localtown_business_hours_status');
        //营业开始时间
        $localtown_business_hours_begin = D('Home/Front')->get_config_by_name('localtown_business_hours_begin');
        //营业结束时间
        $localtown_business_hours_end = D('Home/Front')->get_config_by_name('localtown_business_hours_end');
        $delivery_time = date('H:i',strtotime("+".$total_time." minute"));
        if(isset($localtown_business_hours_status) && $localtown_business_hours_status == 1){
            if(strtotime(date('H:i')) < strtotime($localtown_business_hours_begin)){
                $delivery_time = date('H:i',strtotime($localtown_business_hours_begin." +".$total_time." minute"));
            }
            if(strtotime($delivery_time) < strtotime($localtown_business_hours_begin)){
                $delivery_time = date('m-d H:i',strtotime($delivery_time." +1 day"));
            }else{
                if(strtotime($delivery_time) > strtotime($localtown_business_hours_end)){
                    $delivery_time = date('m-d H:i',strtotime($localtown_business_hours_begin." +1 day"));
                }
            }
        }
        return $delivery_time;
    }

    /*
     * 购物车商品的包装费
     *
     *//**
    public function calc_packing_money( $seller_goodss )
    {
        //设置商品统一包装费
        $localtown_delivery_packingmoney = D('Home/Front')->get_config_by_name('localtown_delivery_packingmoney');

        //是否叠加， 0 叠加，1不叠加
        $localtown_superposition_pickingmoney = D('Home/Front')->get_config_by_name('localtown_superposition_pickingmoney');

        $localtown_superposition_pickingmoney = isset($localtown_superposition_pickingmoney) ? $localtown_superposition_pickingmoney : 0;

        $packing_arr = array();


        if( $localtown_superposition_pickingmoney == 0  )
        {
            $picking_totalmoney = 0;
            foreach( $seller_goodss as $store_id => $val)
            {
                $store_packing_fare = 0;

                foreach($val['goods'] as $kk =>$d_goods)
                {
                    $store_packing_fare += $d_goods['packing_free']*$d_goods['quantity'];
                }
                $packing_arr[$store_id] = $store_packing_fare;
                $picking_totalmoney += $store_packing_fare;
            }

            $packing_arr['total_picking_fare'] = $picking_totalmoney;

            return $packing_arr;

        }else if( $localtown_superposition_pickingmoney == 1 )//todo..不叠加的包装费
        {

            $picking_totalmoney = 0;
            foreach( $seller_goodss as $store_id => $val)
            {
                $store_packing_fare = 0;

                foreach($val['goods'] as $kk =>$d_goods)
                {
                    if( $d_goods['packing_free'] > $store_packing_fare )
                    {
                        $store_packing_fare = $d_goods['packing_free'];
                    }
                }
                $packing_arr[$store_id] = $store_packing_fare;
                $picking_totalmoney += $store_packing_fare;
            }

            $packing_arr['total_picking_fare'] = $picking_totalmoney;

            return $packing_arr;

        }

    }*/

    /**
     * 购物车商品的包装费
     *
     */
    public function calc_packing_money( $seller_goodss )
    {
        $packing_arr = array();
        $total_picking_fare = 0;
        foreach( $seller_goodss as $store_id => $val)
        {
            if($store_id == 0){
                //设置商品统一包装费
                $localtown_delivery_packingmoney = D('Home/Front')->get_config_by_name('localtown_delivery_packingmoney');
                //是否叠加， 0 叠加，1不叠加
                $localtown_superposition_pickingmoney = D('Home/Front')->get_config_by_name('localtown_superposition_pickingmoney');
                $localtown_superposition_pickingmoney = isset($localtown_superposition_pickingmoney) ? $localtown_superposition_pickingmoney : 0;

                $picking_totalmoney = 0;
                $store_packing_fare = 0;
                if( $localtown_superposition_pickingmoney == 0  )
                {

                    foreach($val['goods'] as $kk =>$d_goods)
                    {
                        $store_packing_fare += $d_goods['packing_free']*$d_goods['quantity'];
                    }
                    $packing_arr[$store_id] = $store_packing_fare;
                    $picking_totalmoney += $store_packing_fare;


                    $total_picking_fare = $total_picking_fare + $picking_totalmoney;

                }else if( $localtown_superposition_pickingmoney == 1 )//todo..不叠加的包装费
                {

                    foreach($val['goods'] as $kk =>$d_goods)
                    {
                        if( $d_goods['packing_free'] > $store_packing_fare )
                        {
                            $store_packing_fare = $d_goods['packing_free'];
                        }
                    }
                    $packing_arr[$store_id] = $store_packing_fare;
                    $picking_totalmoney += $store_packing_fare;
                    $total_picking_fare = $total_picking_fare + $picking_totalmoney;
                }
            }else{
                //设置商品统一包装费
                $localtown_delivery_packingmoney = D('Home/Front')->get_supply_config_by_name('localtown_delivery_packingmoney',$store_id);
                //是否叠加， 0 叠加，1不叠加
                $localtown_superposition_pickingmoney = D('Home/Front')->get_supply_config_by_name('localtown_superposition_pickingmoney',$store_id);
                $localtown_superposition_pickingmoney = isset($localtown_superposition_pickingmoney) ? $localtown_superposition_pickingmoney : 0;

                $picking_totalmoney = 0;
                $store_packing_fare = 0;
                if( $localtown_superposition_pickingmoney == 0  )
                {

                    foreach($val['goods'] as $kk =>$d_goods)
                    {
                        $store_packing_fare += $d_goods['packing_free']*$d_goods['quantity'];
                    }
                    $packing_arr[$store_id] = $store_packing_fare;
                    $picking_totalmoney += $store_packing_fare;


                    $total_picking_fare = $total_picking_fare + $picking_totalmoney;

                }else if( $localtown_superposition_pickingmoney == 1 )//todo..不叠加的包装费
                {

                    foreach($val['goods'] as $kk =>$d_goods)
                    {
                        if( $d_goods['packing_free'] > $store_packing_fare )
                        {
                            $store_packing_fare = $d_goods['packing_free'];
                        }
                    }
                    $packing_arr[$store_id] = $store_packing_fare;
                    $picking_totalmoney += $store_packing_fare;
                    $total_picking_fare = $total_picking_fare + $picking_totalmoney;

                }
            }
        }
        $packing_arr['total_picking_fare'] = $total_picking_fare;

        return $packing_arr;
    }

    /**
     * 计算购物车商品配送费
     *
     * D('Home/LocaltownDelivery')->calc_shipping_fare( $lon, $lat , $seller_goodss );

    public function calc_shipping_fare( $lon, $lat , $seller_goodss )
    {

        $localtown_delivery_moneytype = D('Home/Front')->get_config_by_name('localtown_delivery_moneytype');
        $localtown_delivery_moneytype = isset($localtown_delivery_moneytype) ? $localtown_delivery_moneytype : 0;

        /**
         * 结构：
         * store_id
         *          shipping_fare =x
         *          is_fare_shipping = 1/0
         *          qi_fare_money =x
         *          is_can_qisong = 1
         *
         * total_info
         *          shipping_fare =x
         *          is_fare_shipping = 1/0
         *          qi_fare_money =x
         *          is_can_qisong = 1
         *
         * localtown_moneytype_fixed_money


        if( $localtown_delivery_moneytype == 0 )
        {
            //配送费
            $localtown_moneytype_fixed_money = D('Home/Front')->get_config_by_name('localtown_moneytype_fixed_money');
            $localtown_moneytype_fixed_money = isset($localtown_moneytype_fixed_money) ? $localtown_moneytype_fixed_money : 0;

            //起送价格
            $localtown_moneytype_fixed_deliverymoney = D('Home/Front')->get_config_by_name('localtown_moneytype_fixed_deliverymoney');
            $localtown_moneytype_fixed_deliverymoney = isset($localtown_moneytype_fixed_deliverymoney) ? $localtown_moneytype_fixed_deliverymoney : 0;

            //达到多少免配送费
            $localtown_moneytype_fixed_freemoney = D('Home/Front')->get_config_by_name('localtown_moneytype_fixed_freemoney');
            $localtown_moneytype_fixed_freemoney = isset($localtown_moneytype_fixed_freemoney) ? $localtown_moneytype_fixed_freemoney : 0;

            //加价配送费
            $localtown_makeup_delivery_money = D('Home/Front')->get_config_by_name('localtown_makeup_delivery_money');
            $localtown_makeup_delivery_money = isset($localtown_makeup_delivery_money) ? $localtown_makeup_delivery_money : 0;

            $shipping_fare_arr = array();
            $total_shipping_fare = 0;//这一单所有的配送费
            $total_yl_shipping_fare = 0;//这一单原来配送费
            //固定配送费
            foreach( $seller_goodss as $store_id => $val)
            {
                $store_total_fare = 0;
                $store_shipping_fare = $localtown_moneytype_fixed_money;//运费
                $is_can_qisong =0;
                $is_fare_shipping = 0;
                $yl_shipping_fare = 0;//这一单原来配送费
                $localtown_add_shipping_fare = 0;//订单加价配送费
                foreach($val['goods'] as $kk =>$d_goods)
                {
                    $store_total_fare += $d_goods['total'];
                }
                $yl_shipping_fare = $store_shipping_fare;
                //先判断是否免配送费
                if( $localtown_moneytype_fixed_freemoney > 0 && $store_total_fare >= $localtown_moneytype_fixed_freemoney)
                {
                    $store_shipping_fare = 0;
                    $is_fare_shipping = 1;
                }
                //判断是否符合起送价格
                if( $store_total_fare >=$localtown_moneytype_fixed_deliverymoney )
                {
                    $is_can_qisong = 1;
                }else{
                    if($localtown_moneytype_fixed_deliverymoney > 0){
                        $localtown_add_shipping_fare = $localtown_makeup_delivery_money;
                    }
                }
                $total_shipping_fare += $store_shipping_fare;
                $total_yl_shipping_fare += $yl_shipping_fare;
                $shipping_fare_arr[$store_id] = array(
                                        'shipping_fare' => $store_shipping_fare,
                                        'is_can_qisong' => $is_can_qisong,
                                        'is_fare_shipping' => $is_fare_shipping,
                                        'store_total_fare' => $store_total_fare,
                                        'yl_shipping_fare'=>$yl_shipping_fare,
                                        'localtown_add_shipping_fare'=>$localtown_add_shipping_fare
                                    );


            }
            $shipping_fare_arr['total_shipping_fare'] = $total_shipping_fare;
            $shipping_fare_arr['total_yl_shipping_fare'] = $total_yl_shipping_fare;
            return $shipping_fare_arr;

        }else if( $localtown_delivery_moneytype == 1 ){
            //根据距离计算配送费

            //起步价
            $localtown_moneytype_basedistance_deliverymoney = D('Home/Front')->get_config_by_name('localtown_moneytype_basedistance_deliverymoney');
            $localtown_moneytype_basedistance_deliverymoney = isset($localtown_moneytype_basedistance_deliverymoney) ? $localtown_moneytype_basedistance_deliverymoney : 0;

            //起送价格
            $localtown_moneytype_fixed_deliverymoney = D('Home/Front')->get_config_by_name('localtown_moneytype_fixed_deliverymoney');
            $localtown_moneytype_fixed_deliverymoney = isset($localtown_moneytype_fixed_deliverymoney) ? $localtown_moneytype_fixed_deliverymoney : 0;

            //达到多少免配送费
            $localtown_moneytype_fixed_freemoney = D('Home/Front')->get_config_by_name('localtown_moneytype_fixed_freemoney');
            $localtown_moneytype_fixed_freemoney = isset($localtown_moneytype_fixed_freemoney) ? $localtown_moneytype_fixed_freemoney : 0;

            //配送范围内公里数
            $localtown_moneytype_basedistance = D('Home/Front')->get_config_by_name('localtown_moneytype_basedistance');
            $localtown_moneytype_basedistance = isset($localtown_moneytype_basedistance) && $localtown_moneytype_basedistance > 0 ? $localtown_moneytype_basedistance: 0;

            //超出配送范围内， 每公里收取多少钱
            $localtown_moneytype_base_perkmaddmoney = D('Home/Front')->get_config_by_name('localtown_moneytype_base_perkmaddmoney');
            $localtown_moneytype_base_perkmaddmoney = isset($localtown_moneytype_base_perkmaddmoney) && $localtown_moneytype_base_perkmaddmoney >0 ? $localtown_moneytype_base_perkmaddmoney : 0;

            //最多收取配送费多少钱
            $localtown_moneytype_base_maxdeliverymoney = D('Home/Front')->get_config_by_name('localtown_moneytype_base_maxdeliverymoney');
            $localtown_moneytype_base_maxdeliverymoney = isset($localtown_moneytype_base_maxdeliverymoney) && $localtown_moneytype_base_maxdeliverymoney > 0 ? $localtown_moneytype_base_maxdeliverymoney : 0;

            //商家位置经纬度
            $localtown_shop_lon = D('Home/Front')->get_config_by_name('localtown_shop_lon');
            $localtown_shop_lon = isset($localtown_shop_lon) && $localtown_shop_lon > 0 ? $localtown_shop_lon : 0;

            $localtown_shop_lat = D('Home/Front')->get_config_by_name('localtown_shop_lat');
            $localtown_shop_lat = isset($localtown_shop_lat) && $localtown_shop_lat >0 ? $localtown_shop_lat:0;


            $distince = D('Seller/Communityhead')->GetDistance($localtown_shop_lon,$localtown_shop_lat, $lon, $lat);

            $distince = ceil($distince / 1000);//KM距离

            $shipping_fare_arr = array();
            $total_shipping_fare = 0;//这一单所有的配送费
            $total_yl_shipping_fare = 0;//这一单原来配送费
            $localtown_add_shipping_fare = 0;//订单加价配送费
            //固定配送费
            foreach( $seller_goodss as $store_id => $val) {
                $yl_shipping_fare = 0;//这一单原来配送费
                $store_total_fare = 0;
                //$store_shipping_fare = $localtown_moneytype_fixed_money;//运费

                if( $distince > $localtown_moneytype_basedistance )
                {
                    $store_shipping_fare = $localtown_moneytype_basedistance_deliverymoney + ($distince - $localtown_moneytype_basedistance ) * $localtown_moneytype_base_perkmaddmoney;
                    if( $localtown_moneytype_base_maxdeliverymoney > 0 && $store_shipping_fare > $localtown_moneytype_base_maxdeliverymoney  )
                    {
                        $store_shipping_fare = $localtown_moneytype_base_maxdeliverymoney;
                    }
                }else {
                    $store_shipping_fare = $localtown_moneytype_basedistance_deliverymoney;
                }

                $is_can_qisong = 1;
                $is_fare_shipping = 0;

                foreach ($val['goods'] as $kk => $d_goods) {
                    $store_total_fare += $d_goods['total'];
                }

               //先判断是否免配送费
                if( $localtown_moneytype_fixed_freemoney > 0 && $store_total_fare > $localtown_moneytype_fixed_freemoney)
                {
                    $store_shipping_fare = 0;
                    $is_fare_shipping = 1;
                }
                //判断是否符合起送价格
                /*if( $store_total_fare >=$localtown_moneytype_fixed_deliverymoney )
                {
                    $is_can_qisong = 1;
                }
                $total_shipping_fare += $store_shipping_fare;
                $yl_shipping_fare = $store_shipping_fare;
                $total_yl_shipping_fare += $yl_shipping_fare;
                $shipping_fare_arr[$store_id] = array(
                    'shipping_fare' => $store_shipping_fare,
                    'is_can_qisong' => $is_can_qisong,
                    'is_fare_shipping' => $is_fare_shipping,
                    'store_total_fare' => $store_total_fare,
                    'yl_shipping_fare' => $yl_shipping_fare,
                    'localtown_add_shipping_fare'=>$localtown_add_shipping_fare
                );

            }
            $shipping_fare_arr['total_shipping_fare'] = $total_shipping_fare;
            $shipping_fare_arr['total_yl_shipping_fare'] = $total_yl_shipping_fare;
            return $shipping_fare_arr;

        }

    }*/


    /**
     * @author cy 2020.08.03
     * 计算购物车商品配送费
     *
     * D('Home/LocaltownDelivery')->calc_shipping_fare( $lon, $lat , $seller_goodss );
    */
    public function calc_shipping_fare( $lon, $lat , $seller_goodss )
    {
        $shipping_fare_arr = array();
        $total_shipping_fare = 0;//这一单所有的配送费
        $total_yl_shipping_fare = 0;//这一单原来配送费
        foreach( $seller_goodss as $store_id => $val){
            if($store_id == 0){//平台自营
                $localtown_delivery_moneytype = D('Home/Front')->get_config_by_name('localtown_delivery_moneytype');
                $localtown_delivery_moneytype = isset($localtown_delivery_moneytype) ? $localtown_delivery_moneytype : 0;
                if( $localtown_delivery_moneytype == 0 )
                {
                    //配送费
                    $localtown_moneytype_fixed_money = D('Home/Front')->get_config_by_name('localtown_moneytype_fixed_money');
                    $localtown_moneytype_fixed_money = isset($localtown_moneytype_fixed_money) ? $localtown_moneytype_fixed_money : 0;

                    //起送价格
                    $localtown_moneytype_fixed_deliverymoney = D('Home/Front')->get_config_by_name('localtown_moneytype_fixed_deliverymoney');
                    $localtown_moneytype_fixed_deliverymoney = isset($localtown_moneytype_fixed_deliverymoney) ? $localtown_moneytype_fixed_deliverymoney : 0;

                    //达到多少免配送费
                    $localtown_moneytype_fixed_freemoney = D('Home/Front')->get_config_by_name('localtown_moneytype_fixed_freemoney');
                    $localtown_moneytype_fixed_freemoney = isset($localtown_moneytype_fixed_freemoney) ? $localtown_moneytype_fixed_freemoney : 0;

                    //加价配送费
                    $localtown_makeup_delivery_money = D('Home/Front')->get_config_by_name('localtown_makeup_delivery_money');
                    $localtown_makeup_delivery_money = isset($localtown_makeup_delivery_money) ? $localtown_makeup_delivery_money : 0;

                    $store_total_fare = 0;//订单总金额
                    $store_shipping_fare = $localtown_moneytype_fixed_money;//运费
                    $is_can_qisong = 0;
                    $is_fare_shipping = 0;
                    $yl_shipping_fare = 0;//这一单原来配送费
                    $localtown_add_shipping_fare = 0;//订单加价配送费
                    foreach($val['goods'] as $kk =>$d_goods)
                    {
                        $store_total_fare += $d_goods['total'];
                    }
                    $yl_shipping_fare = $store_shipping_fare;
                    //先判断是否免配送费
                    if( $localtown_moneytype_fixed_freemoney > 0 && $store_total_fare >= $localtown_moneytype_fixed_freemoney)
                    {
                        $store_shipping_fare = 0;
                        $is_fare_shipping = 1;
                    }
                    //判断是否符合起送价格
                    if( $store_total_fare >=$localtown_moneytype_fixed_deliverymoney )
                    {
                        $is_can_qisong = 1;
                    }else{
                        if($localtown_moneytype_fixed_deliverymoney > 0){
                            $localtown_add_shipping_fare = $localtown_makeup_delivery_money;
                        }
                    }
                    $total_shipping_fare += $store_shipping_fare;
                    $total_yl_shipping_fare += $yl_shipping_fare;
                    $shipping_fare_arr[$store_id] = array(
                        'shipping_fare' => $store_shipping_fare,
                        'is_can_qisong' => $is_can_qisong,
                        'is_fare_shipping' => $is_fare_shipping,
                        'store_total_fare' => $store_total_fare,
                        'yl_shipping_fare'=>$yl_shipping_fare,
                        'localtown_add_shipping_fare'=>$localtown_add_shipping_fare
                    );
                }else if( $localtown_delivery_moneytype == 1 ) {
                    //根据距离计算配送费
                    //起步价
                    $localtown_moneytype_basedistance_deliverymoney = D('Home/Front')->get_config_by_name('localtown_moneytype_basedistance_deliverymoney');
                    $localtown_moneytype_basedistance_deliverymoney = isset($localtown_moneytype_basedistance_deliverymoney) ? $localtown_moneytype_basedistance_deliverymoney : 0;

                    //起送价格
                    /*$localtown_moneytype_fixed_deliverymoney = D('Home/Front')->get_config_by_name('localtown_moneytype_fixed_deliverymoney');
                    $localtown_moneytype_fixed_deliverymoney = isset($localtown_moneytype_fixed_deliverymoney) ? $localtown_moneytype_fixed_deliverymoney : 0;

                    //达到多少免配送费
                    $localtown_moneytype_fixed_freemoney = D('Home/Front')->get_config_by_name('localtown_moneytype_fixed_freemoney');
                    $localtown_moneytype_fixed_freemoney = isset($localtown_moneytype_fixed_freemoney) ? $localtown_moneytype_fixed_freemoney : 0;*/

                    //配送范围内公里数
                    $localtown_moneytype_basedistance = D('Home/Front')->get_config_by_name('localtown_moneytype_basedistance');
                    $localtown_moneytype_basedistance = isset($localtown_moneytype_basedistance) && $localtown_moneytype_basedistance > 0 ? $localtown_moneytype_basedistance : 0;

                    //超出配送范围内， 每公里收取多少钱
                    $localtown_moneytype_base_perkmaddmoney = D('Home/Front')->get_config_by_name('localtown_moneytype_base_perkmaddmoney');
                    $localtown_moneytype_base_perkmaddmoney = isset($localtown_moneytype_base_perkmaddmoney) && $localtown_moneytype_base_perkmaddmoney > 0 ? $localtown_moneytype_base_perkmaddmoney : 0;

                    //最多收取配送费多少钱
                    $localtown_moneytype_base_maxdeliverymoney = D('Home/Front')->get_config_by_name('localtown_moneytype_base_maxdeliverymoney');
                    $localtown_moneytype_base_maxdeliverymoney = isset($localtown_moneytype_base_maxdeliverymoney) && $localtown_moneytype_base_maxdeliverymoney > 0 ? $localtown_moneytype_base_maxdeliverymoney : 0;

                    //商家位置经纬度
                    $localtown_shop_lon = D('Home/Front')->get_config_by_name('localtown_shop_lon');
                    $localtown_shop_lon = isset($localtown_shop_lon) && $localtown_shop_lon > 0 ? $localtown_shop_lon : 0;

                    $localtown_shop_lat = D('Home/Front')->get_config_by_name('localtown_shop_lat');
                    $localtown_shop_lat = isset($localtown_shop_lat) && $localtown_shop_lat > 0 ? $localtown_shop_lat : 0;

                    $distince = D('Seller/Communityhead')->GetDistance($localtown_shop_lon, $localtown_shop_lat, $lon, $lat);

                    $distince = ceil($distince / 1000);//KM距离

                    $localtown_add_shipping_fare = 0;//订单加价配送费

                    $yl_shipping_fare = 0;//这一单原来配送费
                    $store_total_fare = 0;
                    $store_shipping_fare = 0;//配送运费

                    if ($distince > $localtown_moneytype_basedistance) {
                        $store_shipping_fare = $localtown_moneytype_basedistance_deliverymoney + ($distince - $localtown_moneytype_basedistance) * $localtown_moneytype_base_perkmaddmoney;
                        if ($localtown_moneytype_base_maxdeliverymoney > 0 && $store_shipping_fare > $localtown_moneytype_base_maxdeliverymoney) {
                            $store_shipping_fare = $localtown_moneytype_base_maxdeliverymoney;
                        }
                    } else {
                        $store_shipping_fare = $localtown_moneytype_basedistance_deliverymoney;
                    }

                    $is_can_qisong = 1;
                    $is_fare_shipping = 0;

                    foreach($val['goods'] as $kk =>$d_goods)
                    {
                        $store_total_fare += $d_goods['total'];
                    }

                    $total_shipping_fare += $store_shipping_fare;
                    $yl_shipping_fare = $store_shipping_fare;
                    $total_yl_shipping_fare += $yl_shipping_fare;
                    $shipping_fare_arr[$store_id] = array(
                        'shipping_fare' => $store_shipping_fare,
                        'is_can_qisong' => $is_can_qisong,
                        'is_fare_shipping' => $is_fare_shipping,
                        'store_total_fare' => $store_total_fare,
                        'yl_shipping_fare' => $yl_shipping_fare,
                        'localtown_add_shipping_fare' => $localtown_add_shipping_fare
                    );
                }
            }else if($store_id > 0){//供应商商品

                $localtown_delivery_moneytype = D('Home/Front')->get_supply_config_by_name('localtown_delivery_moneytype',$store_id);
                $localtown_delivery_moneytype = isset($localtown_delivery_moneytype) ? $localtown_delivery_moneytype : 0;
                if( $localtown_delivery_moneytype == 0 )
                {
                    //配送费
                    $localtown_moneytype_fixed_money = D('Home/Front')->get_supply_config_by_name('localtown_moneytype_fixed_money',$store_id);
                    $localtown_moneytype_fixed_money = isset($localtown_moneytype_fixed_money) ? $localtown_moneytype_fixed_money : 0;

                    //起送价格
                    $localtown_moneytype_fixed_deliverymoney = D('Home/Front')->get_supply_config_by_name('localtown_moneytype_fixed_deliverymoney',$store_id);
                    $localtown_moneytype_fixed_deliverymoney = isset($localtown_moneytype_fixed_deliverymoney) ? $localtown_moneytype_fixed_deliverymoney : 0;

                    //达到多少免配送费
                    $localtown_moneytype_fixed_freemoney = D('Home/Front')->get_supply_config_by_name('localtown_moneytype_fixed_freemoney',$store_id);
                    $localtown_moneytype_fixed_freemoney = isset($localtown_moneytype_fixed_freemoney) ? $localtown_moneytype_fixed_freemoney : 0;

                    //加价配送费
                    $localtown_makeup_delivery_money = D('Home/Front')->get_supply_config_by_name('localtown_makeup_delivery_money',$store_id);
                    $localtown_makeup_delivery_money = isset($localtown_makeup_delivery_money) ? $localtown_makeup_delivery_money : 0;

                    $store_total_fare = 0;//订单总金额
                    $store_shipping_fare = $localtown_moneytype_fixed_money;//运费
                    $is_can_qisong = 0;
                    $is_fare_shipping = 0;
                    $yl_shipping_fare = 0;//这一单原来配送费
                    $localtown_add_shipping_fare = 0;//订单加价配送费
                    foreach($val['goods'] as $kk =>$d_goods)
                    {
                        $store_total_fare += $d_goods['total'];
                    }
                    $yl_shipping_fare = $store_shipping_fare;
                    //先判断是否免配送费
                    if( $localtown_moneytype_fixed_freemoney > 0 && $store_total_fare >= $localtown_moneytype_fixed_freemoney)
                    {
                        $store_shipping_fare = 0;
                        $is_fare_shipping = 1;
                    }
                    //判断是否符合起送价格
                    if( $store_total_fare >=$localtown_moneytype_fixed_deliverymoney )
                    {
                        $is_can_qisong = 1;
                    }else{
                        if($localtown_moneytype_fixed_deliverymoney > 0){
                            $localtown_add_shipping_fare = $localtown_makeup_delivery_money;
                        }
                    }
                    $total_shipping_fare += $store_shipping_fare;
                    $total_yl_shipping_fare += $yl_shipping_fare;
                    $shipping_fare_arr[$store_id] = array(
                        'shipping_fare' => $store_shipping_fare,
                        'is_can_qisong' => $is_can_qisong,
                        'is_fare_shipping' => $is_fare_shipping,
                        'store_total_fare' => $store_total_fare,
                        'yl_shipping_fare'=>$yl_shipping_fare,
                        'localtown_add_shipping_fare'=>$localtown_add_shipping_fare
                    );
                }else if( $localtown_delivery_moneytype == 1 ) {
                    //根据距离计算配送费
                    //起步价
                    $localtown_moneytype_basedistance_deliverymoney = D('Home/Front')->get_supply_config_by_name('localtown_moneytype_basedistance_deliverymoney',$store_id);
                    $localtown_moneytype_basedistance_deliverymoney = isset($localtown_moneytype_basedistance_deliverymoney) ? $localtown_moneytype_basedistance_deliverymoney : 0;

                    //配送范围内公里数
                    $localtown_moneytype_basedistance = D('Home/Front')->get_supply_config_by_name('localtown_moneytype_basedistance',$store_id);
                    $localtown_moneytype_basedistance = isset($localtown_moneytype_basedistance) && $localtown_moneytype_basedistance > 0 ? $localtown_moneytype_basedistance : 0;

                    //超出配送范围内， 每公里收取多少钱
                    $localtown_moneytype_base_perkmaddmoney = D('Home/Front')->get_supply_config_by_name('localtown_moneytype_base_perkmaddmoney',$store_id);
                    $localtown_moneytype_base_perkmaddmoney = isset($localtown_moneytype_base_perkmaddmoney) && $localtown_moneytype_base_perkmaddmoney > 0 ? $localtown_moneytype_base_perkmaddmoney : 0;

                    //最多收取配送费多少钱
                    $localtown_moneytype_base_maxdeliverymoney = D('Home/Front')->get_supply_config_by_name('localtown_moneytype_base_maxdeliverymoney',$store_id);
                    $localtown_moneytype_base_maxdeliverymoney = isset($localtown_moneytype_base_maxdeliverymoney) && $localtown_moneytype_base_maxdeliverymoney > 0 ? $localtown_moneytype_base_maxdeliverymoney : 0;

                    //商家位置经纬度
                    $localtown_shop_lon = D('Home/Front')->get_supply_config_by_name('localtown_shop_lon',$store_id);
                    $localtown_shop_lon = isset($localtown_shop_lon) && $localtown_shop_lon > 0 ? $localtown_shop_lon : 0;

                    $localtown_shop_lat = D('Home/Front')->get_supply_config_by_name('localtown_shop_lat',$store_id);
                    $localtown_shop_lat = isset($localtown_shop_lat) && $localtown_shop_lat > 0 ? $localtown_shop_lat : 0;

                    $distince = D('Seller/Communityhead')->GetDistance($localtown_shop_lon, $localtown_shop_lat, $lon, $lat);

                    $distince = ceil($distince / 1000);//KM距离

                    $localtown_add_shipping_fare = 0;//订单加价配送费

                    $yl_shipping_fare = 0;//这一单原来配送费
                    $store_total_fare = 0;
                    $store_shipping_fare = 0;//配送运费

                    if ($distince > $localtown_moneytype_basedistance) {
                        $store_shipping_fare = $localtown_moneytype_basedistance_deliverymoney + ($distince - $localtown_moneytype_basedistance) * $localtown_moneytype_base_perkmaddmoney;
                        if ($localtown_moneytype_base_maxdeliverymoney > 0 && $store_shipping_fare > $localtown_moneytype_base_maxdeliverymoney) {
                            $store_shipping_fare = $localtown_moneytype_base_maxdeliverymoney;
                        }
                    } else {
                        $store_shipping_fare = $localtown_moneytype_basedistance_deliverymoney;
                    }

                    $is_can_qisong = 1;
                    $is_fare_shipping = 0;

                    foreach($val['goods'] as $kk =>$d_goods)
                    {
                        $store_total_fare += $d_goods['total'];
                    }

                    $total_shipping_fare += $store_shipping_fare;
                    $yl_shipping_fare = $store_shipping_fare;
                    $total_yl_shipping_fare += $yl_shipping_fare;
                    $shipping_fare_arr[$store_id] = array(
                        'shipping_fare' => $store_shipping_fare,
                        'is_can_qisong' => $is_can_qisong,
                        'is_fare_shipping' => $is_fare_shipping,
                        'store_total_fare' => $store_total_fare,
                        'yl_shipping_fare' => $yl_shipping_fare,
                        'localtown_add_shipping_fare' => $localtown_add_shipping_fare
                    );
                }
            }
        }
        $shipping_fare_arr['total_shipping_fare'] = $total_shipping_fare;
        $shipping_fare_arr['total_yl_shipping_fare'] = $total_yl_shipping_fare;
        return $shipping_fare_arr;
    }

    /**
     * 更改配送单状态，改为已支付TODO
     */
    public function change_distribution_order_state( $order_id, $orderdistribution_id, $state, $is_front)
    {

        switch( $state )
        {
            case 1://已付款，备货中
                M('lionfish_comshop_orderdistribution_order')->where( array('order_id' => $order_id) )->save( array('state' => 1) );
				$info = M('lionfish_comshop_orderdistribution_order')->where( array('order_id' => $order_id) )->find();
				$this->write_redis_distribution_info( $info['id'] );
				
                $remark = '商家已接单';
                $this->write_distribution_log( $order_id, $orderdistribution_id, $state, $remark );

                break;
            case 2://2 已付款，待配送，已被抢单
                
				
				M('lionfish_comshop_orderdistribution_order')->where( array('order_id' => $order_id , 'orderdistribution_id' => $orderdistribution_id ) )->save( array('state' => 2) );
               
			    $info = M('lionfish_comshop_orderdistribution_order')->where( array('order_id' => $order_id) )->find();
                $this->del_redis_distribution_info( $info['id'] );
				
				$orderdistribution = M('lionfish_comshop_orderdistribution')->where( array('id' => $orderdistribution_id ) )->find();
                $remark = '配送员:'.$orderdistribution['username'].',抢单成功';
                $this->write_distribution_log( $order_id, $orderdistribution_id , $state ,$remark );
                
				break;
            case 3://3，已拿货，配送中
                M('lionfish_comshop_orderdistribution_order')->where( array('order_id' => $order_id , 'orderdistribution_id' => $orderdistribution_id ) )->save( array('state' => 3) );
                $orderdistribution = M('lionfish_comshop_orderdistribution')->where( array('id' => $orderdistribution_id ) )->find();
                $remark = '配送员:'.$orderdistribution['username'].', 已到店拿货，配送中';
                $this->write_distribution_log( $order_id, $orderdistribution_id , $state ,$remark );
                break;
            case 4://4、已送达
                M('lionfish_comshop_orderdistribution_order')->where( array('order_id' => $order_id , 'orderdistribution_id' => $orderdistribution_id ) )->save( array('state' => 4) );
                $orderdistribution = M('lionfish_comshop_orderdistribution')->where( array('id' => $orderdistribution_id ) )->find();
                $remark = '配送员:'.$orderdistribution['username'].', 配送完成';
                
				M('lionfish_comshop_orderdistribution')->where( array('id' => $orderdistribution_id ) )->setInc('has_send_count', 1);
				
				$this->write_distribution_log( $order_id, $orderdistribution_id , $state ,$remark );
                if($is_front){
                    D('Home/Frontorder')->receive_order($order_id);
                }
                break;
        }
    }

    /**
     * 第三方配送公司 更改配送单状态，改为已支付TODO
     */
    public function change_thirth_distribution_order_state( $order_id, $state, $other_data)
    {

        switch( $state )
        {
            case 1://已付款，备货中
                if($other_data['data_type'] == 'imdada'){
                    M('lionfish_comshop_orderdistribution_order')->where( array('order_id' => $order_id) )->save(
                        array('state' => 1,'shipping_money'=>$other_data['delivery_fee'],'third_distribution_type'=>$other_data['data_type'],
                            'is_admin_assign'=>1,'delivery_type'=>2) );
                }else if($other_data['data_type'] == 'sf'){
                    M('lionfish_comshop_orderdistribution_order')->where( array('order_id' => $order_id) )->save(
                        array('state' => 1,
                             'shipping_money'=>$other_data['delivery_fee'],
                            'third_distribution_type'=>$other_data['data_type'],
                            'is_admin_assign'=>1,
                            'third_id'=>$other_data['delivery_bill_id'],
                            'third_order_id'=>$other_data['delivery_order_id'],'delivery_type'=>2
                        )
                    );
                }else if( $other_data['data_type'] == 'make' )
                {
					M('lionfish_comshop_orderdistribution_order')->where( array('order_id' => $order_id) )->save(
                        array('state' => 1,'shipping_money'=>$other_data['delivery_fee'],
                                'third_distribution_type'=>$other_data['data_type'],
                                'third_order_id'=>$other_data['delivery_order_id'],
                                'is_admin_assign'=>1)
                    );
				}else if($other_data['data_type'] == 'ele'){//蜂鸟即配
                    M('lionfish_comshop_orderdistribution_order')->where( array('order_id' => $order_id) )->save(
                        array('state' => 1,
                            'shipping_money'=>$other_data['delivery_fee'],
                            'third_distribution_type'=>$other_data['data_type'],
                            'is_admin_assign'=>1,
                            'third_order_id'=>$other_data['delivery_order_id'],
                            'delivery_type'=>2
                        )
                    );
                }
                $remark = $other_data['delivery_company'].'已接单';
                $this->write_distribution_log( $order_id, 0, $state, $remark );

                break;
            case 2://2 已付款，待配送，已被抢单
                if($other_data['data_type'] == 'imdada'){
                    $res = M('lionfish_comshop_orderdistribution_order')->where( array('order_id' => $order_id) )->save(
                        array('state' => 2,'dm_id'=>$other_data['dm_id'],'dm_name'=>$other_data['dm_name'],'dm_mobile'=>$other_data['dm_mobile'],'third_id'=>$other_data['third_id'])
                    );
                    $info = M('lionfish_comshop_orderdistribution_order')->where( array('order_id' => $order_id) )->find();
                    $this->del_redis_distribution_info( $info['id'] );

                    $remark = $other_data['delivery_company'].'配送员:'.$other_data['dm_name'].'已接单待取货';
                    $this->write_distribution_log( $order_id, 0 , $state ,$remark );
                }else if($other_data['data_type'] == 'sf'){
                    $res = M('lionfish_comshop_orderdistribution_order')->where( array('order_id' => $order_id) )->save(
                        array('state' => 2,'dm_name'=>$other_data['operator_name'],'dm_mobile'=>$other_data['operator_phone'])
                    );
                    $info = M('lionfish_comshop_orderdistribution_order')->where( array('order_id' => $order_id) )->find();
                    $this->del_redis_distribution_info( $info['id'] );

                    $operator_action = "";
                    if($other_data['order_status'] == 10){
                        $operator_action = "确认订单";
                    }else if($other_data['order_status'] == 12){
                        $operator_action = "到店";
                    }
                    $remark = $other_data['delivery_company'].'配送员:'.$other_data['operator_name'].$operator_action;
                    $this->write_distribution_log( $order_id, 0 , $state ,$remark );
                }else if($other_data['data_type'] == 'make'){
					M('lionfish_comshop_orderdistribution_order')->where( array('order_id' => $order_id) )->save(
                       array('state' => 2,'dm_name'=>$other_data['dm_name'],'dm_mobile'=>$other_data['dm_mobile'])
                    );
					$info = M('lionfish_comshop_orderdistribution_order')->where( array('order_id' => $order_id) )->find();

                    $remark = $other_data['delivery_company'].'配送员:'.$other_data['dm_name'].'已接单待取货';
                    $this->write_distribution_log( $order_id, 0 , $state ,$remark );
                }else if($other_data['data_type'] == 'ele'){//蜂鸟即配
                    M('lionfish_comshop_orderdistribution_order')->where( array('order_id' => $order_id) )->save(
                        array('state' => 2,'dm_name'=>$other_data['operator_name'],'dm_mobile'=>$other_data['operator_phone'])
                    );
                    $info = M('lionfish_comshop_orderdistribution_order')->where( array('order_id' => $order_id) )->find();

                    $remark = $other_data['delivery_company'].$other_data['desc'];
                    $this->write_distribution_log( $order_id, 0 , $state ,$remark );
                }
                break;
            case 3://3，已拿货，配送中
                if($other_data['data_type'] == 'imdada'){
                    $res = M('lionfish_comshop_orderdistribution_order')->where( array('order_id' => $order_id) )->save(
                        array('state' => 3,'dm_id'=>$other_data['dm_id'],'dm_name'=>$other_data['dm_name'],'dm_mobile'=>$other_data['dm_mobile'],'third_id'=>$other_data['third_id'])
                    );
                    $remark = $other_data['delivery_company'].'配送员:'.$other_data['dm_name'].', 已到店拿货，配送中';
                    $this->write_distribution_log( $order_id, 0 , $state ,$remark );
                }else if($other_data['data_type'] == 'sf'){
                    $res = M('lionfish_comshop_orderdistribution_order')->where( array('order_id' => $order_id) )->save(
                        array('state' => 3,'dm_name'=>$other_data['operator_name'],'dm_mobile'=>$other_data['operator_phone'])
                    );
                    $operator_action = "";
                    if($other_data['order_status'] == 15){
                        $operator_action = "配送中";
                    }
                    $remark = $other_data['delivery_company'].'配送员:'.$other_data['operator_name'].$operator_action;
                    $this->write_distribution_log( $order_id, 0 , $state ,$remark );
                }else if($other_data['data_type'] == 'make'){
					M('lionfish_comshop_orderdistribution_order')->where( array('order_id' => $order_id) )->save(
                       array('state' => 3,'dm_name'=>$other_data['dm_name'],'dm_mobile'=>$other_data['dm_mobile'])
                    );

                    $remark = $other_data['delivery_company'].'配送员:'.$other_data['dm_name'].', 已到店拿货，配送中';
                    $this->write_distribution_log( $order_id, 0 , $state ,$remark );

                }else if($other_data['data_type'] == 'ele'){//蜂鸟即配
                    M('lionfish_comshop_orderdistribution_order')->where( array('order_id' => $order_id) )->save(
                        array('state' => 3,'dm_name'=>$other_data['operator_name'],'dm_mobile'=>$other_data['operator_phone'])
                    );

                    $remark = $other_data['delivery_company'].$other_data['desc'];
                    $this->write_distribution_log( $order_id, 0 , $state ,$remark );
                }
                break;
            case 4://4、已送达
                M('lionfish_comshop_orderdistribution_order')->where( array('order_id' => $order_id ) )->save( array('state' => 4,'is_statement'=>1) );
                $orderdistribution = M('lionfish_comshop_orderdistribution_order')->where( array('order_id' => $order_id ) )->find();
                $remark = $other_data['delivery_company'].'配送员:'.$orderdistribution['dm_name'].', 配送完成';
                $this->write_distribution_log( $order_id, 0 , $state ,$remark );
                break;
            case 5://5、已取消
                if($other_data['data_type'] == 'imdada'){
                    $orderdistribution = M('lionfish_comshop_orderdistribution_order')->where( array('order_id' => $order_id ) )->find();
                    $cancel_reason = $other_data['cancel_reason'];
                    if($other_data['order_status'] == 5){
                        if($other_data['cancel_from'] == 1){//达达配送员取消
                            $cancel_reason = $cancel_reason.",(".$orderdistribution['dm_name'].",".$orderdistribution['dm_mobile'].")";
                        }else if($other_data['cancel_from'] == 2){//商家主动取消
                            $cancel_reason = $cancel_reason;
                        }else if($other_data['cancel_from'] == 3){//系统或客服取消
                            $cancel_reason = $cancel_reason;
                        }
                    }else if($other_data['order_status'] == 9 || $other_data['order_status'] == 10){
                        if(!empty($orderdistribution['dm_name'])){
                            $cancel_reason = $cancel_reason.",(".$orderdistribution['dm_name'].','.$orderdistribution['dm_mobile'].")";
                        }
                    }else if($other_data['order_status'] == 100){
                        $cancel_reason =  $cancel_reason;
                    }
                    M('lionfish_comshop_orderdistribution_order')->where( array('order_id' => $order_id ) )->save(
                        array('state' => 5,'cancel_reason'=>$cancel_reason,'delivery_type'=>0)
                    );
                    $remark = $other_data['delivery_company'].'已取消,取消原因:'.$cancel_reason;
                    $this->write_distribution_log( $order_id, 0 , $state ,$remark );
                }else if($other_data['data_type'] == 'sf'){
                    if($other_data['order_status'] == 2){//取消订单
                        M('lionfish_comshop_orderdistribution_order')->where( array('order_id' => $order_id ) )->save(
                            array('state' => 5,'cancel_reason'=>$other_data['status_desc'],'delivery_type'=>0)
                        );
                        $remark = $other_data['delivery_company'].'取消订单,取消原因:'.$other_data['status_desc'];
                        $this->write_distribution_log( $order_id, 0 , $state ,$remark );
                    }else if($other_data['order_status'] == 0){//订单异常回调
                        M('lionfish_comshop_orderdistribution_order')->where( array('order_id' => $order_id ) )->save(
                            array('state' => 5,'cancel_reason'=>$other_data['ex_id'].$other_data['ex_content'],'delivery_type'=>0)
                        );
                        $remark = $other_data['delivery_company'].'订单异常,异常详情:'.$other_data['ex_content'];
                        $this->write_distribution_log( $order_id, 0 , $state ,$remark );
                    }

                }else if($other_data['data_type'] == 'make'){

                }else if($other_data['data_type'] == 'ele'){//蜂鸟即配
                    if($other_data['order_status'] == 100){//订单异常回调
                        M('lionfish_comshop_orderdistribution_order')->where( array('order_id' => $order_id ) )->save(
                            array('state' => 5,'cancel_reason'=>$other_data['desc'],'delivery_type'=>0)
                        );
                        $remark = $other_data['delivery_company'].'订单异常,异常详情:'.$other_data['desc'];
                        $this->write_distribution_log( $order_id, 0 , $state ,$remark );
                    }
                }
                break;
        }
    }

    /**
     * 用户取消配送单
     */
    public function member_cancle_order( $order_id )
    {
        M('lionfish_comshop_orderdistribution_order')->where( array('order_id' => $order_id) )->save( array('state' => 5) );
        $remark = '用户取消订单';
        $this->write_distribution_log( $order_id, 0 , 5 ,$remark );
    }

    /**
     * 后台管理员整单退款
     */
    public function admin_cancle_order( $order_id )
    {
        M('lionfish_comshop_orderdistribution_order')->where( array('order_id' => $order_id) )->save( array('state' => 5) );

        $orderdistribution_order = M('lionfish_comshop_orderdistribution_order')->where( array('order_id' => $order_id ) )->find();

        $state_arr = $this->state_arr;
        $remark = '管理员取消订单， 当前配送单状态： '.$state_arr[ $orderdistribution_order['state'] ];

        $this->write_distribution_log( $order_id, 0 , 5 ,$remark );

    }

    /**
     * @auth yj 2020-06-04
     * @desc 配送员 获得订单(后台分配跟前台抢成功，都进入这里)
     * @param $orderdistribution_id
     * @param $order_id
     */
    public function distribution_get_order( $orderdistribution_id , $order_id)
    {
        M()->startTrans();
        
        $distribution_order =  M('lionfish_comshop_orderdistribution_order')->lock(true)->where( array('order_id' => $order_id) )->find();
        
        if( empty($distribution_order) )
        {
            M()->rollback();
            return false;
        }else{
            //未发送第三方配送状态为1 已付款未配送   或者 已发送第三方配送状态为 5 已取消
            if($distribution_order['state'] == 1 && ($distribution_order['delivery_type'] == 0 && (empty($distribution_order['third_distribution_type']) || ($distribution_order['state'] == 5 && !empty($distribution_order['third_distribution_type'])))) || ($distribution_order['delivery_type'] == 1)){
                
            }else{
                $distribution_order = null;
            }
            
            if( empty($distribution_order) )
            {
                M()->rollback();
                return false;
            }else{
                
                M('lionfish_comshop_orderdistribution_order')->where( array('order_id' => $order_id  ) )->save( array('orderdistribution_id' => $orderdistribution_id) );
                
                $shipping_money =  M('lionfish_comshop_orderdistribution_order')->where( array('order_id' => $order_id ) )->find();
                D('Seller/Supply')->update_supply_commission($order_id,$shipping_money["shipping_money"]);
                
                //分配一下订单
                $this->change_distribution_order_state( $order_id, $orderdistribution_id, 2);
                M()->commit();
                
                //删除redis内容，
                //清空发送配送员通知消息队列
                D('Seller/Redisorder')->clear_distribution_delivery_redis($order_id);
                
                return true;
            }
        }
    }

    /**
     * @auth fish 2020-06-04
     * @desc 订单被配送员已拿货，配送中
     * @param $order_id
     */
    public function distribution_deliverying_order( $order_id )
    {
        M()->startTrans();
        $distribution_order =  M('lionfish_comshop_orderdistribution_order')->lock(true)->where( array('order_id' => $order_id , 'state' => 2  ) )->find();

        if( empty($distribution_order) )
        {
            M()->rollback();
            return false;
        }else{

            $this->change_distribution_order_state( $order_id, $distribution_order['orderdistribution_id'], 3);
            M()->commit();
            return true;
        }
    }

    /**
     * @auth fish 2020-06-04
     * @desc   货已送达了
     * @param $order_id
     * @boolean  $is_front 1、前端，0、后端
     * @return bool
     */
    public function distribution_arrived_order( $order_id ,$is_front = true)
    {
        M()->startTrans();
        $distribution_order =  M('lionfish_comshop_orderdistribution_order')->lock(true)->where( array('order_id' => $order_id , 'state' => 3  ) )->find();

        if( empty($distribution_order) )
        {
            M()->rollback();
            return false;
        }else{

            $this->change_distribution_order_state( $order_id, $distribution_order['orderdistribution_id'], 4 , $is_front);

            M()->commit();
            return true;
        }

    }

    /**
     * @author yj 2020-06-04
     * @desc 结算
     * @param $order_id
     */

    public function statement_orderdistribution_order( $order_id )
    {
        M()->startTrans();
        $distribution_order =  M('lionfish_comshop_orderdistribution_order')->lock(true)->where( array('order_id' => $order_id , 'state' => 4 , 'is_statement' => 0 ) )->find();

        if( empty($distribution_order) )
        {
            M()->rollback();
            return false;
        }else{

            //插入配送员佣金
            $orderdistribution_info = $this->get_info_by_distributionid( $distribution_order['orderdistribution_id'] );
            $this->check_commiss_account($distribution_order['orderdistribution_id'], $orderdistribution_info['member_id'] );

            $up_data = array();
            $up_data['is_statement'] = 1;

            M('lionfish_comshop_orderdistribution_order')->where( array('id' => $distribution_order['id'] ) )->save($up_data);

            //M('lionfish_comshop_orderdistribution_commiss')->where( array('orderdistribution_id' => $distribution_order['orderdistribution_id'] ) )->setInc( array('money' => $distribution_order['shipping_money']) );
            M('lionfish_comshop_orderdistribution_commiss')->where( array('orderdistribution_id' => $distribution_order['orderdistribution_id'] ) )->setInc( money,$distribution_order['shipping_money']);

            M()->commit();
            return true;
        }

    }

    /**
     * @author yj 2020-04-06
     * @desc 根据配送员id查找 会员id
     * @param $orderdistribution_id
     */
    public function get_info_by_distributionid( $orderdistribution_id )
    {
        $info =  M('lionfish_comshop_orderdistribution')->where( array('id' => $orderdistribution_id ) )->find();

        if( empty($info) )
        {
            return array();
        }else{
            return $info;
        }

    }

    /**
     * @author yj 2020-06-04
     * @desc 检查是否有佣金账户
     * @param $orderdistribution_id
     * @param int $member_id
     */
    public function check_commiss_account( $orderdistribution_id , $member_id = 0 )
    {
        $info = M('lionfish_comshop_orderdistribution_commiss')->where( array('orderdistribution_id' => $orderdistribution_id ) )->find();

        if( empty($info) )
        {
            $data = array();
            $data['orderdistribution_id'] = $orderdistribution_id;
            $data['member_id'] = $member_id;
            $data['money'] = 0;
            $data['dongmoney'] = 0;
            $data['getmoney'] = 0;
            $data['addtime'] = time();

            M('lionfish_comshop_orderdistribution_commiss')->add( $data );

        }

    }


    /**
     * 写入配送日志
     */
    public function write_distribution_log( $order_id, $orderdistribution_id , $state ,$remark )
    {

        $data = array();
        $data['order_id'] = $order_id;
        $data['orderdistribution_id'] = $orderdistribution_id;
        $data['state'] = $state;
        $data['remark'] = $remark;
        $data['addtime'] = time();

        M('lionfish_comshop_orderdistribution_log')->add($data);
    }

	
	/**
		将发货配送单，放到redis 中
	**/
	public function write_redis_distribution_info( $id )
	{
		$val = M('lionfish_comshop_orderdistribution_order')->where( array( 'id' => $id , 'state' => 1) )->find();
        //获取供应商信息
        $order_info = M('lionfish_comshop_order')->where(array( 'order_id' => $val['order_id']))->find();
        $store_id = $order_info['store_id'];

        $open_redis_server = D('Home/Front')->get_config_by_name('open_redis_server');

        if($open_redis_server == 1) {
            $redis = D('Seller/Redisorder')->get_redis_object_do();
        }
		
		$lon = $val['shop_lon'];
		$lat = $val['shop_lat'];
        if(!empty($store_id)){//独立供应商订单
            $redis->getRedis()->rawCommand('geoadd', '_distributionorder_'.$store_id, $lon, $lat, $val['id'] );
        }else{
            $redis->getRedis()->rawCommand('geoadd', '_distributionorder', $lon, $lat, $val['id'] );
        }

	}
	
	//zRem(key, member)
	
	/**
		被人抢到时，删除键geoadd值
	**/
	public function del_redis_distribution_info( $id )
	{
		$open_redis_server = D('Home/Front')->get_config_by_name('open_redis_server');

        if($open_redis_server == 1) {
            $redis = D('Seller/Redisorder')->get_redis_object_do();
        }

        $val = M('lionfish_comshop_orderdistribution_order')->where( array( 'id' => $id) )->find();
        //获取供应商信息
        $order_info = M('lionfish_comshop_order')->where(array( 'order_id' => $val['order_id']))->find();
        if( !empty($order_info['store_id']) ){
            $redis->zRem('_distributionorder_'.$order_info['store_id'], $id );
        }else{
            $redis->zRem('_distributionorder', $id );
        }
	}

//begin
    /***
    会员配送费佣金申请，余额 审核流程
     **/
    public function send_apply_yuer( $id )
    {
        M()->startTrans();

        $info = M('lionfish_comshop_orderdistribution_tixian_order')->lock(true)->where( array('id' => $id ) )->find();

        if( $info['type'] == 1 && $info['state'] == 0 )
        {
            $del_money = $info['money'] - $info['service_charge_money'];
            if( $del_money >0 )
            {
                D('Seller/User')->sendMemberMoneyChange($info['member_id'], $del_money, 12, '配送佣金提现到余额,提现id:'.$id);
            }
            M('lionfish_comshop_orderdistribution_tixian_order')->where(  array('id' => $id ) )->save( array('state' => 1,'shentime' => time() ) );

            $money = $info['money'];

            //将冻结的钱划一部分到已提现的里面
            M('lionfish_comshop_orderdistribution_commiss')->where( array('member_id' => $info['member_id']) )->setInc('getmoney',$money );
            M('lionfish_comshop_orderdistribution_commiss')->where( array('member_id' => $info['member_id']) )->setInc('dongmoney',-$money );


            M()->commit();
            return array('code' => 0,'msg' => '提现成功');
        }else{
            M()->rollback();
            return array('code' => 1,'msg' => '提现失败');
        }

    }

    /**
    提现到微信零钱
     **/
    public function send_apply_weixin_yuer($id)
    {
        $lib_path = dirname(dirname( dirname(__FILE__) )).'/Lib/';

        require_once $lib_path."/Weixin/lib/WxPay.Api.php";

        $open_weixin_qiye_pay = D('Home/Front')->get_config_by_name('open_weixin_qiye_pay');

        M()->startTrans();

        $info = M('lionfish_comshop_orderdistribution_tixian_order')->lock(true)->where( array('id' => $id ) )->find();

        if( empty($open_weixin_qiye_pay) || $open_weixin_qiye_pay ==0 )
        {
            M()->rollback();
            return array('code' => 1,'msg' => '未开启企业付款');
        }else{
            if( $info['type'] == 2 && $info['state'] == 0 )
            {
                $del_money = $info['money'] - $info['service_charge_money'];
                if( $del_money >0 )
                {
                    $mb_info = M('lionfish_comshop_member')->field('we_openid')->where( array('member_id' => $info['member_id'] ) )->find();

                    $partner_trade_no = build_order_no($info['id']);
                    $desc = date('Y-m-d H:i:s').'申请的提现已到账';

                    $username = $info['bankusername'];
                    $amount = $del_money * 100;

                    $openid = $mb_info['we_openid'];

                    $res =  \WxPayApi::payToUser($openid,$amount,$username,$desc,$partner_trade_no);

                    if(empty($res) || $res['result_code'] =='FAIL')
                    {
                        //show_json(0, $res['err_code_des']);
                        return array('code' => 1,'msg' => $res['err_code_des'] );
                    }else{

                        M('lionfish_comshop_orderdistribution_tixian_order')->where( array('id' => $id ) )->save( array('state' => 1,'shentime' => time() ) );

                        $money = $info['money'];

                        //将冻结的钱划一部分到已提现的里面

                        M('lionfish_comshop_orderdistribution_commiss')->where( array('member_id' => $info['member_id'] ) )->setInc('getmoney',$money);
                        M('lionfish_comshop_orderdistribution_commiss')->where( array('member_id' => $info['member_id'] ) )->setInc('dongmoney',-$money);

                        M()->commit();
                        return array('code' => 0,'msg' => '提现成功');
                    }
                }
            }else{
                M()->commit();
                return array('code' => 1,'msg' => '已提现');
            }

        }

    }

    /***
    提现到支付宝，提现到银行卡
     **/
    public function send_apply_alipay_bank($id)
    {
        M()->startTrans();

        $info = M('lionfish_comshop_orderdistribution_tixian_order')->lock(true)->where( array('id' => $id ) )->find();

        if( ( $info['type'] == 3 || $info['type'] == 4) && $info['state'] == 0 )
        {
            M('lionfish_comshop_orderdistribution_tixian_order')->where( array('id' => $id ) )->save( array('state' => 1,'shentime' => time() ) );

            $money = $info['money'];

            //将冻结的钱划一部分到已提现的里面
            M('lionfish_comshop_orderdistribution_commiss')->where( array('member_id' => $info['member_id']) )->setInc('getmoney',$money);
            M('lionfish_comshop_orderdistribution_commiss')->where( array('member_id' => $info['member_id']) )->setInc('dongmoney',-$money);
            M()->commit();
            return array('code' => 0,'msg' => '提现成功');
        }else{
            M()->rollback();
            return array('code' => 1,'msg' => '已提现');
        }
    }

    /**
     * 获取预计送达时间段
     */
    public function get_expected_delivery($localtown_dispatchtime){
        $result = array();
        //预计送达时间段是否开启，1、开启，0、关闭
        $localtown_expected_delivery_status = D('Home/Front')->get_config_by_name('localtown_expected_delivery_status');
        $localtown_delivery_space_time = D('Home/Front')->get_config_by_name('localtown_delivery_space_time');
        //营业状态
        $localtown_business_hours_status = D('Home/Front')->get_config_by_name('localtown_business_hours_status');
        //营业开始时间
        $localtown_business_hours_begin = D('Home/Front')->get_config_by_name('localtown_business_hours_begin');
        //营业结束时间
        $localtown_business_hours_end = D('Home/Front')->get_config_by_name('localtown_business_hours_end');
        $time = time();
        $localtown_delivery_space_time_list = array();
        $month = "";
        $now_time = $localtown_dispatchtime;
        $count_2 = 0;
        if($localtown_expected_delivery_status == 1 && $localtown_delivery_space_time > 0){
            $month = date('m-d');
            if($time <= strtotime($localtown_dispatchtime)){
                $count = intval((strtotime("24:00")-strtotime($now_time))%86400/60/$localtown_delivery_space_time);
                $k = 0;
                for($i = 0;$i < $count;$i++){
                    $b_time = round($i*$localtown_delivery_space_time);
                    $e_time = round(($i+1)*$localtown_delivery_space_time);
                    $begin_time = date('H:i', strtotime ("+".$b_time." minute", strtotime($now_time)));
                    $end_time = date('H:i', strtotime ("+".$e_time." minute", strtotime($now_time)));
                    if($localtown_business_hours_status == 1){
                        if($this->checkBusinessTime($begin_time,$end_time,$localtown_business_hours_begin,$localtown_business_hours_end)){
                            $localtown_delivery_space_time_list[$month][$k]['time'] = $begin_time.'-'.$end_time;
                            $k++;
                        }
                    }else{
                        $localtown_delivery_space_time_list[$month][$k]['time'] = $begin_time.'-'.$end_time;
                        $k++;
                    }
                }
            }else{
                $localtown_delivery_space_time_list[$month][0]['time'] = "";
            }
            $month_2 = date("m-d",strtotime("+1 day",strtotime(date('Y-m-d'))));
            //$count_2 = intval(24*60/$localtown_delivery_space_time);
            $count_2 = intval((strtotime("24:00")-strtotime($localtown_business_hours_begin))%86400/60/$localtown_delivery_space_time);
            $k = 0;
            for($j = 0;$j < $count_2;$j++){
                $b_time = round($j*$localtown_delivery_space_time);
                $e_time = round(($j+1)*$localtown_delivery_space_time);
                $begin_time = date('H:i', strtotime ("+".$b_time." minute", strtotime($localtown_business_hours_begin)));
                $end_time = date('H:i', strtotime ("+".$e_time." minute", strtotime($localtown_business_hours_begin)));
                if($localtown_business_hours_status == 1) {
                    if ($this->checkBusinessTime($begin_time, $end_time, $localtown_business_hours_begin, $localtown_business_hours_end)) {
                        $localtown_delivery_space_time_list[$month_2][$k]['time'] = $begin_time . '-' . $end_time;
                        $k++;
                    }
                }else{
                    $localtown_delivery_space_time_list[$month_2][$k]['time'] = $begin_time . '-' . $end_time;
                    $k++;
                }
            }
        }
        $result['localtown_expected_delivery_status'] = $localtown_expected_delivery_status;
        $result['localtown_delivery_space_time_list'] = $localtown_delivery_space_time_list;
        $result['localtown_delivery_space_month'] = $month;
        return $result;
    }

    /**
     * 验证时间是否在营业时间之中，是 true，否 false
     * @param $begin_time
     * @param $end_time
     * @param $localtown_business_hours_begin
     * @param $localtown_business_hours_end
     */
    public function checkBusinessTime($begin_time,$end_time,$localtown_business_hours_begin,$localtown_business_hours_end){
        if(strtotime($localtown_business_hours_end) > strtotime($localtown_business_hours_begin)){
            if($end_time != '00:00'){
                if(strtotime($begin_time) >= strtotime($localtown_business_hours_begin) &&  strtotime($end_time) <= strtotime($localtown_business_hours_end)){
                    return true;
                }else{
                    return false;
                }
            }else{
                if(strtotime($begin_time) >= strtotime($localtown_business_hours_begin) &&  (strtotime($end_time)+24*60*60) <= strtotime($localtown_business_hours_end)){
                    return true;
                }else{
                    return false;
                }
            }
        }else{
            if(strtotime($begin_time) >= strtotime($localtown_business_hours_begin) && strtotime($end_time) <= (strtotime($localtown_business_hours_end)+24*60*60)){
                return true;
            }else{
                if((strtotime($begin_time)+24*60*60) >= strtotime($localtown_business_hours_begin) && strtotime($begin_time) <= strtotime($localtown_business_hours_end) &&  strtotime($end_time) <= strtotime($localtown_business_hours_end)){
                    return true;
                }else{
                    return false;
                }
            }
        }
    }


    /**
     * 保存第三方配送日志
     */
    public function save_orderdistribution_thirth_log( $order_id, $third_distribution_type , $state ,$remark )
    {

        $data = array();
        $data['order_id'] = $order_id;
        $data['third_distribution_type'] = $third_distribution_type;
        $data['state'] = $state;
        $data['remark'] = $remark;
        $data['addtime'] = time();

        M('lionfish_comshop_orderdistribution_thirth_log')->add($data);
    }
//end

}
?>