<?php

namespace App\Services;
use App\Models\JdBound;
use App\Models\JdGoods;
use App\Models\JdSynchronous;
use App\Models\Orders;
use App\Models\User;
use BlueCity\Core\Service\Service;
use DB;
use App\Models\Pt;

class JdSynchronousService extends Service
{
    /**
     * 获取详细内容
     * @param string $key 查询键
     * @param string $value 查询值
     * @param array $select 待查询参数
     * @param array $type 查询类型
     * @return
     * @author du 2021年8月14日上午9:03:06
     */
    public static function getInfoBy($key, $value, $select = [] , $type = 'get')
    {
    	$db = new JdSynchronous();
    	if(in_array($key, ['id'])) {
            $type = 'first';
        }
    	if($type == 'first') {
            if (count($select) == 1) {
                $type = 'value';
            }
        }
    	$list = CommonService::getMysqlData($db,[$key=>$value],$select,[],$type);
    	return $list;
    }


    /**
     * 获取列表
     * @param array $input
     * @param array $session
     * @return Ambigous <multitype:, unknown, multitype:unknown NULL >
     * @author du 2021年8月14日下午3:39:38
     */
    public static function getList($input,$session){
    	$where = [];
    	$Db = JdSynchronous::orderBy('id','desc');
    	$state = intval($input['state'])??0;
//    	$where['1'] = 1;
    	//状态
    	if($state>0){
    		$where['is_show'] = intval($state);
    	}

    	//平台单号
    	if(isset($input['order_id'])){
    		$where['order_id_like'] = $input['order_id'];
    	}

    	//用户姓名
    	if(isset($input['fullname'])){
    		$where['fullname_like'] = trim($input['fullname']);
    	}

    	//用户电话
    	if(isset($input['mobile'])){
    		$arr['mobile_like'] = trim($input['mobile']);
            $arr['telephone_like'] = trim($input['mobile']);
            $where['mobile_searchor'] = $arr;
    	}

    	//支付方式
    	if(isset($input['pay_type'])){
    		$where['pay_type_like'] = $input['pay_type'];
    	}

    	$where = CommonService::jointWhere($where);

    	$page_size = $input['page_size']??10;
    	//DB::connection()->enableQueryLog();#开启执行日志
        if($where !='') {
            $paginate = $Db->whereRaw($where)->paginate($page_size);
        }else{
            $paginate = $Db->paginate($page_size);
        }
    	//print_r(DB::getQueryLog());


    	$count_array = JdSynchronous::groupBy('is_show')->selectRaw("count(id) as num,is_show")->get()->toarray();
    	$arr = array_column($count_array, 'num','is_show');
    	if($count_array){

    		$tonji['wtd'] = $arr[1]??0;
    		$tonji['ytd'] = $arr[2]??0;
    		$tonji['ysc'] = $arr[3]??0;
    		$tonji['ywc'] = $arr[4]??0;
    		$tonji['qb'] = array_sum($arr);
    	}else{
    		$tonji['wtd'] = 0;
    		$tonji['ytd'] = 0;
    		$tonji['ysc'] = 0;
    		$tonji['ywc'] = 0;
    		$tonji['qb'] = 0;
    	}
    	$show_Menu = [
    			['show_name'=>"全部",'show_num'=>$tonji['qb'] ,'status'=>'0'],
    			['show_name'=>"未填单",'show_num'=>$tonji['wtd'],'status'=>'1'],
    			['show_name'=>"已填单",'show_num'=>$tonji['ytd'],'status'=>'2'],
    			['show_name'=>"已删除",'show_num'=>$tonji['ysc'],'status'=>'3'],
    			['show_name'=>"已完成",'show_num'=>$tonji['ywc'],'status'=>'4'],
    	];
    	$data['show_Menu'] = $show_Menu;//顶部按钮
    	$all_button = BmmcService::whereButton($input['token'],$input['Pri_id']);
    	$export = BmmcService::getTopButton('excel','',$all_button);
    	$data['button_top'] = $export['button_top']??[];//顶部按钮
    	$data['button_search'] = $export['button_search']??[];//搜索栏按钮
    	$list = CommonService::dataToArray($paginate->items());
    	if($list){
    		$list = JdSynchronousService::getButtonDatas($all_button, $list);
    		$data['list'] = $list;
    		$data['page'] = [
    				'count' => $paginate->total(),
    				'page'=> $paginate->currentPage(),
    				'page_size' => $page_size,
    				'allPage' => $paginate->lastPage()
    		];
    	}else{
    		$data['list'] = [];
    	}
    	return $data;
    }
    /**
     * 获取按钮和数据
     * @param array $all_button
     * @param array $list
     * @return string
     * @author du 2021年8月19日下午3:40:48
     */
    public static function getButtonDatas($all_button,$list){

    	$pt_name = Pt::pluck('pt_name','id');
    	$state = JdSynchronousService::getState();
    	foreach ($list as $k => $v){
            $buttonData = [];
    		$list[$k]['bang'] = 1;//1 已绑定   2未绑定   3 临时绑定
    		$goods_message = Db::table('jdgoods')->where("order_id",$v['order_id'])->get()->toArray();
    		$all_price = 0;
    		foreach( $goods_message as $kg=> $vg ){
    			$all_price += $vg['jd_price']*$vg['item_total'];

    			$pd = JdBound::where("sku_id",$vg['sku_id'])->first();

    			if($pd){
    				if($pd['is_long']==1){
    					$goods_message[$kg]['pd'] = 1;
    				}else{
    					$goods_message[$kg]['pd'] = 3;
    					$list[$k]['bang'] = 3;
    				}
    			}else{
    				$list[$k]['bang'] = 2;
    				$goods_message[$kg]['pd'] = 2;
    				$buttonData[] = 'binding';
    			}
    		}
            $list[$k]['state_name'] = $state[$v['is_show']]??'未确认';
    		$list[$k]['all_price'] = number_format($all_price,2);
    		$list[$k]['jdgoods'] = $goods_message;
    		$list[$k]['pt_name'] = $pt_name[$v['pt_id']];


    		if ($v['is_show'] == 1){
    			$buttonData[] = 'fillBill,delParameter,editAdress';
    		}elseif ($v['is_show'] == 3){
    			$buttonData[] = 'recovery';
    		}

    		$buttonData[] = 'addRemarks';
    		$button = BmmcService::getListButton($buttonData,$all_button);

    		$list[$k]['button_one'] = $button['button_one']??[];
    		$list[$k]['button_two'] = $button['button_two']??[];
    		$list[$k]['button_three'] = $button['button_three']??[];
    	}
    	return $list;
    }

