<?php

namespace App\Http\Models\Api;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;
use App\Http\Models\Api\Common;
class PushSd extends Model
{
    /**
     * 门店收货推送数据到速电
     * @param  $user_info    array      用户数据
     * @param  $rebb_id      int        补货账单id
     * @return boolean
     */
    public function pushs(
        $user_info,
        $rebb_id
    ){
        //门店配送账单号
        $debb_data = DB::table('replenish_bill_bs')
            ->where('rebb_id',$rebb_id)
            ->first(['rebb_shipping_number','rebb_number','rebb_delivery_amount','rebb_total_money']);

        $rerb_data = DB::table('replenish_record_bs')
                ->where('rerb_rebb_id',$rebb_id)
                ->where('rerb_state','!=','3')
                ->get(['rerb_id','rerb_deliver_type','rerb_total_shipping_fee', 'rerb_wd_shop_id','rerb_number']);
        
        $sd_rerb_id = [];
        $wd_rerb_id = [];
        $sd_rerb_number = [];
        $wd_rerb_number = [];
        $logistics = 0;//物流费
        $shipping_fee = 0;//运费
        foreach ($rerb_data as $key => $value) {
            // 1速电发货2 配送商发货
            if($value->rerb_deliver_type == 1){
                $sd_rerb_id[] = $value->rerb_id;
                $logistics += $value->rerb_total_shipping_fee;
                $sd_rerb_number[] = $value->rerb_number;
            }else{
                $wd_rerb_id[] = $value->rerb_id;
                $wd_shop_id = $value->rerb_wd_shop_id;
                $wd_rerb_number[] = $value->rerb_number;
                $shipping_fee += $value->rerb_total_shipping_fee;
            }
        }
        $chan_data = DB::connection('mysql_scm')->table('channel')
            ->whereIn('chan_shop_id',[$user_info->adm_shop_id,$wd_shop_id])
            ->pluck('chan_bound_id','chan_shop_id');
        //速电派发数据
        $sd_rrgb_data = DB::table('replenish_record_goods_bs')
            ->whereIn('rrgb_rerb_id',$sd_rerb_id)
            ->whereIn('rrgb_state',[1,2])
            ->get(['rrgb_goo_name','rrgb_sd_goo_id','rrgb_goo_encode','rrgb_actual_send_quantity','rrgb_spoiled_quantity']);
        $sd_goods_list = [];
        $sd_damaged_list = [];
        $sd_goo_id = [];
        foreach ($sd_rrgb_data as $key => $value) {
            $sd_goods_list[$key]['pg_id'] = $value->rrgb_sd_goo_id;//速电商品id
            $sd_goods_list[$key]['good_name'] = $value->rrgb_goo_name;//商品名称
            $sd_goods_list[$key]['product_version'] = $value->rrgb_goo_encode;//商品编号
            $sd_goods_list[$key]['good_num'] = $value->rrgb_actual_send_quantity;//补货数量
            $sd_goo_id[] = $value->rrgb_sd_goo_id;
        }
        $sd_goods_lists = [];
        foreach ($sd_goods_list as $key => $value) {
            if(isset($sd_goods_lists[$value['pg_id']])){
                $sd_goods_lists[$value['pg_id']]['good_num'] += $value['good_num'];
                $sd_goods_lists[$value['pg_id']]['pg_id'] = $value['pg_id'];
                $sd_goods_lists[$value['pg_id']]['good_name'] = $value['good_name'];
                $sd_goods_lists[$value['pg_id']]['product_version'] = $value['product_version'];
            }else{
                $sd_goods_lists[$value['pg_id']] = $value;
            }
        }
        $sd_goods_data = [];
        foreach ($sd_goods_lists as $key => $value) {
            $sd_goods_data[] = $value;
        }

        $sd_damaged_list = DB::table('spoiled_goods')
            ->where('spgo_type',2)
            ->where('spgo_state',2)
            ->where('spgo_shop_id',$user_info->adm_shop_id)
            ->whereIn('spgo_goo_id',$sd_goo_id)
            ->get(['spgo_sd_goo_id as pg_id','spgo_goo_name as good_name','spgo_goo_encode as product_version','spgo_spoiled_quantity as good_num']);
        $sd_damaged_list = json_decode($sd_damaged_list,true);
        if(!empty($sd_damaged_list)){
            $spgo_res = DB::table('spoiled_goods')
            ->where('spgo_type',2)
            ->where('spgo_state',2)
            ->where('spgo_shop_id',$user_info->adm_shop_id)
            ->whereIn('spgo_sd_goo_id',$sd_goo_id)
            ->update(['spgo_state'=>3,'spgo_update_time'=>date('Y-m-d H:i:s')]);
        }
        $sd_list['ser_id'] = $chan_data[$user_info->adm_shop_id];//门店id
        $sd_list['wd_id'] = 0;//wd门店id
        $sd_list['all_price'] = $logistics;//合计配送费
        $sd_list['good_list'] = $sd_goods_data;//门店配送正常商品数据
        $sd_list['damaged_list'] = $sd_damaged_list;//门店配送残损商品数据
        $sd_list['distri_num'] = trim(implode(',',$sd_rerb_number),',');//速电配送单号
        //供应商派发数据
        $wd_rrgb_data = DB::table('replenish_record_goods_bs')
            ->whereIn('rrgb_rerb_id',$wd_rerb_id)
            ->whereIn('rrgb_state',[1,2])
            ->get(['rrgb_goo_name','rrgb_sd_goo_id','rrgb_goo_encode','rrgb_actual_send_quantity','rrgb_spoiled_quantity','rrgb_shipping_fee']);
        $wd_goods_list = [];
        $wd_damaged_list = [];
        foreach ($wd_rrgb_data as $key => $value) {
            $wd_goods_list[$key]['pg_id'] = $value->rrgb_sd_goo_id;//速电商品id
            $wd_goods_list[$key]['good_name'] = $value->rrgb_goo_name;//商品名称
            $wd_goods_list[$key]['product_version'] = $value->rrgb_goo_encode;//商品编号
            $wd_goods_list[$key]['good_num'] = $value->rrgb_actual_send_quantity;//补货数量
            $wd_goods_list[$key]['price'] = $value->rrgb_shipping_fee;//商品配送费
            $wd_goo_id[] = $value->rrgb_sd_goo_id;
        }
        $wd_goods_lists = [];
        foreach ($wd_goods_list as $key => $value) {
            if(isset($wd_goods_lists[$value['pg_id']])){
                $wd_goods_lists[$value['pg_id']]['good_num'] += $value['good_num'];
                $wd_goods_lists[$value['pg_id']]['price'] += $value['price'];
                $wd_goods_lists[$value['pg_id']]['pg_id'] = $value['pg_id'];
                $wd_goods_lists[$value['pg_id']]['good_name'] = $value['good_name'];
                $wd_goods_lists[$value['pg_id']]['product_version'] = $value['product_version'];
            }else{
                $wd_goods_lists[$value['pg_id']] = $value;
            }
        }
        $wd_goods_data = [];
        foreach ($wd_goods_lists as $key => $value) {
            $wd_goods_data[] = $value;
        }
        $wd_damaged_list = DB::table('spoiled_goods')
            ->where('spgo_type',2)
            ->where('spgo_state',2)
            ->where('spgo_shop_id',$user_info->adm_shop_id)
            ->whereIn('spgo_sd_goo_id',$wd_goo_id)
            ->get(['spgo_sd_goo_id as pg_id','spgo_goo_name as good_name','spgo_goo_encode as product_version','spgo_spoiled_quantity as good_num','spgo_shipping_fee as price']);
        if(!empty($wd_damaged_list)){
            $wd_spgo_res = DB::table('spoiled_goods')
            ->where('spgo_type',2)
            ->where('spgo_state',2)
            ->where('spgo_shop_id',$user_info->adm_shop_id)
            ->whereIn('spgo_sd_goo_id',$wd_goo_id)
            ->update(['spgo_state'=>3,'spgo_update_time'=>date('Y-m-d H:i:s')]);
        }
        $wd_damaged_list = json_decode($wd_damaged_list,true);
        $store_list['ser_id'] = $chan_data[$user_info->adm_shop_id];//门店id
        $store_list['wd_id'] = $chan_data[$wd_shop_id];//wd门店id
        $store_list['all_price'] = $shipping_fee;//合计配送费
        $store_list['good_list'] = $wd_goods_data;//门店配送正常商品数据
        $store_list['damaged_list'] = $wd_damaged_list;//门店配送残损商品数据
        $store_list['distri_num'] = trim(implode(',',$wd_rerb_number),',');//wd配送单号;

        //汇总数据
        $param['wat_num'] = $debb_data->rebb_shipping_number;//结算单号（补货单号）
        $param['store_list'] = $store_list;//供应商
        $param['sd_list'] = $sd_list;//速电

        //推送残损和正产补货数据的链接
        $url = config('apisystem.sd_server_name').'/index.php/get_supply_chain';
        $msg = $this->doPost($url,$param);
        $msg = json_decode($msg);
        if($msg->code != 200){
            return false;
        }
    }

    protected function doPost($url, array $param)
    {
        // 当前时间
        $param['time'] = date('Y-m-d H:i:s');//时间
        //生成token
        $param['token'] = md5(md5($param['time'].'c883e5e641818d993a2d8d966ca450bf'));//token
        // 模拟提交数据函数
        Common::write_log($param);
        $post_data = $this->ToUrlencode($param);
        $post_data=urldecode(json_encode($post_data));
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);//捕抓异常
        }
        curl_close($curl); // 关闭CURL会话
        return $tmpInfo; // 返回数据，json格式
    }

    public function ToUrlencode($arr)
    {
        $temp = array();
        if (is_array($arr)){
            foreach ($arr AS $key => $row){
                $temp[$key] = $row;
                if (is_array($temp[$key])){
                    $temp[$key] = $this->ToUrlencode($temp[$key]);
                }else{
                    $temp[$key] = urlencode($row);
                }
            }
        }else{
            $temp = $arr;
        }
        return $temp;
    }
}
