<?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\controller;

use think\facade\Db;

/**
 * 文章管理
 * Class ArticleController
 * @package app\api\controller
 */
class LogisticsController extends BaseApiController
{

    public array $notNeedLogin = ['courierLogisticsList','logisticsDetail','logisticsCreate','courierTakeGoods','courierCompleteDelivery','userConfirmReceipt','userCancelOrder'];

    /*
     * 获取配送员物流信息列表
     * @method get
     * @param int $courier_id 配送员id
     * @param int $status 物流状态
     * @param int $page_size 每页数量
     * @param int $page_num 页码
     * @return \think\response\Json
     */
    public function courierLogisticsList(): \think\response\Json
    {
        //获取参数
        $courier_id = input('courier_id', 0, 'intval');
        $status = input('status', 0, 'intval');
        $page_size = input('page_size', 5, 'intval');
        $page_num = input('page_num', 1, 'intval');
        $keywords = input('keywords', '', 'trim');
        if(empty($courier_id)) return $this->fail('参数错误');
        //获取物流信息
        $logistics = Db::name('logistics')->whereRaw('courier_id='.$courier_id.' AND status='.$status.' AND (order_sn="'.$keywords.'" OR shop_name LIKE "%'.$keywords.'%"  OR user_name LIKE "%'.$keywords.'%")')->order('update_time desc')->paginate([
            'list_rows'=> $page_size,
            'page' => $page_num,
        ])->each(
            function ($item, $key) use($status) {
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                switch ($status) {
                    case 0:
                        $item['status_name'] = '待取货';
                        break;
                    case 1:
                        $item['status_name'] = '配送中';
                        break;
                    case 2:
                        $item['status_name'] = '已送达';
                        break;
                    case 3:
                        $item['status_name'] = '已完成';
                        break;
                    case 4:
                        $item['status_name'] = '已取消';
                        break;
                    default:
                        $item['status_name'] = '未知状态';
                }
                $item['products'] = Db::connect('mysql2')->table('eb_store_order_product')->field('product_num,cart_info')->where('order_id', $item['order_id'])->select()->each(
                    function ($item2) {
                        $item2['cart_info'] = json_decode($item2['cart_info'], true);
                        $item2['goods_name'] = $item2['cart_info']['product']['store_name'];
                        $item2['goods_unit'] = $item2['cart_info']['product']['unit_name'];
                        unset($item2['cart_info']);
                        return $item2;
                    }
                )->toArray();
                $item['product_count'] = count( $item['products']);
                return $item;
            }
        )->toArray();
        return $this->data($logistics);
    }

    /*
    * 获取物流信息详情
    * @method get
    * @param int $logistics_id 物流id
    * @return \think\response\Json
    */
    public function logisticsDetail(): \think\response\Json
    {
        //获取参数
        $logistics_id = input('logistics_id', 0, 'intval');
        //获取物流信息
        $logistics = Db::name('logistics')
            ->field('id,order_id,order_sn,shop_name,shop_phone,shop_address,user_name,user_address,status,create_time')
            ->where('id', $logistics_id)->find();
        if(!$logistics) return $this->fail('物流信息不存在');
        $logistics['create_time'] = date('Y-m-d H:i:s', $logistics['create_time']);
        //获取订单商品信息
        $product = Db::connect('mysql2')->table('eb_store_order_product')->field('product_num,cart_info')->where('order_id', $logistics['order_id'])->select()->each(
            function ($item, $key) {
                $item['cart_info'] = json_decode($item['cart_info'], true);
                $item['goods_name'] = $item['cart_info']['product']['store_name'];
                $item['goods_unit'] = $item['cart_info']['product']['unit_name'];
                unset($item['cart_info']);
                return $item;
            }
        )->toArray();
        //获取物流记录
        $record = Db::name('logistics_record')->field('type,user_name,content,create_time')->where('lst_id', $logistics_id)->order('create_time desc')->select()->each(
            function ($item) {
                switch ($item['type']) {
                    case 1:
                        $item['content'] = '用户'.$item['user_name'].$item['content'];
                        break;
                    case 2:
                        $item['content'] = '配送员'.$item['user_name'].$item['content'];
                        break;
                    case 3:
                        $item['content'] = '平台'.$item['user_name'].$item['content'];
                        break;
                    default:
                        $item['content'] = '未知';
                }
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                unset($item['type'], $item['user_name']);
                return $item;
            }
        )->toArray();
        //返回数据
        $data = [
            'logistics' => $logistics,
            'product' => $product,
            'product_count' => count($product),
            'record' => $record,
        ];
        return $this->data($data);
    }

