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

namespace app\api\controller\merchant_admin;

use app\api\controller\merchant_admin\MerchantBase;
use think\Db;
use app\common\model\bbfxshop\Order as OrderModel;

class Order extends MerchantBase
{
    protected $noNeedLogin = [];
    protected $noMerchantNeedRight = [];
    protected $noNeedRight = ['*'];
    
    public function getList(){
        $params = $this->param();
        $page = max(1,$this->param("page/d"));
        $psize = 10;
        
        $user = $this->user;
        
        $status = intval($params['status']);
        $where = ['a.uniacid'=>UNIACID,'a.mid'=>$this->mid];
        if($status == 1){
            $where['a.status'] = 0;
        }
        else if($status == 2){
            $where['a.status'] = 1;
            $where['a.refund_status'] = ['in',[-1,2]];
        }
        else if($status == 3){
            $where['a.status'] = 2;
            $where['a.refund_status'] = ['in',[-1,2]];
        }
        else if($status == 4){
            $where['a.status'] = 3;
            $where['a.refund_status'] = ['in',[-1,2]];
        }
        else if($status == 5){
            $where['a.status'] = ['>',0];
            $where['a.refund_status'] = ['in',[0,1,2]];
        }
        
        $list = Db::name("bbfx_order")->alias("a")->join("bbfx_user b","a.user_id=b.id","LEFT")->where($where)->order('id desc')->field("a.id,a.order_no,a.mid,a.user_id,a.price,a.goods_info,a.order_type,a.status,a.refund_status,a.is_pay,a.paytype,a.pay_time,a.is_hexiao,a.delivery_method,a.cash_pay_shenhe,a.createtime,b.nickname,b.avatar")->limit(($page-1)*$psize,$psize)->select();
        if(!empty($list)){
            foreach($list as $key => &$val){
                $val['avatar'] = cdnurl($val['avatar']);
                
                $val['paytypeText'] = OrderModel::getOrderPaytype($val);
                $val['statusText'] = OrderModel::getOrderStatus($val);
                
                $goods_info = iunserializer($val['goods_info']);
                
                foreach ($goods_info as $k => &$v){
                    $v['thumb'] = cdnurl($v['thumb']);
                }
                unset($v);
                
                $val['goods_info'] = $goods_info;
                
                $val['pay_time'] = date("Y-m-d H:i:s",$val['pay_time']);
                $val['createtime'] = date("Y-m-d H:i:s",$val['createtime']);
            }
            unset($val);
            __success("操作成功",$list);
        }
        else{
            __error("未查询到订单");
        }
    }
    
    public function detail(){
        $id = $this->param('id/d');
        
        $where = ['a.uniacid'=>UNIACID,'a.id'=>$id,'a.mid'=>$this->mid];
        
        $order = Db::name("bbfx_order")->alias("a")->join("bbfx_user b","a.user_id=b.id","LEFT")->where($where)->field("a.*,b.nickname,b.avatar")->find();
        if(empty($order)){
            __error("订单不存在");
        }
        
        $order['avatar'] = cdnurl($order['avatar']);
        
        if(($order['order_type'] == 3 || $order['order_type'] == 2 || $order['order_type'] == 4) && $order['is_hexiao'] == 1 && $order['status'] == 3){
            $hexiao_user = Db::name("bbfx_user")->where("id",$order['hexiao_uid'])->field("id,nickname,avatar,level")->find();
            if(!empty($hexiao_user)){
                $hexiao_user['avatar'] = cdnurl($hexiao_user['avatar']);
                $order['hexiao_user'] = $hexiao_user;
            }
        }
        
        if($order['order_type'] == 2){
            $order['express'] = iunserializer($order['express']);
        }
        
        $goods_info = iunserializer($order['goods_info']);
        foreach ($goods_info as $key => &$val){
            $val['thumb'] = cdnurl($val['thumb']);
        }
        unset($val);
        $order['goods_info'] = $goods_info;
        $order['createtime'] = date("Y-m-d H:i:s",$order['createtime']);
        $order['pay_time'] = date("Y-m-d H:i:s",$order['pay_time']);
        $order['hexiao_time'] = date("Y-m-d H:i:s",$order['hexiao_time']);
        
        $order_goods = Db::name("bbfx_order_goods")->where(["uniacid"=>UNIACID,"order_id"=>$order['id']])->select();
        $og_ids = [];
        foreach($order_goods as $k => &$v){
            $og_ids[] = $v['id'];
            $goods_info = iunserializer($v['goods_info']);
            $goods_info['thumb'] = cdnurl($goods_info['thumb']);
            $v['goods'] = $goods_info;
            if($goods_info['type'] == 1 && $v['status'] >= 1){
                $serial_number = Db::name("bbfx_serial_number")->where(['uniacid'=>UNIACID,'pid'=>$v['id']])->find();
                if(!empty($serial_number)){
                    $v['serial_number'] = $serial_number;
                }
                else{
                    $v['serial_number'] = "";
                }
            }
        }
        unset($v);
        $order['order_goods'] = $order_goods;
                
        $order['paytypeText'] = OrderModel::getOrderPaytype($order);
        
        $order['statusText'] = OrderModel::getOrderStatus($order);
        
        $order['hexiao_store'] = iunserializer($order['hexiao_store']);
        
        // print_r($order['store']);die;
        
        $order['give_balance'] = Db::name("bbfx_money_log")->where(['uniacid'=>UNIACID,'item_id'=>['in',$og_ids],'user_id'=>$order['user_id'],'type'=>1,'item_type'=>24])->sum("money");
        $order['give_score'] = Db::name("bbfx_money_log")->where(['uniacid'=>UNIACID,'item_id'=>['in',$og_ids],'user_id'=>$order['user_id'],'type'=>2,'item_type'=>24])->sum("money");
        $order['give_balance'] = round($order['give_balance'],2);
        $order['give_score'] = round($order['give_score'],2);
        
        
        $order['coupon_list'] = Db::name("bbfx_user_coupon")->where(['uniacid'=>UNIACID,'item_id'=>['in',$og_ids],'receive_type'=>3,'user_id'=>$order['user_id']])->select();
        
        $order['hx_list'] = OrderModel::getHexiaoCode($order,$order['platform']);
        if(!empty($order['hx_list'])){
            $order['hexiao_total'] = count($order['hx_list']);
            $order['hexiao_num'] = 0;
            foreach($order['hx_list'] as $key => $val){
                if($val['status'] == 0){
                    $order['hexiao_num']++;
                }
            }
        }

        __success("操作成功",$order);
    }
    
