<?php
/**
 *  ╔═══════════════════════════════════════════════════╗
 *  ║                                                   ║
 *  ║     ██╗  ██╗   █████╗    ██████╗                  ║
 *  ║     ██║  ██║  ██╔══██╗  ██╔═══██╗                 ║
 *  ║     ███████║  ███████║  ██║   ██║                 ║
 *  ║     ██╔══██║  ██╔══██║  ██║   ██║                 ║
 *  ║     ██║  ██║  ██║  ██║  ╚██████╔╝   SNS           ║
 *  ║                                                   ║
 *  ║                                                   ║
 *  ║     © 2023 HaoSNS™ All Rights Reserved            ║
 *  ║     官方网站: https://www.haosns.com                *
 *  ║     本代码由赣州乐易网络科技有限公司®提供             *
 *  ║                                                    *
 *  ║   未经授权禁止复制、传播或用于其他商业目的            *
 *  ║                                                   ║
 *  ╚═══════════════════════════════════════════════════╝
 */

namespace app\api\controller\twoshop;

// use app\api\lists\OrderLists;
use app\api\logic\twoshop\OrderLogic;
use app\api\validate\twoshop\PlaceOrderValidate;
use app\api\validate\twoshop\OrderValidate;
use app\common\model\TwoOrder;

/**
 * 订单
 * Class OrderController
 * @package app\api\controller
 */
class Order extends \app\api\controller\BaseShopController
{
    public array $notNeedLogin = ['listComments'];

    /**
     * 创建订单
     */
    public function create()
    {
        $data = [
            'terminal' => $this->userInfo['terminal'],
            'user_id'=> $this->userId
        ];
        // 验证参数
        $params = (new PlaceOrderValidate())->post()->goCheck('', $data);

        // 订单结算信息计算
        $settlement = OrderLogic::settlement($params);
        if (false === $settlement) {
            return show(0,OrderLogic::getError());
        }

        // dd($settlement);
        // 提交新订单
        $result = OrderLogic::submitOrder($settlement);
        if (false === $result) {
            return show(0,OrderLogic::getError());
        }

        return show(1,'订单创建成功',$result);

    }

    /**
     * @notes 查看物流
     * @return \think\response\Json
     */
    public function orderTraces()
    {
        $params = (new OrderValidate())->goCheck('OrderTraces', ['user_id' => $this->userId]);
        // $params = $this->request->get();
        // dd($params);
        $result = OrderLogic::orderTraces($params);
        return $this->data($result);
    }

    /**
     * @notes 订单详情
     * @return \think\response\Json
     */
    public function detail()
    {
        $params = (new OrderValidate())->goCheck('detail', ['user_id' => $this->userId]);
        // dd($params);
        return $this->data(OrderLogic::getDetail($params));
    }


    /**
     * @notes 订单列表
     * @return \think\response\Json
     */
    // public function lists()
    // {
    //     return $this->dataLists((new OrderLists()));
    // }




    /**
     * 提交评论
     */
    public function addComment()
    {
        $params = $this->request->post();
        $orderGoods = \app\common\model\TwoOrder::with("order_goods")
        ->find($params['oid']);

        // 查询订单是否已收货
        $orderLog = \app\common\model\TwoOrderLog::where([
            ['order_id','=',$params['oid']],
            ['operator_id','=',$this->userId],
            ['type','=','3'],
            ['channel','=','103']
        ])
        ->find();

        if(!$orderLog){
            return show(0,'订单异常或未收货');
        }

        $from = 'buy';
        if($orderGoods->sell_user_id == $this->userId){
            $from = 'sell';
        }

        $res = \app\common\model\TwoGoodsComment::create([
            'from'=>$from ,//来自买家
            'sell_user_id'=>$orderGoods->sell_user_id,
            'goods_id'=>$orderGoods->order_goods->goods_id,
            'item_id'=>$orderGoods->order_goods->item_id,
            'spec_value_str'=>$orderGoods->order_goods->goods_name,
            'user_id'=>$this->userId,
            'order_goods_id'=>$orderGoods->order_goods->id,
            'goods_comment'=> $params['goods_comment'],//'商品评论星级 1 一星 2 二星 3三星 4四星 5五星'
            'service_comment'=>$params['service_comment'],//'服务评论星级 1 一星 2 二星 3三星 4四星 5五星',
            'description_comment'=>$params['description_comment'],//'描述相符星级1 一星 2 二星 3三星 4四星 5五星',
            'express_comment'=>$params['express_comment'],//'物流评论星级 1 一星 2 二星 3三星 4四星 5五星',
            'comment'=>$params['comment'],//'商品评论',
            'images'=>$params['images'],
            // 'reply'=>$params['reply'],//'商家回复',
            'status'=>0,//状态,
        ]);

        // dd($res);
        return show(1,'评论成功');
    }

