<?php
/*
 本代码由 焕岱科技 创建
 技术支持 WX：15285007200
 严禁反编译、逆向等任何形式的侵权行为，违者将追究法律责任
*/

namespace app\admin\controller\bbfxshop\scoreshop;

use app\admin\controller\bbfxshop\Base;
use think\Db;
use app\common\model\bbfxshop\User;

class Order extends Base
{

    public $model = null;
    public function _initialize(){
        parent::_initialize();
        $this->model = new \app\common\model\bbfxshop\Scoreshop;
    }
    

    public function extractData(){
        $params = $this->param();
        
        $order_id = intval($params['order_id']);
        $order = Db::name("bbfx_scoreshop_order")->where(['id'=>$order_id])->find();
        if(empty($order)){
            __error("订单不存在");
        }
        return ['order_id'=>$order_id,'order'=>$order,'params'=>$params];
    }
    
    public function print(){
        $extractData = $this->extractData();
        extract($extractData);
        
        $result = \app\common\model\bbfxshop\Printer::orderPrint($order['id'],1);
        
        __result($result);
    }

    public function queryExpressDelivery(){
        $extractData = $this->extractData();
        extract($extractData);
        $express_no = $this->param("express_no/s");
        
        if($order['order_type'] == 2 && $order['delivery_method'] != 1){
            __error("不是快递订单");
        }
        if($order['status'] <= 1){
            __error("订单未发货");
        }
        $express = iunserializer($order['express']);
        $new_express_no = $express_no;
        if(!strstr($new_express_no, ':')){
            foreach ($express as $key => $val){
                if($val['express_no'] == $express_no && $val['express_name'] == '中通快递'){
                    $new_express_no = $express_no.":".mb_substr($order['delivery_mobile'], -4);
                }
            }
            unset($val);
        }
        
        $result = \app\common\model\bbfxshop\Delivery::queryExpressDelivery($new_express_no);
        if($result['code'] == 1){
            $res = $result['data'];
            foreach ($express as $key => &$val){
                if($val['express_no'] == $express_no){
                    $val['express_data'] = $res;
                }
            }
            unset($val);
            
            Db::name("bbfx_scoreshop_order")->where(['id'=>$order['id']])->update(['express'=>iserializer($express)]);
        }
        
        __result($result);
    }
    
    public function refund(){
        $extractData = $this->extractData();
        extract($extractData);
        if($order['status'] == 0){
            __error("订单未支付");
        }
        
        if($order['refund_status'] == 1){
            __error("订单已退款");
        }
        $type = intval($params['type']);
        $refund_status = intval($params['status']);
         
        if($type == 1){
            $refund = Db::name("bbfx_scoreshop_order_refund")->where(['order_id'=>$order_id,'uniacid'=>UNIACID])->find();
            if(empty($refund)){
                $order_no = date('YmdHis').random(8,true);
                $data = array(
                    "uniacid"=>UNIACID,
                    "user_id"=>$order['user_id'],
                    "order_no"=>$order_no,
                    "money"=>$order['price'],
                    "order_id"=>$order_id,
                    "score"=>$order['score'],
                    "content"=>"平台退款",
                    "createtime"=>time()
                );
                
                $refund_id = Db::name("bbfx_scoreshop_order_refund")->insertGetId($data);
        
                if(empty($refund_id)){
                    __error("退款失败");
                }
                Db::name("bbfx_scoreshop_order")->where(['id'=>$order_id])->update(['refund_status'=>0]);
            }
            else{
                if($refund['status'] == 1){
                    Db::name("bbfx_scoreshop_order")->where(['id'=>$order_id])->update(['refund_status'=>1]);
                    __error("退款失败");
                }
            }
            $refund_status = 1;
        }
        
        $result = $this->model->refund($order_id,$refund_status,$type);
        if(!empty($result) && $result['code'] === 1){
            \app\admin\model\AdminLog::record("","",["id"=>$order_id,"refund_status"=>$refund_status],"bbfx_scoreshop_order");
            __success("退款成功");
        }
        else{
            __error($result['message']);
        }
    }
    