    /*
     * 生成物流信息
     * @method post
     * @param int $order_id 订单id
     * @param string $order_sn 订单编号
     * @return \think\response\Json
     */
    public function logisticsCreate(): \think\response\Json
    {
        //获取参数
        $order_id = input('order_id', 0, 'intval');
        $order_sn = input('order_sn', '', 'trim');
        //判断物流信息是否已存在
        $logistics = Db::name('logistics')->where('order_id', $order_id)->where('order_sn', $order_sn)->find();
        if($logistics) return $this->fail('物流信息已存在');
        //查找订单信息
        $order = Db::connect('mysql2')->table('eb_store_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_name, m.mer_phone, m.mer_address')
            ->where('order_id', $order_id)->where('order_sn', $order_sn)->find();
        if (!$order) return $this->fail('订单信息不存在');
        $addressCode = explode(',', $order['user_address_code']);
        //匹配配送员
        $courier = Db::connect('mysql3')->name('la_user')->where(
            [
                'province'=> $addressCode[0],
                'city'=>	$addressCode[1],
                'area'=>	$addressCode[2],
                'street'=>	$addressCode[3],
                'village'=>	$addressCode[4],
                'brigade'=>	$addressCode[5],
                'is_captain'=>	1,
                'is_contract'=>	1,
            ]
        )->value('id');
        if (!$courier) return $this->fail('暂无配送员');
        //写入数据
        Db::startTrans();
        try {
            $lst_id = Db::name('logistics')->insertGetId([
                'order_id' => $order_id,
                'order_sn' => $order_sn,
                'courier_id' => $courier,
                'shop_name' => $order['mer_name'],
                'shop_phone' => $order['mer_phone'],
                'shop_address' => $order['mer_address'],
                '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(),
            ]);
            Db::name('logistics_record')->insert([
                'lst_id' => $lst_id,
                'type' => 1,
                'user_name' => $order['real_name'],
                'user_phone' => $order['user_phone'],
                'content' => '用户提交订单',
                'create_time' => time(),
            ]);
            Db::commit();
            return $this->success('生成物流信息成功');
        } catch (\Exception $e) {
            Db::rollback();
            return $this->fail('生成物流信息失败');
        }
    }

    /*
     * 配送员提取商品
     * @method post
     * @param int $logistics_id 物流id
     * @return \think\response\Json
     */
    public function courierTakeGoods(): \think\response\Json
    {
        //获取参数
        $logistics_id = input('logistics_id', 0, 'intval');
        $user_id = input('user_id', 0, 'intval');
        //获取物流信息
        $logistics = Db::name('logistics')->where('id', $logistics_id)->where('courier_id',$user_id)->where('status',0)->find();
        if (!$logistics) return $this->fail('物流信息不存在');
        //获取配送员信息
        $courier = Db::connect('mysql3')->name('la_user')->field('real_name,mobile')->where('id', $user_id)->find();
        //设置记录信息
        $record = [
            'lst_id' => $logistics['id'],
            'type' => 2,
            'user_name' => $courier['real_name'],
            'user_phone' => $courier['mobile'],
            'content' => '已提取商品',
            'create_time' => time(),
        ];
        //更改物流信息状态
        $res = $this->logisticsUpdate($logistics_id, 1,$record);
        if($res){
            return $this->success('操作成功');
        }else{
            return $this->fail('操作失败');
        }
    }