    /**
     * @param $jd_order
     * @param $sys_bh
     * @param $goods_name
     * @param $cost_amou
     * @param $session
     * @return mixed
     * @author du 2021年8月20日上午9:40:48
     */
    public static function addOrderInfo ($jd_order,$sys_bh,$goods_name,$cost_amou,$session,$reaa=''){
        $userArr['shr_name'] = $jd_order['fullname'];
        $userArr['shr_phone'] = $jd_order['mobile'];
        $userArr['shr_sheng'] = $jd_order['province'];
        $userArr['shr_shi'] = $jd_order['city'];
        $userArr['shr_xian'] = $jd_order['county'];
        $userArr['shr_adress'] = $jd_order['full_address'];
        $userArr['sys_num'] = $sys_bh;
        $userArr['create_time'] = date('Y-m-d H:i:s');
        $customer_id = User::insertGetId($userArr);
        //添加订单
        $data['goods_name'] = $goods_name;//商品名称
        $data['p_id'] = $jd_order['pt_id'];//平台id
        $data['order_num'] = $jd_order['order_id'];//平台编号
        $data['order_time'] = $jd_order['order_start_time'];//date('Y-m-d H:i:s');//下单时间
        $data['sys_num'] = $sys_bh;//系统编号
        $data['customer_id'] = $customer_id;//客户信息
        $data['new_customer_id'] = $customer_id;//安装联系人
        $data['order_account'] = $cost_amou;//订单金额
        $data['new_money'] = $cost_amou;//实收
        $data['handled_by'] = $session['admin_name'];//创建人
        $data['admin_id'] = $session['id'];//创建人id
        $data['ser_type'] = 1;//服务类型
        $data['order_status'] = 10;//默认为可派单
        if($reaa){
            $data['kef_id'] = $reaa['kf_id'];
        }
        $newOrderId = Orders::insertGetId($data);
        if($newOrderId){
            return $newOrderId;
        }else{
            return false;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 同步数据状态
     * @retrun /multitype:array
     * @author dou 2021/8/24 9:45
     * |---------------------------------------------------------------------------------
    */
    public static function getState ( ){
        return ['1'=>'未填单','2'=>'已填单','3'=>'已删除','4'=>'已完成'];
    }

    /**|---------------------------------------------------------------------------------
     * @name 添加京东数据表
     * @param string $fullname 客户姓名
     * @param string $telephone 客户电话
     * @param string $mobile 客户手机
     * @param string $province 省
     * @param string $city 市
     * @param string $county 区
     * @param string $full_address 详细地址
     * @param string $admin_acc 经手人
     * @param string $pt_id 平台id
     * @param string $order_id 平台单号
     * @param string $pay_type 支付方式
     * @param string $order_seller_price 订单金额
     * @param string $order_pay 实收金额
     * @param string $freight_price 运费
     * @param string $order_state 订单状态
     * @param string $is_show 是否显示1显示2不显示
     * @param string $invoice_info 发票1开2不开
     * @param string $order_remark 订单备注
     * @param string $order_start_time 下单时间
     * @retrun /multitype:array
     * @author dou 2021/9/29 9:08
     * |---------------------------------------------------------------------------------
    */
    public static function creactJdSynchronous ( $fullname , $telephone , $mobile , $province , $city , $county , $full_address , $admin_acc , $pt_id , $order_id , $pay_type , $order_seller_price , $order_pay , $freight_price , $order_state , $is_show , $invoice_info , $order_remark , $order_start_time ){
        $syn['fullname'] = $fullname;
        $syn['telephone'] = $telephone;
        $syn['mobile'] = $mobile;
        $syn['province'] = $province;
        $syn['city'] = $city;
        $syn['county'] = $county;
        $syn['full_address'] = $full_address;
        $syn['admin_acc'] = $admin_acc;
        $syn['pt_id'] = $pt_id;
        $syn['order_id'] = $order_id;
        $syn['pay_type'] = $pay_type;
        $syn['order_seller_price'] = $order_seller_price;
        $syn['order_pay'] = $order_pay;
        $syn['freight_price'] = $freight_price;
        $syn['order_state'] = $order_state;
        $syn['is_show'] = $is_show;
        $syn['invoice_info'] = $invoice_info;
        $syn['order_remark'] = $order_remark;
        $syn['order_start_time'] = $order_start_time;
        $res = JdSynchronous::insertGetId($syn);
        return $res;
    }

    /**|---------------------------------------------------------------------------------
     * @name 添加京东商品表
     * @param string ju_ordernum 订单单号
     * @retrun /multitype:array
     * @author dou 2021/9/29 16:27
     * |---------------------------------------------------------------------------------
    */
    public static function creactJdGood ( $pt_id , $order_id , $sku_id , $sku_name , $item_total , $jd_price , $jd_cost , $verCodeList = '' , $storeName ){
        $good['pt_id'] = $pt_id;
        $good['order_id'] = $order_id;
        $good['sku_id'] = $sku_id;
        $good['sku_name'] = $sku_name;
        $good['item_total'] = $item_total;
        $good['jd_price'] = $jd_price;
        $good['jd_cost'] = $jd_cost;
        $good['verCodeList'] = json_encode($verCodeList);
        $good['storeName'] = $storeName;
        $res = JdGoods::insertGetId($good);
        return $res;
    }
}
