<?php
namespace App\Http\Controllers\DataSyn;
use App\Http\Controllers\BaseController;
use App\Models\JdBound;
use App\Models\OrderMsg;
use App\Models\PjGoods;
use App\Services\CommonService;
use App\Services\JdBoundService;
use App\Services\OrderaddService;
use App\Services\OrderService;
use BlueCity\Core\Inc\ErrorInc;
use Illuminate\Http\Request;
use App\Models\JdSynchronous;
use DB;
use App\Services\JdSynchronousService;
use App\Services\GoodsService;

class JdSynchronousController extends BaseController
{
	/**
	 * @name  列表页
     * @param state    0:全部; 1:未填单 2:已填单 3:已删除 4:已完成
     * @param order_id 平台单号
     * @param fullname 用户姓名
     * @param mobile   用户电话
     * @param pay_type 支付方式
	 * @param  $request
	 * @author du 2021年8月19日上午9:28:06
	 */
	public function index(Request $request){
		$input = $request->all();
        $session = $request->get('session_token');
    	$list = JdSynchronousService::getList($input,$session);
    	if($list['list']){
	    	return $this->success('获取成功', $list); exit;
    	}else{
	    	return $this->error('暂无数据', ErrorInc::DATA_EMPTY,$list);exit;
    	}
	}