    protected function extractData(){
        $params = $this->param();
        
        $order_id = intval($params['id']);
        $order = Db::name("bbfx_order")->where(['id'=>$order_id,'mid'=>$this->mid])->find();
        if(empty($order)){
            __error("订单不存在");
        }
        
        return ['order_id'=>$order_id,'order'=>$order,'params'=>$params];
    }
    
    public function refund(){
        $extractData = $this->extractData();
        extract($extractData);
        if($order['is_pay'] != 1){
            __error("订单未支付");
        }
        
        if($order['refund_status'] == 1){
            __error("订单已退款");
        }
        if($order['pintuan_miandan_status'] == 1){
            __error("拼团免单订单不支持重复退款");
        }
        
        $type = intval($params['type']);
         
        if($type == 1){
            $refund = Db::name("bbfx_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,
                    "content"=>"平台退款",
                    "createtime"=>time()
                );
                
                $refund_id = Db::name("bbfx_order_refund")->insertGetId($data);
        
                if(empty($refund_id)){
                    __error("退款失败");
                }
                Db::name("bbfx_order")->where(['id'=>$order_id])->update(['refund_status'=>0]);
            }
            else{
                if($refund['status'] == 1){
                    Db::name("bbfx_order")->where(['id'=>$order_id])->update(['refund_status'=>1]);
                    __error("退款失败");
                }
            }
            $status = 1;
        }
        else{
            $status = intval($params['status']);
        }
        