    public function updateDeliver(){
        $extractData = $this->extractData();
        extract($extractData);
        if($order['status'] == 0){
            __error("订单未支付");
        }
        if($order['refund_status'] != -1){
            __error("订单已申请售后");
        }
        if($order['status'] > 1){
            __error("订单已发货");
        }
        
        $delivery_username = $params['delivery_username'];
        $delivery_mobile = $params['delivery_mobile'];
        $delivery_address = $params['delivery_address'];
        $delivery_dz = $params['delivery_dz'];
        
        $data = array(
            "delivery_username"=>$delivery_username,
            "delivery_mobile"=>$delivery_mobile,
            "delivery_province"=>$delivery_dz[0],
            "delivery_city"=>$delivery_dz[1],
            "delivery_area"=>$delivery_dz[2],
            "delivery_address"=>$delivery_address,
        );
        
        if(empty($data['delivery_username'])){
            __error("请填写收货人");
        }
        if(empty($data['delivery_mobile'])){
            __error("请填写收货人电话");
        }
        if(empty($data['delivery_province']) || empty($data['delivery_city']) || empty($data['delivery_area'])){
            __error("请选择地区");
        }
        if(empty($data['delivery_address'])){
            __error("请填写详细地址");
        }
        
        $res = Db::name("bbfx_scoreshop_order")->where(['id'=>$order['id']])->update($data);
        
        if($res){
            $data['id'] = $order['id'];
            \app\admin\model\AdminLog::record("","",$data,"bbfx_scoreshop_order");
            __success("修改成功");
        }
        else{
            __error("修改失败");
        }
    }
    
    public function updateRemarks(){
        $extractData = $this->extractData();
        extract($extractData);
        
        $content = $params['content'];
        
        $res = Db::name("bbfx_scoreshop_order")->where(['id'=>$order['id']])->update(['remarks'=>$content]);
        
        if($res){
            \app\admin\model\AdminLog::record("","",['id'=>$order['id'],'remarks'=>$content],"bbfx_scoreshop_order");
            __success("修改成功");
        }
        else{
            __error("修改失败");
        }
    }
    
    public function takeDelivery(){
        $extractData = $this->extractData();
        extract($extractData);
        $result = $this->model->takeDelivery($order['id']);
        if(!empty($result) && $result['code'] == 1){
            \app\admin\model\AdminLog::record("","",['id'=>$order['id'],'status'=>3],"bbfx_scoreshop_order");
            __success("确认收货成功");
        }
        else{
            __error($result['message']);
        }
    }
    
    public function send(){
        $extractData = $this->extractData();
        extract($extractData);
        if($order['status'] == 0){
            __error("订单未支付");
        }
        if($order['refund_status'] != -1){
            __error("订单已申请售后");
        }
        
        
        if($order['order_type'] == 2){
            $expressInfo = $params['expressInfo'];
            $deliver_type = intval($params['deliver_type']);
            if(empty($expressInfo)){
                __error("请填写快递信息");
            }
            
            foreach($expressInfo as $key => $val){
                if(empty($val['express_id'])){
                    __error("请选择快递公司");
                }
                if(empty($val['express_no'])){
                    __error("请填写快递单号");
                }
                if($deliver_type != 1 && empty($val['goods_id'])){
                    __error("请选择商品");
                }
            }
            if($order['status'] == 1){
                $res = Db::name("bbfx_scoreshop_order")->where(['id'=>$order['id'],'status'=>1])->update(['status'=>2]);
            }
            else{
                $res = true;
            }
            
            if($res){
                $udata = [];
                if($order['status'] == 1){
                    $udata = ['deliverytime'=>time()];
                }
                if($order['order_type'] == 2){
                    $udata['express'] = iserializer($expressInfo);
                    $udata['deliver_type'] = $deliver_type;
                }
                
                Db::name("bbfx_scoreshop_order")->where(['id'=>$order['id']])->update($udata);
                
                \app\common\model\bbfxshop\Message::sendShippingnoticeMsg($order['id'],1);
                
                $udata['status'] = 2;
                $udata['id'] = $order['id'];
                
                \app\admin\model\AdminLog::record("","",$udata,'bbfx_scoreshop_order');
                
                __success("发货成功");
            }
            else{
                __error("发货失败");
            }
        }
        else if($order['order_type'] == 1 || $order['order_type'] == 4){
            if($order['status'] != 1){
                __error("订单状态错误");
            }
            $res = $this->model->takeDelivery($order['id']);
            if(!empty($res) && $res['code'] == 1){
                Db::name("bbfx_scoreshop_order")->where(['id'=>$order['id']])->update(['deliverytime'=>time()]);
                
                \app\admin\model\AdminLog::record("","",['id'=>$order['id'],'status'=>3],'bbfx_scoreshop_order');
                
                __success("发货成功");
            }
            else{
                 __error($res['message']);
            }
        }
        else{
            __error("商品类型错误");
        }
    }
    
