<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台(PHP版)
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
// | 开源版本可自由商用,可去除界面版权logo
// | gitee下载:https://gitee.com/likeshop_gitee/likeadmin
// | github下载:https://github.com/likeshop-github/likeadmin
// | 访问官网:https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\api\logic;

use app\common\logic\BaseLogic;
use app\common\model\logistics\Courier;
use app\common\model\logistics\Logistics;
use app\common\model\logistics\Order;
use app\common\model\logistics\Product;
use app\common\model\logistics\LogisticsRecord;


/**
 * 物流逻辑
 * Class LogisticsLogic
 * @package app\api\logic
 */
class LogisticsLogic extends BaseLogic
{
    /*
     * 物流列表
     * @param $params
     * @return array
     */
    public static function list($params):array {
        //获取物流列表
        if(!isset($params['status'])){
            $status = ['status','in','0,1'];
        }else{
            $status = ['status','=',$params['status']];
        }
        $logistics = Logistics::where('courier_id', $params['courier_id'])
                    ->where([$status])
                    ->where('(order_sn="'.$params['keywords'].'" OR shop_name LIKE "%'.$params['keywords'].'%"  OR user_name LIKE "%'.$params['keywords'].'%")')
                    ->order('update_time desc')
                    ->paginate([
                        'list_rows'=> !empty($params['page_size'])? $params['page_size'] : 6,
                        'page' => !empty($params['page_num'])? $params['page_num'] : 1,
                    ])->each(function($lst_item){
                        $lst_item['status_name'] = $lst_item->status_name;
                        $product_count = 0;
                        //获取产品信息
                        $lst_item['products'] = Product::field('product_num,cart_info')->where('order_id', $lst_item['order_id'])->select()->each(function($pro_item) use(&$product_count){
                            $pro_item['cart_info'] = json_decode($pro_item['cart_info'], true);
                            $pro_item['goods_name'] = $pro_item['cart_info']['product']['store_name'];
                            $pro_item['goods_unit'] = $pro_item['cart_info']['product']['unit_name'];
                            $product_count += $pro_item['product_num'];
                            unset($pro_item['cart_info']);
                            return $pro_item;
                        });
                        $lst_item['product_count'] = $product_count;
                        return $lst_item;
                    })->toArray();
        //返回数据
        return $logistics;
    }

    /*
     * 配送端物流详情
     * @param $id
     * @return array
     */
    public static function cDetail($id):array {
        //获取物流信息
        $logistics = Logistics::field('id,order_id,order_sn,shop_name,shop_phone,shop_address,user_name,user_phone,user_address,shop_long,shop_lat,status,create_time')
                    ->where('id', $id)->find();
        //获取商品信息
        $product_count = 0;
        $product = Product::field('product_num,cart_info')->where('order_id', $logistics['order_id'])->select()->each(function($pro_item) use(&$product_count){
            $pro_item['cart_info'] = json_decode($pro_item['cart_info'], true);
            $pro_item['goods_name'] = $pro_item['cart_info']['product']['store_name'];
            $pro_item['goods_unit'] = $pro_item['cart_info']['product']['unit_name'];
            $product_count += $pro_item['product_num'];
            unset($pro_item['cart_info']);
            return $pro_item;
        })->toArray();
        //获取物流记录
        $records = LogisticsRecord::field('type,user_name,content,create_time')
                   ->where('lst_id', $logistics['id'])->order('create_time desc')->select()->each(function($red_item){
                        switch ($red_item['type']) {
                            case 1:
                                $red_item['content'] = '用户'.$red_item['user_name'].$red_item['content'];
                                break;
                            case 2:
                                $red_item['content'] = '配送员'.$red_item['user_name'].$red_item['content'];
                                break;
                            case 3:
                                $red_item['content'] = '平台'.$red_item['user_name'].$red_item['content'];
                                break;
                            default:
                                $red_item['content'] = '未知';
                        }
                        unset($red_item['type'], $red_item['user_name']);
                   })->toArray();
        //返回数据
        return[
            'logistics' => $logistics,
            'product' => $product,
            'product_count' => $product_count,
            'record' => $records,
        ];
    }