	/**
	 *  @name  恢复
     * @param id 数据id
	 * @param  $request
	 * @author du 2021年8月19日上午9:46:57
	 */
	public function recovery(Request $request){
		if (!$request->filled('id')){
			return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);exit;
		}
		$id = intval($request->input('id'));
		$res = JdSynchronous::where(['id'=>$id,'is_show'=>3])->update(['is_show'=>1]);
		if($res){
			 $order_id = JdSynchronous::where('id',$id)->value('order_id');
			 $this->insertingLog('恢复，',$order_id,'订单：'.$order_id,'京东自营同步',$request->ip(), $request->get('session_token')['admin_acc']);//日志
			return $this->success('恢复成功'); exit;
    	}else{
	    	return $this->error('恢复失败', ErrorInc::MYSQL_FAILED);exit;
    	}
	}


	/**
	 * @name  删除
     * @param id 数据id
	 * @param  $request
	 * @author du 2021年8月19日上午10:03:59
	 */
	public function delParameter(Request $request){
		if (!$request->filled('id')){
			return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);exit;
		}
		$id = intval($request->input('id'));
		$res = JdSynchronous::where(['id'=>$id,'is_show'=>1])->update(['is_show'=>3]);
		if($res){
            $order_id = JdSynchronous::where('id',$id)->value('order_id');
            $this->insertingLog("删除，",$order_id,"删除，订单：".$order_id,"京东自营同步",$request->ip(), $request->get('session_token')['admin_acc']);
			return $this->success('删除成功'); exit;
    	}else{
	    	return $this->error('删除失败', ErrorInc::MYSQL_FAILED);exit;
    	}
	}

	/**
	 * @name  绑定
     * @param id 数据id
     * @param is_long  1:绑定 2:临时绑定
     * @param goods_id 商品id
	 * @param  $request
	 * @author du 2021年8月19日上午10:29:44
	 */
	public function binding(Request $request){
		if (!$request->filled('id')||!$request->filled('goods_id')){
			return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);exit;
		}
		$id = intval($request->input('id'));

		$is_long = (int)$request->input('is_long',1);

		$goods_id = (int)$request->input('goods_id');

		$jdgoods = Db::table('jdgoods')->where('id',$id)->select('pt_id','sku_id','sku_name')->first();
		if($jdgoods){
			$goods_info = GoodsService::getGoodsByKey("pg_id", $goods_id,['brand_name','pg_series','version']);
            if ($goods_info['pg_series'] == ''){
                $goods_name = $goods_info['brand_name'].'-'.$goods_info['version'];
            }else{
                $goods_name = $goods_info['brand_name'].'-'.$goods_info['pg_series'].'-'.$goods_info['version'];
            }
			if($goods_info){
				$res = JdBoundService::createjdBound($jdgoods['sku_id'], $jdgoods['sku_name'], $jdgoods['pt_id'], $goods_id, $is_long, '', $goods_name,$request->get("session_token")['company_id'],$request->get('session_token')['admin_acc']);
				if($res){
					if($is_long==1){
						$bding = "永久绑定商品，";
					}else{
						$bding = "临时绑定商品，";
					}
                    $this->insertingLog($bding,$jdgoods['sku_id'],'商品绑定','京东自营同步',$request->ip(), $request->get('session_token')['admin_acc']);//日志
                    return $this->success('绑定成功'); exit;
				}else{
					return $this->error('绑定失败', ErrorInc::DATA_EMPTY);exit;
				}
			}else{
				return $this->error('未找到该系统商品', ErrorInc::DATA_EMPTY);exit;
			}
		}else{
			return $this->error('暂无数据', ErrorInc::DATA_EMPTY);exit;
		}
	}



    /**|---------------------------------------------------------------------------------
     * @name 填单
     * @param id 数据id
     * @return \Illuminate\Http\JsonResponse
     * @author  <2019>
     * |---------------------------------------------------------------------------------
     * @noinspection ProblematicWhitespace
     */
	public function fillBill(Request $request){
		if (!$request->filled('id')){
			return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);exit;
		}
		$id = intval($request->input('id'));
        $session = $request->get('session_token');
		try{
            DB::beginTransaction();
			$sys_bh = 'L'.date("Ymdhis").str_pad(rand(0,999),3,'0',STR_PAD_LEFT);//生成系统单号算法
			$jd_order = JdSynchronous::where(["id"=>$id,"is_show"=>1])->select('province','city','county','order_id','mobile','fullname','full_address','pt_id','order_start_time')->first();

			if(!$jd_order){
				return $this->error('未找到该数据', ErrorInc::DATA_EMPTY);exit;
			}
			$res = OrderService::getOrderBy("order_num", $jd_order['order_id'],['id']);

			if($jd_order['province']=="" || $jd_order['city']=="" || $jd_order['county']==""){
				return $this->error('该订单省市县不完整，请补充完整后填单', ErrorInc::DATA_EMPTY);exit;
			}
			//判定同步表和订单表是否存在该订单
			if($jd_order && !$res){
				$jd_goods = Db::table('jdgoods')->where("order_id",$jd_order['order_id'])->get()->toArray();
                $goods_name = "";
                $cost_amou = 0;
                $appoint_code = substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 6);
                foreach( $jd_goods as $k => $v){
                    $good_id = JdBound::where("sku_id",$v['sku_id'])->select('goods_id','is_long','id')->first();
                    $goodsres = PjGoods::where("pg_id",$good_id['goods_id'])->first();
                    if(!$goodsres){
                        throw new \Exception("请先将商品绑定,后在填单");
                    }
                    if($goodsres['pg_series']!=""){
                        $goods_name .= $goodsres['brand_name'].'-'.$goodsres['pg_series'].'-'.$goodsres['version'].',';
                        $gname = $goodsres['brand_name'].'-'.$goodsres['pg_series'].'-'.$goodsres['version'];
                    }else{
                        $goods_name .= $goodsres['brand_name'].'-'.$goodsres['version'].',';
                        $gname = $goodsres['brand_name'].'-'.$goodsres['version'];
                    }
                    // 订单总金额
                    $cost_amou += $v['jd_price'] * $v['item_total'];
                    $num = 0;
                    //添加商品信息
                    $orderMsgData['appoint_code'] = $appoint_code;
                    $orderMsgData['goods_id'] = $good_id['goods_id'];
                    $orderMsgData['goods_name'] = $gname;
                    $orderMsgData['sys_num'] = $sys_bh;
                    $orderMsgData['goods_brand'] = $goodsres['brand_name'];
                    $orderMsgData['goods_number'] = "";
                    $orderMsgData['goods_pic_path'] = $goodsres['goods_pic_path'];
                    $orderMsgData['creator'] = $session['admin_acc'];
                    if($v['item_total']<4) {
                        while ($num < $v['item_total']) {
                            $orderMsgData['goods_num'] = 1;
                            $orderMsgData['goods_price'] = $v['jd_price'];//实收/商品单价
                            $orderMsgData['goods_paid'] = $v['jd_price'];//应收
                            $newOrderIds = OrderMsg::insert($orderMsgData);
                            $num = $num + 1;
                        }
                    }else{
                        $orderMsgData['goods_num'] = $v['item_total'];
                        $orderMsgData['goods_price'] = $cost_amou;//实收/商品单价
                        $orderMsgData['goods_paid'] = $cost_amou;//应收
                        $newOrderIds = OrderMsg::insert($orderMsgData);
                    }
                }
                $time = date("Y-m-d");
                $time1 = date("Y-m-d",strtotime("+1 day"));
                $reaa = Db::table('kefu')->where('kf_day','>',$time)->where('kf_day','<',$time1)->where(['disable'=>1,'kef_pd'=>2])->orderBy('fp_time','asc')->first();
                $newOrderId = JdSynchronousService::addOrderInfo($jd_order, $sys_bh, $goods_name, $cost_amou, $session,$reaa);
				if (!$newOrderId){
                    DB::rollback();
					throw new \Exception("填单失败");
				}else{
					if($jd_order["order_remark"]!=""){
					    $content = $jd_order["order_remark"];
					}else{
						$content = "接单后10分钟内务必联系客户核实车型跟安装时间！不断电安装、如果无法完成 请立刻反馈我们处理~！";//操作内容
					}
                    CommonService::accMe($sys_bh, '客户留言', $content, $jd_order['order_id'], 2,$session['admin_groupnew'], $session['admin_name'], $session['id']);
					JdSynchronous::where("id",$id)->update(['is_show'=>2]);
					$poss['number'] = $reaa['number']+1;
					$poss['fp_time'] = date("Y-m-d H:i:s");
					Db::table('kefu')->where("id",$reaa['id'])->update($poss);
					DB::commit();
					return $this->success('填单成功');
				}
			}else{
				throw new \Exception("该订单号已存在");exit;
			}
		}catch(\Exception $e){
			Db::rollBack();
			return $this->error($e->getMessage(), ErrorInc::MYSQL_FAILED);
		}
	}


 /**|---------------------------------------------------------------------------------
  * @name  编辑地址
  * @param id        数据id
  * @param province  省
  * @param city      市
  * @param county    县
  * @param address   详细地址
  * @retrun \Illuminate\Http\JsonResponse /multitype:array
  * @author du 2021/8/20 10:15
  * |---------------------------------------------------------------------------------
 */
	public function editAdress(Request $request){
        if (!$request->filled('id')){
            return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);exit;
        }
        $id = intval($request->input('id'));
		if($request->filled('province') && $request->filled('city') && $request->filled('county') && $id >0){
			$poss['province'] = $request->input('province');
			$poss['city'] = $request->input('city');
			$poss['county'] = $request->input('county');
			$poss['full_address'] = $request->input('address');
			$res = JdSynchronous::where(['id'=>$id,'is_show'=>1])->update($poss);
			if($res){
			    $this->insertingLog("编辑地址，","","数据id：".$id,"京东自营同步",$request->ip(), $request->get('session_token')['admin_acc']);
                return $this->success('操作成功'); exit;
            }else{
                return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
            }
		}else{
			return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);exit;
		}
	}

	/**|---------------------------------------------------------------------------------
	 * @name  更新京东表备注
     * @param remarks  备注内容
	 * @retrun \Illuminate\Http\JsonResponse /multitype:array
	 * @author du 2021/8/20 10:21
	 * |---------------------------------------------------------------------------------
	*/
	public function addRemarks(Request $request){
        if (!$request->filled('id')){
            return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);exit;
        }
        $id = intval($request->input('id'));
		if($request->filled('remarks') && $id>0){
			$res = JdSynchronous::where(['id'=>$id])->update(['order_remark'=>$request->input('remarks')]);
			if($res){
                return $this->success('操作成功'); exit;
            }else{
                return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
            }
		}else{
            return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);exit;
		}
	}



}