    public function close(){
        $id = $this->param('order_id/d');
        
        $result = $this->model->closeOrder($id);
        if($result['code'] != 1){
            \app\admin\model\AdminLog::record("","",['id'=>$id],'bbfx_scoreshop_order');
            __error($result['message']);
        }
        
        __success($result['message']);
    }
    
    public function detail(){
        global $_W;
        $extractData = $this->extractData();
        extract($extractData);
        
        $order_goods = Db::name("bbfx_scoreshop_order_goods")->where(['order_id'=>$order['id'],'uniacid'=>UNIACID])->select();
        $goods_list = [];
        $goods_all = [];
        $serial_numbers = [];
        foreach ($order_goods as $key => &$val){
            $goods_info = iunserializer($val['goods_info']);
            $goods_info['thumb'] = cdnurl($goods_info['thumb']);
            
            if($order['status'] == 3 && $order['order_type'] == 1){
                $serial_number = Db::name("bbfx_scoreshop_serial_number")->where(['pid'=>$val['id'],'uniacid'=>UNIACID])->field(['id','val','pid'])->select();
                foreach ($serial_number as $k => &$v){
                    $v['goods'] = $goods_info;
                }
                unset($v);
                $serial_numbers = array_merge($serial_numbers,$serial_number);
            }
            
            $val['goods_info'] = $goods_info;
            $goods_info['total'] = $val['total'];
            $goods_list[$val['goods_id']] = $goods_info;
            $goods_all[] = $goods_info;
        }
        unset($val);
        $paytypes = ['1'=>'微信支付','2'=>'余额支付','积分兑换'];
        $order['paytypeText'] = $paytypes[$order['paytype']];
        
        $order['user'] = User::getUser($order['user_id'],false);
        
	    $order['typeText'] = $this->model->getOrderType($order['order_type']);
        $order['statusText'] = $this->model->getOrderStatus($order,1);
        $order['refund_statusText'] = $this->model->getOrderRefundStatus($order['refund_status']);
        $order['deliverytime'] = date("Y-m-d H:i:s",$order['deliverytime']);
        $order['serial_numbers'] = $serial_numbers;
        if($order['refund_status'] != -1){
            
            $refund = Db::name("bbfx_scoreshop_order_refund")->where("order_id",$order['id'])->find();
            if(!empty($refund)){
                $refund['images'] = iunserializer($refund['images']);
                foreach ($refund['images'] as $key => &$val){
                    $val = cdnurl($val);
                }
                unset($val);
                $refund['createtime'] = date("Y-m-d H:i:s",$refund['createtime']);
                $order['refund'] = $refund;
            }
        }
        
        
        if(($order['order_type'] == 2 || $order['order_type'] == 4) && $order['is_hexiao'] == 1){
            $hexiao_record = Db::name("bbfx_scoreshop_order_hexiao_record")->where(['uniacid'=>UNIACID,'order_id'=>$order['id']])->select();
            foreach ($hexiao_record as $key => &$val){
                $val['info'] = iunserializer($val['info']);
                if($val['user_id'] > 0){
                    $val['info']['user']['avatar'] = cdnurl($val['info']['user']['avatar']);
                    $val['createtime'] = date("Y-m-d H:i:s",$val['createtime']);
                }
            }
            unset($val);
            $order['hexiao_record'] = $hexiao_record;
            $hexiao_store = iunserializer($order['hexiao_store']);
            $hexiao_store['logo'] = cdnurl($hexiao_store['logo']);
            $order['hexiao_store'] = [$hexiao_store];
        }
        
        
        $result = ['order'=>$order,'order_goods'=>$order_goods];
        
        if($order['order_type'] == 2){
            $express_list = Db::name("bbfx_express")->where(['status'=>1])->field(['id','name','coding'])->order('sort desc')->select();
            $result['express_list'] = $express_list;
        }
        if($order['order_type'] == 2 && $order['status'] > 1){
            $express = iunserializer($order['express']);
            $goods_list = [];
            foreach ($express as $key => &$val){
                $val['deliverytime'] = $order['deliverytime'];
                if($order['deliver_type'] == 1){
                    $val['goods'] = $goods_all;
                }
                else if($order['deliver_type'] == 2 || $order['deliver_type'] == 3){
                    $val['goods'] = [$goods_list[$val['goods_id']]];
                }
            }
            unset($val);
            $result['express'] = $express;
        }

        $fenxiao_order_list = Db::name("bbfx_fenxiao_order")->where(['uniacid'=>UNIACID,'user_id'=>['>',0],'order_type'=>3,'order_id'=>$order['id']])->order('type asc')->select();
        if(empty($fenxiao_order_list)){
            $fenxiao_order_list = [];
        }
        
        $texts = $_W['base']['fenxiao']['texts'];
        $levels = \app\common\model\bbfxshop\FenxiaoLevel::getLevels(1);
        foreach ($fenxiao_order_list as $key => &$val){
            $user = Db::name("bbfx_user")->where(['id'=>$val['user_id']])->field(['id','avatar','nickname','level','sup_uid'])->find();
            $sup_user = Db::name("bbfx_user")->where(['id'=>$user['sup_uid']])->field(['id','avatar','nickname','level','sup_uid'])->find();
            if(!empty($user)){
                $user['level_name'] = $levels[$val['level']]['title'];
                // $user['level_name'] = $levels[$user['level']]['title'];
                $user['avatar'] = cdnurl($user['avatar']);
                $val['user'] = $user;
            }
            if(!empty($sup_user)){
                $sup_user['level_name'] = $levels[$sup_user['level']]['title'];
                $sup_user['avatar'] = cdnurl($sup_user['avatar']);
                $val['sup_user'] = $sup_user;
            }
            
	        $val['typeText']= \app\common\model\bbfxshop\Fenxiao::getTypeText($val['type'],$val['money_type']);
	        if($val['money_type'] == 2){
                $val['moneyText'] = "+".floatval($val['money']).$base['texts']['score_unit'];
            }
            else{
                $val['moneyText'] = "+".floatval($val['money']).$texts['yuan'];
            }
        }
        unset($val);
        
        $result['fenxiao_order_list'] = $fenxiao_order_list;
        
        __success("操作成功",$result);
    }
    