    /*
     * 商超用户物流详情
     * @param $params
     * @return array
     */
    public static function uDetail($params):array {
        //获取物流信息
        $logistics = Logistics::field('id,order_id,order_sn,courier_id,shop_name,shop_phone,shop_address,user_name,user_address,status,create_time')
            ->where('order_id', $params['order_id'])->where('order_sn',$params['order_sn'])->find();
        //获取物流记录
        $records = LogisticsRecord::field('type,user_name,content,create_time')
            ->where('lst_id', $logistics['id'])->order('create_time desc')->select()->each(function($red_item){
                switch ($red_item['type']) {
                    case 1:
                        $red_item['content'] = '用户'.$red_item['user_name'].$red_item['content'];
                        break;
                    case 2:
                        $red_item['content'] = '配送员'.$red_item['user_name'].$red_item['content'];
                        break;
                    case 3:
                        $red_item['content'] = '平台'.$red_item['user_name'].$red_item['content'];
                        break;
                    default:
                        $red_item['content'] = '未知';
                }
                unset($red_item['type'], $red_item['user_name']);
            })->toArray();
        $courier = Courier::alias('u')
                   ->field('u.nickname,a.phone')
                   ->leftjoin('la_admin a', 'u.admin_id = a.id')
                   ->where('u.id', $logistics['courier_id'])->find();
        //返回数据
        return[
            'logistics' => $logistics,
            'courier' => $courier,
            'record' => $records,
        ];
    }

    /*
     * 生成物流信息
     * @param $params
     * @return array
     */
    public static function create($params):array {
        //判断物流信息是否已存在
        $logistics = Logistics::where('order_id', $params['order_id'])->where('order_sn', $params['order_sn'])->find();
        if($logistics) return ['code'=>0, 'msg'=>'物流信息已存在'];
        //查找订单信息
        $order = Order::alias('s')
                ->leftjoin('eb_merchant m', 'm.mer_id = s.mer_id')
                ->field('s.real_name, s.user_phone,s.uid, s.user_address,s.user_address_code,m.mer_id,m.mer_name,m.mer_phone,m.mer_address,m.long,m.lat')
                ->where('order_id', $params['order_id'])->where('order_sn', $params['order_sn'])->find();
        if(empty($order['user_address_code'])) return ['code'=>1, 'msg'=>'用户地址信息错误'];
        //匹配配送员
        $courier = Courier::alias('u')
                    ->leftjoin('la_company c', 'c.id = u.company_id')
                    ->where("CONCAT_WS(',',u.province,u.city,u.area,u.street,u.village,u.brigade) = '". $order['user_address_code']."'")
                    ->where('u.is_contract', 1)
                    ->where('u.is_captain',1)
                    ->value('c.user_id');
        //判断配送员是否存在
        if(!$courier) return ['code'=>0, 'msg'=>'暂无配送员'];
        //写入数据
        Logistics::startTrans();
        try {
            $lst = Logistics::create([
                'order_id' => $params['order_id'],
                'order_sn' => $params['order_sn'],
                'courier_id' => $courier,
                'shop_id' => $order['mer_id'],
                'shop_name' => $order['mer_name'],
                'shop_phone' => $order['mer_phone'],
                'shop_address' => $order['mer_address'],
                'shop_long' => $order['long'],
                'shop_lat' => $order['lat'],
                'user_id' => $order['uid'],
                'user_name' => $order['real_name'],
                'user_phone' => $order['user_phone'],
                'user_address' => $order['user_address'],
                'status' => 0,
                'create_time' => time(),
                'update_time' => time(),
            ]);
            LogisticsRecord::create([
                'lst_id' => $lst->id,
                'type' => 1,
                'user_name' => $order['real_name'],
                'user_phone' => $order['user_phone'],
                'content' => '用户提交订单',
                'create_time' => time(),
            ]);
            Logistics::commit();
            return ['code'=>1, 'msg'=>'操作成功'];
        } catch (\Exception $e) {
            Logistics::rollback();
            return ['code'=>0, 'msg'=>$e->getMessage()];
        }
    }