        $result = OrderModel::refund($order_id,$status,$type);
        if(!empty($result) && $result['code'] === 1){
            __success("退款成功");
        }
        else{
            __error($result['message']);
        }
    }
    
    public function refundDetail(){
        $params = $this->param();
        
        $user = $this->user;
        $order_id = intval($params['id']);
        
        $order = Db::name("bbfx_order")->where(['id'=>$order_id,'is_pay'=>1,'mid'=>$this->mid])->find();
        
        if(empty($order)){
            __error("订单不存在");
        }
        
        $order_refund = Db::name("bbfx_order_refund")->where(['order_id'=>$order['id']])->find();
        if(empty($order_refund)){
            __error("未查询到退款信息");
        }
        
        $order_goods = Db::name("bbfx_order_goods")->where(["uniacid"=>UNIACID,"order_id"=>$order['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);
        
        if($order_refund['createtime'] > strtotime(date("Y-01-01 00:00:00"))){
            $createtime = date("m/d H:i",$order_refund['createtime']);
        }
        else{
            $createtime = date("Y/m/d H:i",$order_refund['createtime']);
        }
        
        $steps = array(
            array('title'=>'提交申请','time'=>$createtime),
            array('title'=>'商家审核','time'=>''),
            array('title'=>'退款成功','time'=>''),
        );
        $order_refund['step'] = 0;
        if($order_refund['status'] > 0){
            if($order_refund['refundtime'] > strtotime(date("Y-01-01 00:00:00"))){
                $refundtime = date("m/d H:i",$order_refund['refundtime']);
            }
            else{
                $refundtime = date("Y/m/d H:i",$order_refund['refundtime']);
            }
            $steps[1]['time'] = $refundtime;
            $steps[2]['time'] = $refundtime;
            
            $order_refund['step'] = 2;
        }
        if($order_refund['status'] == 1){
            $steps[2]['title'] = '退款成功';
        }
        else if($order_refund['status'] == 2){
            $steps[2]['title'] = '退款失败';
        }
        $order_refund['createtime'] = date("Y-m-d H:i:s",$order_refund['createtime']);
        $order_refund['images'] = iunserializer($order_refund['images']);
        foreach ($order_refund['images'] as $key => &$val){
            $val = cdnurl($val);
        }
        unset($val);
        __success("操作成功",['order'=>$order,'steps'=>$steps,'order_goods'=>$order_goods,'refund'=>$order_refund]);
    }
    
    public function updateDeliver(){
        $extractData = $this->extractData();
        extract($extractData);
        if($order['is_pay'] != 1){
            __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_street"=>$delivery_dz[3],
            "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_order")->where(['id'=>$order['id']])->update($data);
        
        if($res){
            __success("修改成功");
        }
        else{
            __error("修改失败");
        }
    }
    
    public function updateRemarks(){
        $extractData = $this->extractData();
        extract($extractData);
        
        $content = $params['content'];
        
        $res = Db::name("bbfx_order")->where(['id'=>$order['id']])->update(['remarks'=>$content]);
        
        if($res){
            __success("修改成功");
        }
        else{
            __error("修改失败");
        }
    }
    
    public function takeDelivery(){
        $extractData = $this->extractData();
        extract($extractData);
        $result = OrderModel::takeDelivery($order['id']);
        __result($result);
    }
    
    public function send(){
        $extractData = $this->extractData();
        extract($extractData);
        
        $result = OrderModel::checkFahuo($order);
        if($result['code'] !=1){
            __result($result);
        }
        
        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'] == 2){
                $res = true;
            }
            else if($order['status'] == 1){
                $res = Db::name("bbfx_order")->where(['id'=>$order['id'],'status'=>1])->update(['status'=>2]);
            }
            if($res){
                $udata = ['deliverytime'=>time()];
                if($order['order_type'] == 2){
                    $udata['express'] = iserializer($expressInfo);
                    $udata['deliver_type'] = $deliver_type;
                }
                
                Db::name("bbfx_order")->where(['id'=>$order['id']])->update($udata);
                
                \app\common\model\bbfxshop\Message::sendShippingnoticeMsg($order['id']);
                
                \app\common\model\bbfxshop\Sms::sendOrderDeliveryNotice($order['id']);
                
                OrderModel::sendGoods($order['id']);

                __success("发货成功");
            }
            else{
                __error("发货失败");
            }
        }
        else if($order['order_type'] == 1 || $order['order_type'] == 4){
            $res = OrderModel::takeDelivery($order['id']);
            if(!empty($res) && $res['code'] == 1){
                Db::name("bbfx_order")->where(['id'=>$order['id']])->update(['deliverytime'=>time()]);
                __success("发货成功");
            }
            else{
                 __error($res['message']);
            }
        }
        else{
            __error("商品类型错误");
        }
    }
    
    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("订单未发货");
        }
        
        $result = \app\common\model\bbfxshop\Delivery::queryExpressDelivery($express_no);
        if($result['code'] == 1){
            $express = iunserializer($order['express']);
            $res = $result['data'];
            foreach ($express as $key => &$val){
                if($val['express_no'] == $express_no){
                    $val['express_data'] = $res;
                }
            }
            unset($val);
            
            Db::name("bbfx_order")->where(['id'=>$order['id']])->update(['express'=>iserializer($express)]);
        }
        
        __result($result);
    }

    public function checkHexiaoCode(){
        $code = $this->param("code/s");

        $hxcode = Db::name("bbfx_order_goods_hxcode")->where(['uniacid'=>UNIACID,'hexiao_code'=>$code])->find();
        $hx_id = 0;
        if(!empty($hxcode)){
            $hx_id = $hxcode['id'];
            $order = Db::name("bbfx_order")->where(['uniacid'=>UNIACID,'order_type'=>['in',[3,2,4]],'is_hexiao'=>1,'is_hexiao_quantity'=>1,'mid'=>$this->mid,'id'=>$hxcode['order_id'],'is_pay'=>1])->find();
        }
        else{
            $order = Db::name("bbfx_order")->where(['uniacid'=>UNIACID,'order_type'=>['in',[3,2,4]],'is_hexiao'=>1,'is_hexiao_quantity'=>0,'mid'=>$this->mid,'hexiao_code'=>$code,'is_pay'=>1])->find();
        }

        if(empty($order)){
            __error("核销码错误");
        }
        
        if($order['status'] == 3){
            __error("已完成核销");
        }
        
        __success("操作成功",['order_id'=>$order['id'],'hx_id'=>$hx_id]);
    }
    
    public function hexiao(){
        $id = $this->param('id/d');
        $hx_id = $this->param('hx_id/d');
        $store_id = Db::name("bbfx_store")->where(['uniacid'=>UNIACID,'type'=>1,'main'=>1,'mid'=>$this->mid])->value("id");
        
        $result = OrderModel::hexiao($id,$store_id,$hx_id,$this->user['id'],$this->mid);
        
        __result($result);
    }

    public function cashShenhe(){
        $id = $this->param('order_id/d');
        $status = $this->param('status/d');
        if($status != 1) $status = 2;
        
        $result = OrderModel::cashPay($id,$status,$this->mid);
        
        __result($result);
    }
    
    public function close(){
        $id = $this->param('id/d');
        
        $result = OrderModel::closeOrder($id);
        
        __result($result);
    }
}