<?php

namespace app\adminapi\controller\v1\order;


use app\adminapi\controller\AuthController;
use app\adminapi\validates\order\StoreOrderValidate;
use Exception;
use app\models\system\{Express, SystemStore};
use crmeb\traits\CurdControllerTrait;
use FormBuilder\exception\FormBuilderException;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\response\Json;
use app\models\user\{UserBill, User};
use crmeb\repositories\OrderRepository;
use app\models\store\{StoreOrder as StoreOrderModel, StoreOrderStatus, StorePink};
use crmeb\services\{CacheService,
    ExpressService,
    MiniProgramService,
    SystemConfigService,
    WechatService,
    UtilService,
    FormBuilder as Form};
use think\facade\Route as Url;

class StoreOrder extends AuthController
{

    use CurdControllerTrait;

    protected function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->bindModel = StoreOrderModel::class;
    }

    /**
     * 获取订单类型数量
     * @return mixed
     * @throws Exception
     */
    public function chart()
    {
        $where = UtilService::getMore([
            ['data', ''],
        ], $this->request);
        $where['mer_id'] = $this->merId;
        return $this->success(StoreOrderModel::orderCount($where));
    }

    /**
     * 获取订单列表
     * @return mixed
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public function lst()
    {
        $where = UtilService::getMore([
            ['status', ''],
            ['real_name', ''],
            ['is_del', 0],
            ['data', ''],
            ['type', ''],
            ['pay_type', ''],
            ['order', ''],
            ['page', 1],
            ['limit', 10],
        ], $this->request);
        $where['mer_id'] = $this->merId;
        return $this->success(StoreOrderModel::getAdminOrderList($where));
    }

    /**
     * 核销码核销
     * @return mixed
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws Exception
     */
    public function write_order()
    {
        [$code, $confirm] = UtilService::getMore([
            ['code', ''],
            ['confirm', 0]
        ], $this->request, true);
        if (!$code) return $this->fail('Lack of write-off code');
        StoreOrderModel::beginTrans();
        $orderInfo = StoreOrderModel::merSet($this->merId)->where('verify_code', $code)->where('paid', 1)->field(['status', 'uid', 'order_id'])->where('refund_status', 0)->find();
        if (!$orderInfo) return $this->fail('Write off order does not exist');
        if ($orderInfo->status > 0) return $this->fail('Order written off');
        if ($orderInfo->combination_id && $orderInfo->pink_id) {
            $res = StorePink::where('id', $orderInfo->pink_id)->where('status', '<>', 2)->count();
            if ($res) return $this->fail('Failed to write off the group order');
        }
        if ($confirm == 0) {
            $orderInfo['nickname'] = User::where(['uid' => $orderInfo['uid']])->value('nickname');
            return $this->success($orderInfo->toArray());
        }
        $orderInfo->status = 2;
        if ($orderInfo->save()) {
            StoreOrderModel::commitTrans();
            return $this->success('Write off successfully');
        } else {
            StoreOrderModel::rollbackTrans();
            return $this->fail('Write off failure');
        }
    }

    /**
     * 修改支付金额等
     * @param $id
     * @return mixed|Json|void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function edit($id)
    {
        if (!$id) return $this->fail('Data does not exist!');
        $product = StoreOrderModel::merSet($this->merId)->where('id', $id)->find();
        if (!$product) return $this->fail('Data does not exist!');
        $f = [];
        $f[] = Form::input('order_id', '订单编号', $product->getData('order_id'))->disabled(1);
        $f[] = Form::number('total_price', '商品总价', $product->getData('total_price'))->min(0);
        $f[] = Form::number('total_postage', '原始邮费', $product->getData('total_postage'))->min(0);
        $f[] = Form::number('pay_price', '实际支付金额', $product->getData('pay_price'))->min(0);
        $f[] = Form::number('pay_postage', '实际支付邮费', $product->getData('pay_postage'));
        $f[] = Form::number('gain_integral', '赠送积分', $product->getData('gain_integral'));
        return $this->makePostForm('修改订单', $f, Url::buildUrl('/order/update/' . $id), 'PUT');
    }

    /**
     * 修改订单
     * @param $id
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public function update($id)
    {
        if (!$id) return $this->fail('Missing order ID');
        $product = StoreOrderModel::merSet($this->merId)->where('id', $id)->find();
        if (!$product) return $this->fail('Data does not exist!');
        $data = UtilService::postMore([
            ['order_id', ''],
            ['total_price', 0],
            ['total_postage', 0],
            ['pay_price', 0],
            ['pay_postage', 0],
            ['gain_integral', 0],
        ], $this->request);

        $this->validate($data, StoreOrderValidate::class);

        if ($data['total_price'] < 0) return $this->fail('Please enter the total price');
        if ($data['pay_price'] < 0) return $this->fail('Please enter the actual payment amount');

        StoreOrderModel::beginTrans();
        $data['order_id'] = StoreOrderModel::changeOrderId($data['order_id']);
        $res = StoreOrderModel::edit($data, $id);
        $res = $res && StoreOrderStatus::status($id, 'order_edit', '修改商品总价为：' . $data['total_price'] . ' 实际支付金额' . $data['pay_price']);
        if ($res) {
            event('StoreProductOrderEditAfter', [$data, $id]);
            StoreOrderModel::commitTrans();
            return $this->success('Modified success');
        } else {
            StoreOrderModel::rollbackTrans();
            return $this->fail('Modification failed');
        }
    }

    /**
     * 获取快递公司
     * @return mixed
     */
    public function express()
    {
        $list = Express::where('is_show', 1)->order('sort desc')->column('name', 'id');
        $data = [];
        foreach ($list as $key => $value) {
            $data[] = ['id' => $key, 'value' => $value];
        }
        return $this->success($data);
    }

    /**
     * 批量删除用户已经删除的订单
     * @return mixed
     * @throws Exception
     */
    public function del_orders()
    {
        [$ids] = UtilService::postMore([
            ['ids', []],
        ], $this->request, true);
        if (!count($ids)) return $this->fail('请选择需要删除的订单');
        if (StoreOrderModel::merSet($this->merId)->where('is_del', 0)->whereIn('id', $ids)->count())
            return $this->fail('您选择的的订单存在用户未删除的订单');
        if (StoreOrderModel::merSet($this->merId)->whereIn('id', $ids)->update(['is_system_del' => 1]))
            return $this->success('SUCCESS');
        else
            return $this->fail('ERROR');
    }

    //批量设置标签
    public function setLevel()
    {
        $data = UtilService::postMore([
            ['ids', []],
            ['level', '']
        ], $this->request);
        if (!count($data['ids'])) return $this->fail('请选择需要设置的订单');
        if (StoreOrderModel::merSet($this->merId)->whereIn('id', $data['ids'])->update(['level' => $data['level']]))
            return $this->success('SUCCESS');
        else
            return $this->fail('ERROR');
    }

    /**
     * 删除订单
     * @param $id
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function del($id)
    {
        if (!$id || !($orderInfo = StoreOrderModel::merSet($this->merId)->where('id', $id)->find()))
            return $this->fail('订单不存在');
        if (!$orderInfo->is_del)
            return $this->fail('订单用户未删除无法删除');
        $orderInfo->is_system_del = 1;
        if ($orderInfo->save())
            return $this->success('SUCCESS');
        else
            return $this->fail('ERROR');
    }

    /**
     * 订单发送货
     * @param int $id 订单id
     * @return mixed
     * @throws Exception
     */
    public function update_delivery($id)
    {
        if (!$id) return $this->fail('订单不存在');
        $product = StoreOrderModel::merSet($this->merId)->where('id', $id)->find();
        if (!$product) return $this->fail('订单不存在');
        $data = UtilService::postMore([
            ['type', 1],
            ['delivery_name', ''],
            ['delivery_id', ''],
            ['sh_delivery_name', ''],
            ['sh_delivery_id', ''],
        ], $this->request);
        StoreOrderModel::beginTrans();
        $type = (int)$data['type'];
        unset($data['type']);
        switch ($type) {
            case 1:
                //发货
                $data['delivery_type'] = 'express';
                if (!$data['delivery_name']) return $this->fail('请选择快递公司');
                if (!$data['delivery_id']) return $this->fail('请输入快递单号');
                $data['status'] = 1;
                StoreOrderModel::edit($data, $id);
                event('StoreProductOrderDeliveryGoodsAfter', [$data, $id]);
                StoreOrderStatus::setStatus($id, 'delivery_goods', '已发货 快递公司：' . $data['delivery_name'] . ' 快递单号：' . $data['delivery_id']);
                break;
            case 2:
                $data['delivery_type'] = 'send';
                $data['delivery_name'] = $data['sh_delivery_name'];
                $data['delivery_id'] = $data['sh_delivery_id'];
                unset($data['sh_delivery_name'], $data['sh_delivery_id']);
                if (!$data['delivery_name']) return $this->fail('请输入送货人姓名');
                if (!$data['delivery_id']) return $this->fail('请输入送货人电话号码');
                if (!preg_match("/^1[3456789]{1}\d{9}$/", $data['delivery_id'])) return $this->fail('请输入正确的送货人电话号码');
                $data['status'] = 1;
                StoreOrderModel::edit($data, $id);
                event('StoreProductOrderDeliveryAfter', [$data, $id]);
                StoreOrderStatus::setStatus($id, 'delivery', '已配送 发货人：' . $data['delivery_name'] . ' 发货人电话：' . $data['delivery_id']);
                break;
            case 3:
                $data['delivery_type'] = 'fictitious';
                $data['status'] = 1;
                unset($data['sh_delivery_name'], $data['sh_delivery_id'], $data['delivery_name'], $data['delivery_id']);
                StoreOrderModel::edit($data, $id);
                event('StoreProductOrderDeliveryAfter', [$data, $id]);
                StoreOrderStatus::setStatus($id, 'delivery_fictitious', '已虚拟发货');
                break;
            default:
                return $this->fail('暂时不支持其他发货类型');
                break;
        }
        //短信发送
        event('ShortMssageSend', [StoreOrderModel::where('id', $id)->value('order_id'), 'Deliver']);
        StoreOrderModel::commitTrans();
        return $this->success('SUCCESS');
    }


    /**
     * 确认收货
     * @param int $id 订单id
     * @return mixed
     * @throws Exception
     */
    public function take_delivery($id)
    {
        if (!$id) return $this->fail('缺少参数');
        $order = StoreOrderModel::merSet($this->merId)->where('id', $id)->find();
        if (!$order) return $this->fail('订单不存在');
        if ($order['status'] == 2)
            return $this->fail('不能重复收货!');
        if ($order['paid'] == 1 && $order['status'] == 1)
            $data['status'] = 2;
        else if ($order['pay_type'] == 'offline')
            $data['status'] = 2;
        else
            return $this->fail('请先发货或者送货!');
        StoreOrderModel::beginTrans();
        if (!StoreOrderModel::edit($data, $id)) {
            StoreOrderModel::rollbackTrans();
            return $this->fail('收货失败,请稍候再试!');
        } else {
            OrderRepository::storeProductOrderTakeDeliveryAdmin($order);
            StoreOrderStatus::setStatus($id, 'take_delivery', '已收货');
            StoreOrderModel::commitTrans();
            //发送短信
            event('ShortMssageSend', [$order['order_id'], 'Receiving']);
            return $this->success('收货成功');
        }
    }

    /**
     * 退款表单生成
     * @param int $id 订单id
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws FormBuilderException
     * @throws ModelNotFoundException
     */
    public function refund($id)
    {
        if (!$id) return $this->fail('Data does not exist!');
        $order = StoreOrderModel::merSet($this->merId)->where('id', $id)->find();
        if (!$order) return $this->fail('未查到订单');
        if (!$order['paid']) return $this->fail('未支付无法退款');
        if ($order['pay_price'] <= $order['refund_price']) return $this->fail('订单已退款');
        $f[] = Form::input('order_id', '退款单号', $order->getData('order_id'))->disabled(1);
        $f[] = Form::number('refund_price', '退款金额', $order->getData('pay_price'))->precision(2)->min(0.01)->required('请输入退款金额');
        $f[] = Form::radio('type', '状态', 1)->options([['label' => '直接退款', 'value' => 1], ['label' => '退款后,返回原状态', 'value' => 2]]);
        return $this->makePostForm('退款处理', $f, Url::buildUrl('/order/refund/' . $id), 'PUT');
    }

    /**
     * 订单退款
     * @param int $id 订单id
     * @return mixed
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws Exception
     */
    public function update_refund($id)
    {
        $data = UtilService::postMore([['refund_price', 0], ['type', 1]], $this->request);
        if (!$id) return $this->fail('Data does not exist!');
        $order = StoreOrderModel::merSet($this->merId)->where('id', $id)->find();
        if (!$order) return $this->fail('未查到订单');
        if ($order['pay_price'] == $order['refund_price']) return $this->fail('已退完支付金额!不能再退款了');
        if (!$data['refund_price']) return $this->fail('请输入退款金额');
        $refund_price = $data['refund_price'];
        $data['refund_price'] = bcadd($data['refund_price'], $order['refund_price'], 2);
        $bj = bccomp((float)$order['pay_price'], (float)$data['refund_price'], 2);
        if ($bj < 0) return $this->fail('退款金额大于支付金额，请修改退款金额');

        if ($data['type'] == 1)
            $data['refund_status'] = 2;
        else if ($data['type'] == 2)
            $data['refund_status'] = 0;
        $type = $data['type'];
        unset($data['type']);
        $refund_data['pay_price'] = $order['pay_price'];
        $refund_data['refund_price'] = $refund_price;
        //退款处理
        StoreOrderModel::beginTrans();
        $res = true;
        switch ($order['pay_type']) {
            case 'weixin':
                if ($order['is_channel'] == 1)
                    MiniProgramService::payOrderRefund($order['order_id'], $refund_data, $this->merId);//小程序
                else
                    WechatService::payOrderRefund($order['order_id'], $refund_data);//公众号
                break;
            case 'yue':
                $usermoney = User::where('uid', $order['uid'])->value('now_money');
                $res = User::bcInc($order['uid'], 'now_money', $refund_price, 'uid') &&
                    UserBill::income(
                        '商品退款',
                        $order['uid'],
                        'now_money',
                        'pay_product_refund',
                        $refund_price, $order['id'],
                        bcadd($usermoney, $refund_price, 2),
                        '订单退款到余额' . floatval($refund_price) . '元',
                        1,
                        $this->merId
                    );
                OrderRepository::storeOrderYueRefund($order, $refund_data);
                break;
        }
        if (!$res) return $this->fail('余额退款失败');
        //修改订单退款状态
        $res = true;
        if (StoreOrderModel::edit($data, $id)) {
            $data['type'] = $type;
            if ($data['type'] == 1) $res = StorePink::setRefundPink($id);
            if (!$res) return $this->fail('拼团修改失败');
            OrderRepository::storeProductOrderRefundY($data, $id);
            StoreOrderStatus::setStatus($id, 'refund_price', '退款给用户' . $refund_price . '元');
            //退佣金
            $brokerage_list = UserBill::where('category', 'now_money')
                ->where('type', 'brokerage')
                ->where('link_id', $id)
                ->where('pm', 1)
                ->select();

            if ($brokerage_list) {
                $brokerage_list = $brokerage_list->toArray();
                foreach ($brokerage_list as $item) {
                    $usermoney = User::where('uid', $item['uid'])->value('brokerage_price');
                    if ($item['number'] > $usermoney)
                        $item['number'] = $usermoney;
                    User::bcDec($item['uid'], 'brokerage_price', $item['number'], 'uid');
                    UserBill::expend('退款退佣金', $item['uid'], 'now_money', 'brokerage', $item['number'], $id, bcsub($usermoney, $item['number'], 2), '订单退款扣除佣金' . floatval($item['number']) . '元', 1, $this->merId);
                }
            }
            //退款扣除用户积分
            $bill_integral = UserBill::where('category', 'integral')
                ->where('type', 'gain')
                ->where('link_id', $id)
                ->where('pm', 1)
                ->find();
            if ($bill_integral) {
                $bill_integral = $bill_integral->toArray();
                //用户积分
                $user_integral = User::where('uid', $bill_integral['uid'])->value('integral');
                if ($bill_integral['number'] > $user_integral)
                    $bill_integral['number'] = $user_integral;
                User::bcDec($bill_integral['uid'], 'integral', $bill_integral['number'], 'uid');
                UserBill::expend('退款扣除积分', $bill_integral['uid'], 'integral', 'gain', $bill_integral['number'], $id, bcsub($user_integral, $bill_integral['number'], 2), '订单退款扣除积分' . floatval($bill_integral['number']) . '积分', 1, $this->merId);
            }
            StoreOrderModel::commitTrans();
            return $this->success('退款成功');
        } else {
            StoreOrderModel::rollbackTrans();
            StoreOrderStatus::setStatus($id, 'refund_price', '退款给用户' . $refund_price . '元失败');
            return $this->fail('退款失败');
        }
    }

    /**
     * 订单详情
     * @param int $id 订单id
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function order_info($id)
    {
        if (!$id || !($orderInfo = StoreOrderModel::merSet($this->merId)->where('id', $id)->find()))
            return $this->fail('订单不存在');
        $userInfo = User::merSet($this->merId)->where('uid', $orderInfo['uid'])->find();
        if (!$userInfo) return $this->fail('用户信息不存在');
        $userInfo = $userInfo->hidden(['pwd', 'add_ip', 'last_ip', 'login_type']);
        $userInfo['spread_name'] = '';
        if ($userInfo['spread_uid'])
            $userInfo['spread_name'] = User::where('uid', $userInfo['spread_uid'])->value('nickname');
        $orderInfo = StoreOrderModel::tidyOrder($orderInfo->toArray(), false, false, $this->merId);
        if ($orderInfo['store_id'] && $orderInfo['shipping_type'] == 2)
            $orderInfo['_store_name'] = SystemStore::where('id', $orderInfo['store_id'])->value('name');
        else
            $orderInfo['_store_name'] = '';
        $userInfo = $userInfo->toArray();
        return $this->success(compact('orderInfo', 'userInfo'));
    }

    /**
     * 查询物流信息
     * @param int $id 订单id
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function get_express($id)
    {
        if (!$id || !($orderInfo = StoreOrderModel::merSet($this->merId)->where('id', $id)->find()))
            return $this->fail('订单不存在');
        if ($orderInfo['delivery_type'] != 'express' || !$orderInfo['delivery_id'])
            return $this->fail('该订单不存在快递单号');

        $cacheName = $orderInfo['order_id'] . $orderInfo['delivery_id'];
        if (!$result = CacheService::get($cacheName, null)) {
            $result = ExpressService::query($orderInfo['delivery_id']);
            if (is_array($result) &&
                isset($result['result']) &&
                isset($result['result']['deliverystatus']) &&
                $result['result']['deliverystatus'] >= 3)
                $cacheTime = 0;
            else
                $cacheTime = 1800;
            CacheService::set($cacheName, $result, $cacheTime);
        }
        $data['delivery_name'] = $orderInfo['delivery_name'];
        $data['delivery_id'] = $orderInfo['delivery_id'];
        $data['result'] = $result['result']['list'] ?? [];
        return $this->success($data);
    }


    /**
     * 获取修改配送信息表单结构
     * @param int $id 订单id
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function distribution($id)
    {
        if (!$id || !($orderInfo = StoreOrderModel::merSet($this->merId)->where('id', $id)->find()))
            return $this->fail('订单不存在');

        $f[] = Form::input('order_id', '订单号', $orderInfo->getData('order_id'))->disabled(1);
        switch ($orderInfo['delivery_type']) {
            case 'send':
                $f[] = Form::input('delivery_name', '送货人姓名', $orderInfo->getData('delivery_name'))->required('请输入送货人姓名');
                $f[] = Form::input('delivery_id', '送货人电话', $orderInfo->getData('delivery_id'))->required('请输入送货人电话');
                break;
            case 'express':
                $f[] = Form::select('delivery_name', '快递公司', $orderInfo->getData('delivery_name'))->setOptions(function () {
                    $list = Express::where('is_show', 1)->column('name', 'id');
                    $menus = [];
                    foreach ($list as $k => $v) {
                        $menus[] = ['value' => $v, 'label' => $v];
                    }
                    return $menus;
                })->required('请选择快递公司');
                $f[] = Form::input('delivery_id', '快递单号', $orderInfo->getData('delivery_id'))->required('请填写快递单号');
                break;
        }
        return $this->makePostForm('配送信息', $f, Url::buildUrl('/order/distribution/' . $id), 'PUT');
    }

    /**
     * 修改配送信息
     * @param int $id 订单id
     * @return mixed
     * @throws Exception
     */
    public function update_distribution($id)
    {
        $data = UtilService::postMore([['delivery_name', ''], ['delivery_id', '']], $this->request);
        if (!$id) return $this->fail('Data does not exist!');
        $order = StoreOrderModel::merSet($this->merId)->where('id', $id)->find();
        if (!$order) return $this->fail('数据不存在！');
        switch ($order['delivery_type']) {
            case 'send':
                if (!$data['delivery_name']) return $this->fail('请输入送货人姓名');
                if (!$data['delivery_id']) return $this->fail('请输入送货人电话号码');
                if (!preg_match("/^1[3456789]{1}\d{9}$/", $data['delivery_id'])) return $this->fail('请输入正确的送货人电话号码');
                break;
            case 'express':
                if (!$data['delivery_name']) return $this->fail('请选择快递公司');
                if (!$data['delivery_id']) return $this->fail('请输入快递单号');
                break;
            default:
                return $this->fail('未发货，请先发货再修改配送信息');
                break;
        }
        StoreOrderModel::edit($data, $id);
        event('StoreProductOrderDistributionAfter', [$data, $id]);
        StoreOrderStatus::setStatus($id, 'distribution', '修改发货信息为' . $data['delivery_name'] . '号' . $data['delivery_id']);
        return $this->success('Modified success');
    }

    /**
     * 不退款表单结构
     * @param $id
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function no_refund($id)
    {
        if (!$id) return $this->fail('Data does not exist!');
        $order = StoreOrderModel::merSet($this->merId)->where('id', $id)->find();
        if (!$order) return $this->fail('Data does not exist!');
        $f[] = Form::input('order_id', '不退款单号', $order->getData('order_id'))->disabled(1);
        $f[] = Form::input('refund_reason', '不退款原因')->type('textarea')->required('请填写不退款原因');
        return $this->makePostForm('不退款原因', $f, Url::buildUrl('order/no_refund/' . $id)->suffix(false), 'PUT');
    }

    /**
     * 订单不退款
     * @param $id
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public function update_un_refund($id)
    {
        if (!$id || !($orderInfo = StoreOrderModel::merSet($this->merId)->where('id', $id)->find()))
            return $this->fail('订单不存在');
        [$refund_reason] = UtilService::postMore([['refund_reason', '']], $this->request, true);
        if (!$refund_reason) return $this->fail('请输入不退款原因');
        StoreOrderModel::edit(['refund_reason' => $refund_reason, 'refund_status' => 0], $id);
        event('StoreProductOrderRefundNAfter', [$refund_reason, $id]);
        StoreOrderStatus::setStatus($id, 'refund_n', '不退款原因:' . $refund_reason);
        return $this->success('Modified success');
    }

    /**
     * 线下支付
     * @param int $id 订单id
     * @return mixed
     */
    public function pay_offline($id)
    {
        if (!$id) return $this->fail('缺少参数');
        $res = StoreOrderModel::updateOffline($id, $this->merId);
        if ($res) {
            event('StoreProductOrderOffline', [$id]);
            StoreOrderStatus::setStatus($id, 'offline', '线下付款');
            return $this->success('Modified success');
        } else {
            return $this->fail(StoreOrderModel::getErrorInfo('Modification failed'));
        }
    }

    /**
     * 退积分表单获取
     * @param $id
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function refund_integral($id)
    {
        if (!$id || !($orderInfo = StoreOrderModel::merSet($this->merId)->where('id', $id)->find()))
            return $this->fail('订单不存在');
        if ($orderInfo->use_integral < 0 || $orderInfo->use_integral == $orderInfo->back_integral)
            return $this->fail('积分已退或者积分为零无法再退');
        if (!$orderInfo->paid)
            return $this->fail('未支付无法退积分');
        $f[] = Form::input('order_id', '退款单号', $orderInfo->getData('order_id'))->disabled(1);
        $f[] = Form::number('use_integral', '使用的积分', (float)$orderInfo->getData('use_integral'))->min(0)->disabled(1);
        $f[] = Form::number('use_integrals', '已退积分', (float)$orderInfo->getData('back_integral'))->min(0)->disabled(1);
        $f[] = Form::number('back_integral', '可退积分', (float)bcsub($orderInfo->getData('use_integral'), $orderInfo->getData('use_integral')))->min(0)->required('请输入可退积分');
        return $this->makePostForm('退积分', $f, Url::buildUrl('/order/refund_integral/' . $id), 'PUT');
    }

    /**
     * 退积分保存
     * @param $id
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public function update_refund_integral($id)
    {
        [$back_integral] = UtilService::postMore([['back_integral', 0]], $this->request, true);
        if (!$id || !($orderInfo = StoreOrderModel::merSet($this->merId)->where('id', $id)->find()))
            return $this->fail('订单不存在');
        if ($back_integral <= 0)
            return $this->fail('请输入积分');
        if ($orderInfo['use_integral'] == $orderInfo['back_integral'])
            return $this->fail('已退完积分!不能再积分了');

        $data['back_integral'] = bcadd($back_integral, $orderInfo['back_integral'], 2);
        $bj = bccomp((float)$orderInfo['use_integral'], (float)$data['back_integral'], 2);
        if ($bj < 0) return $this->fail('退积分大于支付积分，请修改退积分');
        //积分退款处理
        StoreOrderModel::beginTrans();
        $integral = User::where('uid', $orderInfo['uid'])->value('integral');
        $res1 = User::bcInc($orderInfo['uid'], 'integral', $back_integral, 'uid');
        $res2 = UserBill::income('商品退积分', $orderInfo['uid'], 'integral', 'pay_product_integral_back', $back_integral, $orderInfo['id'], bcadd($integral, $back_integral, 2), '订单退积分' . floatval($back_integral) . '积分到用户积分', 1, $this->merId);
        event('StoreOrderIntegralBack', [$orderInfo, $back_integral]);
        OrderRepository::storeOrderIntegralBack($orderInfo, $back_integral);
        if ($res1 && $res2) {
            StoreOrderModel::edit($data, $id);
            StoreOrderStatus::setStatus($id, 'integral_back', '商品退积分：' . $data['back_integral']);
            StoreOrderModel::commitTrans();
            return $this->success('退积分成功');
        } else {
            StoreOrderModel::rollbackTrans();
            return $this->fail('退积分失败');
        }
    }

    /**
     * 修改备注
     * @param $id
     * @return mixed
     * @throws Exception
     */
    public function remark($id)
    {
        $data = UtilService::postMore([['remark', '']], $this->request);
        if (!$data['remark'])
            return $this->fail('请输入要备注的内容');
        if (!$id)
            return $this->fail('缺少参数');
        if (!StoreOrderModel::merSet($this->merId)->where('id', $id)->find()) {
            return $this->fail('找不到订单');
        }
        $res = $this->model_save($id, $data);
        if ($res) {
            return $this->success('备注成功');
        } else
            return $this->fail($this->getErrorInfo());
    }

    /**
     * 获取订单状态列表并分页
     * @param $id
     * @return mixed
     * @throws Exception
     */
    public function status($id)
    {
        if (!$id) return $this->fail('缺少参数');
        if (!StoreOrderModel::merSet($this->merId)->where('id', $id)->find()) {
            return $this->fail('找不到订单');
        }
        [$page, $limit] = UtilService::getMore([['page', 1], ['limit', 10]], $this->request, true);
        return $this->success(StoreOrderStatus::getOrderList($id, $page, $limit));
    }

    /**
     * 获取商品下的门店
     */

}