    /*
     * 配送员完成配送
     * @method post
     * @param int $logistics_id 物流id
     * @return \think\response\Json
     */
    public function courierCompleteDelivery(): \think\response\Json
    {
        //获取参数
        $logistics_id = input('logistics_id', 0, 'intval');
        $user_id = input('user_id', 0, 'intval');
        //获取物流信息
        $logistics = Db::name('logistics')->where('id', $logistics_id)->where('courier_id',$user_id)->where('status',1)->find();
        if (!$logistics) return $this->fail('物流信息不存在');
        //获取配送员信息
        $courier = Db::connect('mysql3')->name('la_user')->field('real_name,mobile')->where('id', $user_id)->find();
        //设置记录信息
        $record = [
            'lst_id' => $logistics['id'],
            'type' => 2,
            'user_name' => $courier['real_name'],
            'user_phone' => $courier['mobile'],
            'content' => '已完成配送',
            'create_time' => time(),
        ];
        //更改物流信息状态
        $res = $this->logisticsUpdate($logistics_id, 2,$record);
        if($res){
            return $this->success('操作成功');
        }else{
            return $this->fail('操作失败');
        }
    }

    /*
     * 用户确认收货
     * @method post
     * @param int $logistics_id 物流id
     * @return \think\response\Json
     */
    public function userConfirmReceipt(): \think\response\Json
    {
        //获取参数
        $logistics_id = input('logistics_id', 0, 'intval');
        $user_id = input('user_id', 0, 'intval');
        //获取物流信息
        $logistics = Db::name('logistics')->where('id', $logistics_id)->where('user_id',$user_id)->find();
        if (!$logistics) return $this->fail('物流信息不存在');
        if ($logistics['status'] == 4) return $this->fail('不可更改物流状态');
        //设置记录信息
        $record = [
            'lst_id' => $logistics['id'],
            'type' => 1,
            'user_name' => $logistics['user_name'],
            'user_phone' => $logistics['user_phone'],
            'content' => '已确认收货',
            'create_time' => time(),
        ];
        //更改物流信息状态
        $res = $this->logisticsUpdate($logistics_id, 3,$record);
        if($res){
            return $this->success('操作成功');
        }else{
            return $this->fail('操作失败');
        }
    }

    /*
     * 用户取消订单
     * @method post
     * @param int $logistics_id 物流id
     * @return \think\response\Json
     */
    public function userCancelOrder(): \think\response\Json
    {
        //获取参数
        $logistics_id = input('logistics_id', 0, 'intval');
        $user_id = input('user_id', 0, 'intval');
        //获取物流信息
        $logistics = Db::name('logistics')->where('id', $logistics_id)->where('user_id',$user_id)->find();
        if (!$logistics) return $this->fail('物流信息不存在');
        if ($logistics['status'] == 2 || $logistics['status'] == 3 || $logistics['status'] == 4) return $this->fail('订单已完成不能取消订单');
        //设置记录信息
        $record = [
            'lst_id' => $logistics['id'],
            'type' => 1,
            'user_name' => $logistics['user_name'],
            'user_phone' => $logistics['user_phone'],
            'content' => '已取消订单',
            'create_time' => time(),
        ];
        //更改物流信息状态
        $res = $this->logisticsUpdate($logistics_id, 4,$record);
        if($res){
            return $this->success('操作成功', [], 1, 200);
        }else{
            return $this->fail('操作失败', [], 0, 200);
        }
    }

    /*
     * 更新物流信息
     * @method post
     * @param int $logistics_id 物流id
     * @return bool
     */
    private function logisticsUpdate($id,$status,$data):bool
    {
        if(empty($id) || empty($status) || empty($data)) return false;
        Db::startTrans();
        try {
            Db::name('logistics')->where('id', $id)->update(['status' => $status, 'update_time' => time()]);
            Db::name('logistics_record')->insert($data);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return false;
        }
    }
}