    public function hexiao(){
        $id = $this->param('order_id/d');
        
        $result = $this->model->hexiao($id);
        if($result['code'] != 1){
            \app\admin\model\AdminLog::record("","",['id'=>$id],'bbfx_scoreshop_order');
            __error($result['message']);
        }
        
        __success($result['message']);
    }
    
    public function list(){
        $params = $this->param();
        
        
        $pindex = max(1, intval($params["page"]));
        $psize = intval($params["limit"])?intval($params["limit"]):10;
        
        $where = array("a.uniacid"=>UNIACID);
         
        $keyword = trim($params['keyword']);
        $startTime = trim($params['startTime']);
        $endTime = trim($params['endTime']);
        $status = intval($params['status']);
        $refund_status = intval($params['refund_status']);
        $type = intval($params['type']);
        if($status != -1){
            if($status == 4){
                 $where['a.status'] = ['>=',1];
                if($refund_status != -1){
                    $where['a.refund_status'] = $refund_status;
                }
                else{
                    $where['a.refund_status'] = ['neq',-1];
                }
            }
            else{
                $where['a.status'] = $status;
            }
        }
        
        if($keyword){
            if($type == 1){
                $where['a.order_no'] = ['like',"%".$keyword."%"];
            }
            else if($type == 2){
                $where['b.nickname'] = ['like',"%".$keyword."%"];
            }
            else if($type == 3){
                $where['a.delivery_username'] = ['like',"%".$keyword."%"];
            }
            else if($type == 4){
                $where['a.user_id'] = intval($keyword);
            }
        }
        
        $whereTime = [];
        if($startTime){
            $startTime = strtotime($startTime." 00:00:00");
            $where['a.createtime'] = ['>=',$startTime];
        } 
        
        if($endTime){
            $endTime = strtotime($endTime." 23:59:59");
            $whereTime['a.createtime'] = ['<=',$endTime];
        }
        
    	$list = Db::name("bbfx_scoreshop_order")->alias("a")->join("bbfx_user b","a.user_id=b.id")->where($where)->where($whereTime)->field('a.*,b.avatar,b.nickname')->order('a.createtime desc')->limit(($pindex - 1) * $psize,$psize)->select();
    	$export = intval($params['export']);
        if($export == 1){
            $pindex = 1;
            $psize = 999999;
        }
        $export_list = [];
    	foreach($list as $key => &$val){
            
            $val['store_name'] = Db::name("bbfx_store")->where(['id'=>$val['store_id']])->value("name");
    	    if(empty($val['store_name'])){
    	        $val['store_name'] = "";
    	    }
    	    $val['avatar'] = cdnurl($val['avatar']);
    	    $order_goods = Db::name("bbfx_scoreshop_order_goods")->where(["uniacid"=>UNIACID,"order_id"=>$val['id']])->select();
    	    
    	    foreach ($order_goods as $k => &$v){
    	        $goods_info = iunserializer($v['goods_info']);
    	        $goods_info['thumb'] = cdnurl($goods_info['thumb']);
    	        $v['goods'] = $goods_info;
    	    }
    	    unset($v);
    	    $val['order_goods'] = $order_goods;
    	    
    	    if($val['status'] >= 1){
    	        $val['pay_time'] = date("Y-m-d H:i:s",$val['pay_time']);
    	    }
    	    else{
    	        $val['pay_time'] = "";
    	    }
    	    
    	    $val['createtime'] = date("Y-m-d H:i:s",$val['createtime']);
    	    
    	    $val['typeText'] = $this->model->getOrderType($val['order_type']);
    	    $val['refund_statusText'] = $this->model->getOrderRefundStatus($val['refund_status']);
    	    $val['statusText'] = $this->model->getOrderStatus($val);

            if($export == 1){
    	        
    	        $delivery = $val['delivery_username']." ".$val['delivery_mobile'].','.$val['delivery_province'].$val['delivery_city'].$val['delivery_area'].$val['delivery_street'].$val['delivery_address'];
    	        if(empty($val['delivery_mobile'])){
                    $delivery = '';
                }
    	        
    	        foreach ($order_goods as $k => $v){
    	            
        	        $goods = $v['goods'];

                    $product_code = $goods['product_code'];
                    if(!empty($goods['sku'])){
                        $product_code = $goods['sku']['product_code'];
                    }

        	        $export_list[] = array(
        	            $val['id'],
        	            $val['order_no'],
        	            $val['store_name'],
        	            "(ID:{$val['user_id']})".$val['nickname'],
        	            $val['price'],
        	            $val['score'],
        	            $goods['title'],
        	            $v['price'],
        	            $v['score'],
        	            $v['total'],
        	            $delivery,
        	            $val['typeText'],
        	            $val['statusText'],
        	            $val['refund_statusText'],
        	            $val['remarks'],
        	            $val['createtime']
        	        );
        	    }
        	    
    	    }
    	}
    	unset($val);

        if($export == 1){
    	    $headArr = ["订单ID","订单编号","核销门店","用户信息","订单金额","订单积分","商品名称","商品金额","商品积分","商品数量","收货信息","订单类型","订单状态","退款状态","订单备注","下单时间"];
    	    $result = \app\common\model\PhpOffice::excelExport("scoreorder-".date("Y-m-d"),$headArr,$export_list,['mergek'=>0,'merges'=>[0,1,2,3,4,5,10,11,12,13,14,15]]);
    	}
      
    	$total = Db::name("bbfx_scoreshop_order")->alias("a")->join("bbfx_user b","a.user_id=b.id")->where($where)->where($whereTime)->count();
    	
    	__success("操作成功",['total'=>$total,'list'=>$list]);
    }
    
    public function delete(){
        $this->commonDelete('bbfx_scoreshop_order');
    }
}