    public function addReply()
    {
        $params = $this->request->post();

        if (!isset($params['id']) || !isset($params['text'])) {
            return show(0,'参数错误');
        }

        $comment =  \app\common\model\TwoGoodsComment::where('sell_user_id',$this->userId)->where('id',$params['id'])->find();

        if (!$comment) {
            return show(0,'不存在');
        }

        \app\common\model\TwoGoodsComment::where('sell_user_id',$this->userId)->where('id',$params['id'])->update([
            'reply'=>$params['text'],
        ]);

        return show(1,'回复成功');
    }

    public function listComments()
    {
        $params = $this->request->param();

        $where = [];

        if (isset($params['goods_id'])) {
            $where[] = ['goods_id', '=', $params['goods_id']];
        }

        if (isset($params['order_id'])) {
            $order = TwoOrder::find($params['order_id']);
            if (!$order) return show(0,'订单不存在');
            $where[] = ['order_goods_id', '=', $order->order_goods->id];
        }

        $data = \app\common\model\TwoGoodsComment::where($where)->with(['user'])->select()->toArray();

        if (!$data) {
            return show(0,'不存在');
        }

        foreach ($data as &$item) {
            if (!empty($item['user'])) {
                $item['user']['location'] = \app\common\model\User::where('id', $item['user']['id'])->value('ip_address');
            }
        }

        return show(1, '评论列表', $data);
    }


    /**
     * 卖家发货
     */
    public function send()
    {
        $params = $this->request->post();

        $order = TwoOrder::where([
            ['order_status','=',1],
            ['id','=',$params['id']],
            ['sell_user_id','=',$this->userId]
        ])->find();

        if(!$order){
            return show(0,'订单不存在');
        }
        // 物流发货逻辑
        $order->delivery_type = $params['delivery_type'];
        $order->express_id = $params['express_id'];//快递公司id
        $order->invoice_no = $params['invoice_no'];//物流单号
        $order->express_time = time();//发货时间
        $order->order_status = 2;//订单状态;0-待付款;1-待发货;2-待收货;3-已完成;4-已关闭
        $order->save();

        return show(config('status.success'),'success');

    }

    /**
     * 快递公司列表
     */
    public function expressList()
    {
        $list = \app\common\model\Express::field('id,name,icon')
        ->order(['sort'=>'desc'])
        ->select()->toArray();

        return show(1,'success', $list);
    }

    /**
     * @notes 取消订单
     * @return \think\response\Json
     */
    public function cancel()
    {
        // 只有未支付的订单才可以取消
        $params = (new OrderValidate())->post()->goCheck('cancel', ['user_id' => $this->userId]);
        $result = OrderLogic::cancelOrder($params);
        if (false === $result) {
            return $this->fail(OrderLogic::getError());
        }
        return $this->success('取消订单成功');
    }

    /**
     * @notes 获取配送方式
     * @return \think\response\Json
     */
    // public function getDeliveryType()
    // {
    //     $result = (new OrderLogic())->getDeliveryType();
    //     return $this->success('',$result);
    // }

    /**
     * @notes 删除订单
     * @return \think\response\Json
     */
    public function del()
    {
        $params = (new OrderValidate())->post()->goCheck('del', ['user_id' => $this->userId]);
        (new OrderLogic())->del($params);
        return $this->success('删除成功',[],1,1);
    }

        /**
     * @notes 确认收货
     * @return \think\response\Json
     */
    public function confirm()
    {
        $params = (new OrderValidate())->post()->goCheck('confirm', ['user_id' => $this->userId]);
        OrderLogic::confirmOrder($params);
        return $this->success('确认收货成功');
    }

}