<?php

namespace app\api\controller\order;

use app\api\logic\order\OrderLogic;
use app\api\controller\BaseApiController;
use app\api\lists\order\OrderList;
use app\api\service\WechatUserService;
use app\api\validate\OrderValidate;
use app\common\enum\PayEnum;
use app\common\logic\PaymentLogic;
use app\common\logic\PayNotifyLogic;
use app\common\model\retail\Cashierclass;
use app\common\model\store_order\StoreOrder;
use app\common\model\user\UserAddress;
use Webman\RedisQueue\Redis;
use hg\apidoc\annotation as ApiDoc;

#[ApiDoc\title('订单')]
class OrderController extends BaseApiController
{

    /**
     * 订单列表
     */
    public function order_list()
    {

        return $this->dataLists(new OrderList());
    }

    #[
        ApiDoc\Title('核销码查数据'),
        ApiDoc\url('/api/order/order/write_code'),
        ApiDoc\Method('POST'),
        ApiDoc\Param(name: "code", type: "string", require: false, desc: "核销码"),
        ApiDoc\NotHeaders(),
        ApiDoc\Header(name: "token", type: "string", require: true, desc: "token"),
        ApiDoc\ResponseSuccess("data", type: "array"),
    ]
    public function write_code()
    {
        $code = $this->request->post('code');
        if(empty($code)){
            return $this->fail('缺失参数');
        }
        $res = OrderLogic::getOne($code);
        return $this->success('ok',$res);
    }

    #[
        ApiDoc\Title('核销订单列表'),
        ApiDoc\url('/api/order/order/write_list'),
        ApiDoc\Method('POST'),
        ApiDoc\Param(name: "status", type: "int", require: true, desc: "1:待核销;2:已核销"),
        ApiDoc\Param(name: "name", type: "string", require: false, desc: "搜商品或者订单id"),
        ApiDoc\Param(name: "page_no", type: "int", require: true, desc: "默认1页数"),
        ApiDoc\Param(name: "page_size", type: "int", require: false, desc: "条数默认15"),
        ApiDoc\NotHeaders(),
        ApiDoc\Header(name: "token", type: "string", require: true, desc: "token"),
        ApiDoc\ResponseSuccess("data", type: "array"),
    ]
    public function write_list()
    {
        $status = (int)$this->request->post('status',1);
        $page_no = (int)$this->request->post('page_no',1);
        $page_size = (int)$this->request->post('page_size',15);
        $params = $this->request->post();
        if(empty($page_no) || empty($page_size)){
            $params['page_no'] =  1;
            $params['page_size'] =  15;
        }
        $info = $this->userInfo;
        $res = OrderLogic::write_list($info,$status,$params);
        $res['page_no'] =$params['page_no'];
        $res['page_size'] =$params['page_size'];
        return $this->success('ok',$res);

    }

    #[
        ApiDoc\Title('核销数量'),
        ApiDoc\url('/api/order/order/write_count'),
        ApiDoc\Method('POST'),
        ApiDoc\Param(name: "name", type: "string", require: false, desc: "搜商品或者订单id"),
        ApiDoc\NotHeaders(),
        ApiDoc\Header(name: "token", type: "string", require: true, desc: "token"),
        ApiDoc\ResponseSuccess("data", type: "array"),
    ]
    public function write_count()
    {
        $info = $this->userInfo;
        $params = $this->request->post();
        $res = OrderLogic::write_count($info,$params);
        return $this->success('ok',$res);
    }

    #[
        ApiDoc\Title('订单校验'),
        ApiDoc\url('/api/order/order/checkOrder'),
        ApiDoc\Method('POST'),
        ApiDoc\Param(name: "cart_id", type: "int", require: true, desc: "购物车id"),
        ApiDoc\Param(name: "address_id", type: "int", require: true, desc: "地址id"),
        ApiDoc\Param(name: "store_id", type: "int", require: true, desc: "店铺id"),
        ApiDoc\Param(name: "verify_code", type: "int", require: true, desc: "校验码"),
        ApiDoc\Param(name: "shipping_type", type: "int", require: true, desc: "配送方式"),
        ApiDoc\Param(name: "pay_type", type: "int", require: true, desc: "支付类型"),
        ApiDoc\NotHeaders(),
        ApiDoc\Header(name: "token", type: "string", require: true, desc: "token"),
        ApiDoc\ResponseSuccess("data", type: "array", children:[
            ['name' => 'order', 'desc' => '订单信息', 'type' => 'array', 'children' => [
                ['name' => 'create_time', 'desc' => '订单创建时间', 'type' =>'int'],
                ['name' => 'order_id', 'desc' => '订单id', 'type' => 'int'],
                ['name' => 'total_price', 'desc' => '订单总金额', 'type' => 'float'],
                ['name' => 'pay_price', 'desc' => '实际支付金额', 'type' =>'float'],
                ['name' => 'total_num', 'desc' => '订单总数量', 'type' =>'int'],
                ['name' => 'pay_type', 'desc' => '支付方式', 'type' =>'int'],
                ['name' => 'cart_id', 'desc' => '购物车id', 'type' =>'string'],
                ['name' => 'store_id', 'desc' => '店铺id', 'type' =>'int'],
                ['name' => 'shipping_type', 'desc' => '配送方式', 'type' =>'int'],
            ]],
            ['name' => 'cart_list', 'desc' => '购物车商品列表', 'type' => 'array', 'children' => [
                ['name' => 'goods', 'desc' => '商品id', 'type' => 'int'],
                ['name' => 'cart_num', 'desc' => '购买数量', 'type' =>'int'],
                ['name' => 'total', 'desc' => '商品总价', 'type' => 'float'],
                ['name' => 'price', 'desc' => '商品单价', 'type' => 'float'],
                ['name' => 'product_id', 'desc' => '商品id', 'type' =>'int'],
                ['name' => 'old_cart_id', 'desc' => '原购物车id', 'type' =>'string'],
                ['name' => 'verify_code', 'desc' => '校验码', 'type' =>'string'],
            ]],
        ]),
    ]
    public function checkOrder()
    {
        $cartId = (array)$this->request->post('cart_id', []);
        $addressId = (int)$this->request->post('address_id');
        // $pay_type = (int)$this->request->post('pay_type');
        // $auth_code = $this->request->post('auth_code'); //微信支付条码
        $params = $this->request->post();
        $res = OrderLogic::cartIdByOrderInfo($cartId, $addressId, null, $params);
        if ($res == false) {
            $msg = OrderLogic::getError();
            if ($msg == '购物车为空') {
                return $this->data([]);
            }
            return $this->fail(OrderLogic::getError());
        }
        return $this->data($res);
    }

    #[
        ApiDoc\Title('创建订单'),
        ApiDoc\url('/api/order/order/createOrder'),
        ApiDoc\Method('POST'),
        ApiDoc\Param(name: "cart_id", type: "int", require: true, desc: "id"),
        ApiDoc\Param(name: "store_id", type: "int", require: true, desc: "店铺id"),
        ApiDoc\Param(name: "address_id", type: "int", require: true, desc: "地址id"),
        ApiDoc\Param(name: "auth_code", type: "string", require: true, desc: "付款码"),
        ApiDoc\Param(name: "pay_type", type: "int", require: true, desc: "支付类型"),
        ApiDoc\NotHeaders(),
        ApiDoc\Header(name: "token", type: "string", require: true, desc: "token"),
        ApiDoc\ResponseSuccess("data", type: "array"),
    ]
    public function createOrder()
    {
        $cartId = (array)$this->request->post('cart_id', []);
        $store_id = (array)$this->request->post('store_id', 0);
        $pay_type = (int)$this->request->post('pay_type');
        $addressId = (int)$this->request->post('address_id');
        $auth_code = $this->request->post('auth_code'); //微信支付条码
        $params = $this->request->post();
        if ($store_id <= 0 && $pay_type != 9) {
            return $this->fail('自提点不能为空');
        }
        if (count($cartId) > 100) {
            return $this->fail('购物车商品不能超过100个');
        }

//        if ($pay_type == 9 || $pay_type == 17 ||$pay_type==13) {
//            if (empty($this->request->userInfo['merchant'])) {
//                return $this->fail('请先绑定商户');
//            }
//            $mer_id = $this->request->userInfo['merchant']['mer_id'];
//            $params['mer_id'] = $mer_id;
//        }
        $order = OrderLogic::createOrder($cartId, $addressId, null, $params);
        if ($order != false) {
            switch ($pay_type) {
                case PayEnum::BALANCE_PAY:
                    //余额支付
                    PayNotifyLogic::handle('balancePay', $order['order_id']);
                    return $this->success('余额支付成功');
                case PayEnum::CASH_PAY:
                    //现金支付
                    PayNotifyLogic::handle('cash_pay', $order['order_id']);
                    return $this->success('现金支付成功');
                case PayEnum::WECHAT_PAY:
                    //微信支付
                    $redirectUrl = $params['redirect'] ?? '/pages/payment/payment';
                    $result = PaymentLogic::pay($pay_type, 'wechat_common', $order, $this->userInfo['terminal'], $redirectUrl);
                    if (PaymentLogic::hasError()) {
                        return $this->fail(PaymentLogic::getError(), $params);
                    }
                    return $this->success('', $result);
                case  PayEnum::WECHAT_PAY_BARCODE:
                    //微信条码支付
                    $result = PaymentLogic::codepay($auth_code, $order);
                    if (PaymentLogic::hasError()) {
                        return $this->fail(PaymentLogic::getError(), $params);
                    }
                    if (isset($result['trade_state_desc']) && $result['trade_state_desc'] == '支付成功') {
                        PayNotifyLogic::handle('StoreOrder', $result['out_trade_no'], $result);
                    } else {
                        Redis::send('send-code-pay', ['number' => $order['number']]);
                        return $this->success('用户支付中');
                    }
                    return $this->success('支付成功', ['out_trade_no'=>$result['out_trade_no'],'pay_type'=>PayEnum::WECHAT_PAY_BARCODE,'transaction_id'=>$result['transaction_id']]);
                case  PayEnum::ALIPAY_BARCODE:
                    //支付宝条码支付
                    $result = PaymentLogic::ali_auth_code($auth_code, $order);
                    if (PaymentLogic::hasError()) {
                        return $this->fail(PaymentLogic::getError(), $params);
                    }
                    if ($result['msg'] !== 'Success') {
                        return $this->success('用户支付中');
                    }
                    $result['create_time'] = $order['create_time'];
                    return $this->success('支付成功', ['out_trade_no'=>$result['out_trade_no'],'pay_type'=>PayEnum::ALIPAY_BARCODE,'transaction_id'=>$result['trade_no']]);
                default:
                    return $this->fail('支付方式错误');
            }
//            return $this->data(['order_id' => $order->id]);
        } else {
            return $this->fail(OrderLogic::getError());
        }
    }


    public function order_count()
    {
        $userId = $this->request->userId;
        $where = ['uid' => $userId, 'paid' => 0];
        $no_pay = StoreOrder::where($where)->count();
        $where['paid'] = 1;
        $where['status'] = 0;
        $waiting = StoreOrder::where($where)->count();
        $where['status'] = 1;
        $receiving = StoreOrder::where($where)->count();
        return $this->success('ok', ['no_pay' => $no_pay, 'waiting' => $waiting, 'receiving' => $receiving]);
    }

    #[
        ApiDoc\Title('订单支付'),
        ApiDoc\url('/api/order/order/pay'),
        ApiDoc\Method('POST'),
        ApiDoc\Param(name: "order_id", type: "int", require: true, desc: "订单id"),
        ApiDoc\Param(name: "address_id", type: "int", require: true, desc: "地址id"),
        ApiDoc\Param(name: "auth_code", type: "string", require: true, desc: "付款码"),
        ApiDoc\Param(name: "pay_type", type: "int", require: true, desc: "支付类型"),
        ApiDoc\NotHeaders(),
        ApiDoc\Header(name: "token", type: "string", require: true, desc: "token"),
        ApiDoc\ResponseSuccess("data", type: "array"),
    ]
    public function pay()
    {
        $order_id = (int)$this->request->post('order_id');
        $addressId = (int)$this->request->post('address_id');
        $pay_type = (int)$this->request->post('pay_type');
        $auth_code = $this->request->post('auth_code'); //微信支付条码
        $params = $this->request->post();
        $where = [
            'id' => $order_id,
            'uid' => $this->userId,
            'paid' => 0,
        ];
        $order = StoreOrder::where($where)->find();
        if (!$order) {
            return $this->fail('订单不存在或已支付');
        }

        switch ($pay_type) {
            case PayEnum::BALANCE_PAY:
                //余额支付
                PayNotifyLogic::handle('balancePay', $order['order_id']);
                return $this->success('余额支付成功');
            case PayEnum::CASH_PAY:
                //现金支付
                PayNotifyLogic::handle('cash_pay', $order['order_id']);
                return $this->success('现金支付成功');
                break;
            case PayEnum::WECHAT_PAY:
                //微信支付
                $redirectUrl = $params['redirect'] ?? '/pages/payment/payment';
                if ($addressId != $order['address_id']) {
                    $address = UserAddress::where(['address_id' => $addressId, 'uid' => Request()->userId])->find();
                    if ($address) {
                        $_order['real_name'] = $address['real_name'];
                        $_order['user_phone'] = $address['phone'];
                        $_order['user_address'] = $address['detail'];
                        $_order['address_id'] = $addressId;
                        StoreOrder::where(['id' => $order_id, 'uid' => Request()->userId])->update($_order);
                    }
                }
                $result = PaymentLogic::pay($pay_type, 'StoreOrder', $order, $this->userInfo['terminal'], $redirectUrl);
                if (PaymentLogic::hasError()) {
                    return $this->fail(PaymentLogic::getError());
                }
                return $this->success('', $result);
                break;
            case  PayEnum::WECHAT_PAY_BARCODE:
                //微信条码支付
                $result = PaymentLogic::codepay($auth_code, $order);
                if (PaymentLogic::hasError()) {
                    return $this->fail(PaymentLogic::getError(), $params);
                }
                if (isset($result['trade_state_desc']) && $result['trade_state_desc'] == '支付成功') {
                    PayNotifyLogic::handle('StoreOrder', $result['out_trade_no'], $result);
                } else {
                    Redis::send('send-code-pay', ['number' => $order['number']]);
                    return $this->success('用户支付中');
                }
                return $this->success('支付成功', ['out_trade_no'=>$result['out_trade_no'],'pay_type'=>PayEnum::WECHAT_PAY_BARCODE,'transaction_id'=>$result['transaction_id']]);
                break;
            case  PayEnum::ALIPAY_BARCODE:
                //支付宝条码支付
                $result = PaymentLogic::ali_auth_code($auth_code, $order);
                if (PaymentLogic::hasError()) {
                    return $this->fail(PaymentLogic::getError(), $params);
                }
                if ($result['msg'] !== 'Success') {
                    return $this->success('用户支付中');
                }
                return $this->success('支付成功', ['out_trade_no'=>$result['out_trade_no'],'pay_type'=>PayEnum::ALIPAY_BARCODE,'transaction_id'=>$result['trade_no']]);
                break;
            default:
                return $this->fail('支付方式错误');
        }
        return $this->fail('支付失败');
    }

    public function detail()
    {
        $order_id = (int)$this->request->get('order_id');
        $where = [
            'id' => $order_id,
            'uid' => $this->userId,
        ];
        $order = OrderLogic::detail($where);
        if ($order) {
            return $this->data($order);
        } else {
            return $this->fail('订单不存在');
        }
    }

    /**
     *  获取用户常用购买记录
     */
    public function frequently_purchase()
    {
        $params = $this->request->get();
        $res = OrderLogic::frequentlyPurchase($params);
        if (OrderLogic::hasError()) {
            return $this->fail(OrderLogic::getError());
        } else {
            return $this->data($res);
        }
    }

    /**
     * 取消订单
     */
    public function cancel_order()
    {
        $order_id = (int)$this->request->post('order_id');
        $value = (int)$this->request->post('value');
        $where = [
            'id' => $order_id,
            'uid' => $this->userId,
            'paid' => 0,
        ];
        $order = StoreOrder::where($where)->find();
        if ($order) {
            $data = ['data' => $value, 'delete_time' => time()];
            StoreOrder::where($where)->update($data);
            return $this->success('取消成功');
        }
        return $this->fail('取消失败');
    }

    /**
     * 确认收货
     */
    public function confirm_receipt()
    {
        $order_id = (int)$this->request->post('order_id');
        $where = [
            'id' => $order_id,
            'uid' => $this->userId,
            'paid' => 1,
            'status' => 1,
        ];
        $order = StoreOrder::where($where)->find();
        if ($order) {
            $data = ['status' => 2];
            StoreOrder::where($where)->update($data);
            return $this->success('确认成功');
        }
        return $this->fail('确认失败');
    }

    /**
     * 再次购买
     */
    public function purchase_again()
    {
        $order_id = (int)$this->request->get('order_id');

        $res = OrderLogic::purchaseAgain($order_id);
        if ($res == false) {
            return $this->fail('添加失败');
        } else {
            return $this->success('添加成功');
        }
    }

    #[
        ApiDoc\Title('核销'),
        ApiDoc\url('/api/order/order/writeoff_order'),
        ApiDoc\Method('POST'),
        ApiDoc\Param(name: "verify_code", type: "string", require: true, desc: "验证码"),
        ApiDoc\NotHeaders(),
        ApiDoc\Header(name: "token", type: "string", require: true, desc: "token"),
        ApiDoc\ResponseSuccess("data", type: "array"),
    ]
    public function writeoff_order()
    {
        $params = (new OrderValidate())->post()->goCheck('check');
        $res = OrderLogic::writeOff($params);
        if ($res) {
            return $this->success('核销成功');
        }
        return $this->fail('核销失败'.OrderLogic::getError());
    }


}