    /*
     * 配送员接单
     * @param $params
     * @return array
     */
    public static function takeGoods($params):array {
        //获取物流信息
        $logistics = Logistics::where('id', $params['logistics_id'])->find();
        if (!$logistics) return ['code'=>0, 'msg'=>'物流信息不存在'];
        //判断订单是否一致
        if($logistics['order_id'] !== $params['order_id'] || $logistics['order_sn'] !== $params['order_sn']) return ['code'=>0, 'msg'=>'订单信息不一致'];
        //判断物流信息状态
        switch ($logistics['status']) {
            case 1:
                return ['code'=>0, 'msg'=>'该商品正在配送中'];
            case 2:
                return ['code'=>0, 'msg'=>'该商品已完成配送'];
            case 3:
                return ['code'=>0, 'msg'=>'该订单已经被取消'];
        }
        //获取配送员信息
        $courier = Courier::field('nickname,mobile')->where('id', $logistics['courier_id'])->find();
        //更改物流信息状态
        Logistics::startTrans();
        try {
            //查询订单用户取件码
            $order = Order::field('logistics_code')->where('order_id', $params['order_id'])->where('order_sn', $params['order_sn'])->find();
            Logistics::where('id', $params['logistics_id'])->update([
                'status' => 1,
                'update_time' => time(),
                'qh_time' => time(),
                'user_take_code' => $order['logistics_code']
            ]);
            LogisticsRecord::create([
                'lst_id' => $logistics['id'],
                'type' => 2,
                'user_name' => $courier['nickname'],
                'user_phone' => $courier['mobile'],
                'content' => '已提取商品',
                'create_time' => time(),
            ]);
            Logistics::commit();
            return ['code'=>1, 'msg'=>'操作成功'];
        } catch (\Exception $e) {
            Logistics::rollback();
            return ['code'=>0, 'msg'=>$e->getMessage()];
        }
    }

    /*
     * 配送员配送
     * @param $params
     * @return array
     */
    public static function doneDelivery($params):array {
        //获取物流信息
        $logistics = Logistics::where('id', $params['logistics_id'])->find();
        if (!$logistics) return ['code'=>0, 'msg'=>'物流信息不存在'];
        //判断物流信息状态
        switch ($logistics['status']) {
            case 0:
                return ['code'=>0, 'msg'=>'该商品未揽件'];
            case 2:
                return ['code'=>0, 'msg'=>'该商品已配送'];
            case 3:
                return ['code'=>0, 'msg'=>'订单已被取消'];
        }
        //验证取件码
        if($logistics['user_take_code'] !== $params['take-code']) return ['code'=>0, 'msg'=>'取件码错误'];
        //获取配送员信息
        $courier = Courier::field('nickname,mobile')->where('id', $logistics['courier_id'])->find();
        //更改物流信息状态
        Logistics::startTrans();
        try {
            Logistics::where('id', $params['logistics_id'])->update([
                'status' => 2,
                'update_time' => time(),
                'ps_time' => time(),
            ]);
            LogisticsRecord::create([
                'lst_id' => $logistics['id'],
                'type' => 2,
                'user_name' => $courier['nickname'],
                'user_phone' => $courier['mobile'],
                'content' => '已完成配送',
                'create_time' => time(),
            ]);
            Logistics::commit();
            return ['code'=>1, 'msg'=>'操作成功'];
        } catch (\Exception $e) {
            Logistics::rollback();
            return ['code'=>0, 'msg'=>$e->getMessage()];
        }
    }

    /*
     * 取消订单
     * @param $params
     * @return array
     */
    public static function cancel($params):array {
        //获取物流信息
        $logistics = Logistics::where('order_id', $params['order_id'])->where('order_sn',$params['order_sn'])->find();
        if (!$logistics) return ['code'=>0, 'msg'=>'物流信息不存在'];
        //判断物流信息状态
        switch ($logistics['status']) {
            case 1:
                return ['code'=>0, 'msg'=>'该商品正在配送中'];
            case 2:
                return ['code'=>0, 'msg'=>'该商品已完成配送'];
        }
        //更改物流信息状态
        Logistics::startTrans();
        try {
            Logistics::where('id', $params['logistics_id'])->update([
                'status' => 3,
                'update_time' => time(),
                'qx_time' => time(),
            ]);
            LogisticsRecord::create([
                'lst_id' => $logistics['id'],
                'type' => 1,
                'user_name' => $logistics['user_name'],
                'user_phone' => $logistics['user_phone'],
                'content' => '已取消订单',
                'create_time' => time(),
            ]);
            Logistics::commit();
            return ['code'=>1, 'msg'=>'操作成功'];
        } catch (\Exception $e) {
            Logistics::rollback();
            return ['code'=>0, 'msg'=>$e->getMessage()];
        }
    }
}