<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016～2022 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------

namespace app\merchant\controller\order;

use Api\Express;
use app\merchant\controller\AuthController;
use service\AlipayTradeWapService;
use service\FormBuilder as Form;
use app\merchant\model\order\StoreOrderStatus;
use app\merchant\model\order\StoreOrder as StoreOrderModel;
use service\SystemConfigService;
use app\wap\model\store\StorePink;
use app\wap\model\special\SpecialBuy;
use app\merchant\model\user\User;
use app\admin\model\user\UserBill;
use basic\ModelBasic;
use behavior\wap\StoreProductBehavior;
use behavior\wechat\PaymentBehavior;
use EasyWeChat\Core\Exception;
use service\CacheService;
use service\HookService;
use service\JsonService as Json;
use app\admin\model\merchant\MerchantFlowingWater;
use think\Db;
use think\Request;
use think\Url;


/**
 * 订单管理控制器 同一个订单表放在一个控制器
 * Class StoreOrder
 */
class StoreOrder extends AuthController
{
    /**课程订单
     * @return mixed
     */
    public function index()
    {
        $mer_id = $this->merchantId;
        $this->assign([
            'year' => getMonth('y'),
            'real_name' => $this->request->get('real_name', ''),
            'orderCount' => StoreOrderModel::orderCount(0, $mer_id),
        ]);
        return $this->fetch();
    }

    /**商品订单
     * @return mixed
     */
    public function productOrder()
    {
        $mer_id = $this->merchantId;
        $this->assign([
            'year' => getMonth('y'),
            'real_name' => $this->request->get('real_name', ''),
            'gold_name' => SystemConfigService::get('gold_name'),
            'orderCount' => StoreOrderModel::orderCount(2, $mer_id),
        ]);
        return $this->fetch('product_order');
    }

    /**
     * 获取头部订单金额等信息
     * return json
     *
     */
    public function getBadge()
    {
        $where = parent::postMore([
            ['status', ''],
            ['real_name', ''],
            ['is_del', 0],
            ['data', ''],
            ['type', ''],
            ['types', 0],
            ['order', '']
        ]);
        $where['mer_id'] = $this->merchantId;
        return Json::successful(StoreOrderModel::getBadge($where));
    }

    /**
     * 获取订单列表
     * return json
     */
    public function order_list()
    {
        $where = parent::getMore([
            ['status', ''],
            ['real_name', $this->request->param('real_name', '')],
            ['data', ''],
            ['type', ''],
            ['types', $this->request->param('types', 0)],
            ['order', ''],
            ['spread_type', ''],
            ['page', 1],
            ['limit', 20],
            ['excel', 0]
        ]);
        $where['mer_id'] = $this->merchantId;
        return Json::successlayui(StoreOrderModel::OrderList($where));
    }

    /**
     * 修改支付金额等
     * @param $id
     * @return mixed|\think\response\Json|void
     */
    public function edit($id)
    {
        if (!$id) return $this->failed('数据不存在');
        $product = StoreOrderModel::get($id);
        if (!$product) return Json::fail('数据不存在!');
        $f = array();
        $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'));
        $form = Form::make_post_form('修改订单', $f, Url::build('update', array('id' => $id)), 4);
        $this->assign(compact('form'));
        return $this->fetch('public/form-builder');

    }

    /** 修改订单提交更新
     * @param Request $request
     * @param $id
     */
    public function update(Request $request, $id)
    {
        $data = parent::postMore([
            'order_id',
            'total_price',
            'total_postage',
            'pay_price',
            'pay_postage',
        ], $request);
        if ($data['total_price'] <= 0) return Json::fail('请输入商品总价');
        if ($data['pay_price'] <= 0) return Json::fail('请输入实际支付金额');
        $data['order_id'] = StoreOrderModel::changeOrderId($data['order_id']);
        StoreOrderModel::edit($data, $id);
        HookService::afterListen('store_product_order_edit', $data, $id, false, StoreProductBehavior::class);
        StoreOrderStatus::setStatus($id, 'order_edit', '修改商品总价为：' . $data['total_price'] . ' 实际支付金额' . $data['pay_price']);
        return Json::successful('修改成功!');
    }

    /**
     * 发货
     * @param $id
     *  express
     */
    public function deliver_goods($id)
    {
        if (!$id) return $this->failed('数据不存在');
        $product = StoreOrderModel::get($id);
        if (!$product) return Json::fail('数据不存在!');
        if ($product['paid'] == 1 && $product['status'] == 0) {
            $f = array();
            $f[] = Form::select('delivery_name', '快递公司')->setOptions(function () {
                $list = db('express')->where('is_show', 1)->order('sort DESC')->column('id,name');
                $menus = [];
                foreach ($list as $k => $v) {
                    $menus[] = ['value' => $v, 'label' => $v];
                }
                return $menus;
            })->filterable(1);
            $f[] = Form::input('delivery_id', '快递单号')->number(1);
            $form = Form::make_post_form('修改订单', $f, Url::build('updateDeliveryGoods', array('id' => $id)), 4);
            $this->assign(compact('form'));
            return $this->fetch('public/form-builder');
        } else return Json::fail('数据不存在!');
    }

    /**发货保存
     * @param Request $request
     * @param $id
     */
    public function updateDeliveryGoods(Request $request, $id)
    {
        $data = parent::postMore([
            'delivery_name',
            'delivery_id',
        ], $request);
        $data['delivery_type'] = 'express';
        if (!$data['delivery_name']) return Json::fail('请选择快递公司');
        if (!$data['delivery_id']) return Json::fail('请输入快递单号');
        $data['status'] = 1;
        StoreOrderModel::edit($data, $id);
        HookService::afterListen('store_product_order_delivery_goods', $data, $id, false, StoreProductBehavior::class);
        StoreOrderStatus::setStatus($id, 'delivery_goods', '已发货 快递公司：' . $data['delivery_name'] . ' 快递单号：' . $data['delivery_id']);
        return Json::successful('修改成功!');
    }

    /**
     * 修改状态为已收货
     * @param $id
     * @return \think\response\Json|void
     */
    public function take_delivery($id)
    {
        if (!$id) return $this->failed('数据不存在');
        $product = StoreOrderModel::get($id);
        if (!$product) return Json::fail('数据不存在!');
        if ($product['status'] == 2) return Json::fail('不能重复收货!');
        if ($product['paid'] == 1 && $product['status'] == 1) $data['status'] = 2;
        else return Json::fail('请先发货或者送货!');
        if (!StoreOrderModel::edit($data, $id)) {
            return Json::fail(StoreOrderModel::getErrorInfo('收货失败,请稍候再试!'));
        } else {
            try {
                HookService::listen('store_product_order_take_delivery', $product, $id, false, StoreProductBehavior::class);
            } catch (Exception $e) {
                return Json::fail($e->getMessage());
            }
            StoreOrderStatus::setStatus($id, 'take_delivery', '已收货');
            return Json::successful('收货成功!');
        }
    }

    /**
     * 修改退款状态
     * @param $id
     * @return \think\response\Json|void
     */
    public function refund_y($id)
    {
        if (!$id) return $this->failed('数据不存在');
        $product = StoreOrderModel::get($id);
        if (!$product) return Json::fail('数据不存在!');
        if ($product['paid'] == 1) {
            $f = array();
            $f[] = Form::input('order_id', '退款单号', $product->getData('order_id'))->disabled(1);
            if ($product['type'] == 2) {
                $f[] = Form::number('refund_price', '退款金额', $product->getData('pay_price'))->precision(2)->disabled(1);
            } else {
                $f[] = Form::number('refund_price', '退款金额', $product->getData('pay_price'))->precision(2)->min(0.01);
            }
            $f[] = Form::radio('type', '状态', 1)->options([['label' => '直接退款', 'value' => 1]]);
            $form = Form::make_post_form('退款处理', $f, Url::build('updateRefundY', array('id' => $id)), 4);
            $this->assign(compact('form'));
            return $this->fetch('public/form-builder');
        } else return Json::fail('数据不存在!');
    }

    /**退款处理
     * @param Request $request
     * @param $id
     */
    public function updateRefundY(Request $request, $id)
    {
        $data = parent::postMore([
            'refund_price',
            ['type', 1],
        ], $request);
        if (!$id) return $this->failed('数据不存在');
        $product = StoreOrderModel::get($id);
        if (!$product) return Json::fail('数据不存在!');
        if ($product['pay_price'] == $product['refund_price']) return Json::fail('已退完支付金额!不能再退款了');
        if (!$data['refund_price']) return Json::fail('请输入退款金额');
        $refund_price = $data['refund_price'];
        $data['refund_price'] = bcadd($data['refund_price'], $product['refund_price'], 2);
        $bj = bccomp((float)$product['pay_price'], (float)$data['refund_price'], 2);
        if ($bj < 0) return Json::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'] = $product['pay_price'];
        $refund_data['refund_price'] = $refund_price;
        if ($product['pay_type'] == 'weixin') {
            try {
                HookService::listen('wechat_pay_order_refund', $product['order_id'], $refund_data, true, PaymentBehavior::class);
            } catch (\Exception $e) {
                return Json::fail($e->getMessage());
            }
        } else if ($product['pay_type'] == 'yue') {
            ModelBasic::beginTrans();
            $res = User::bcInc($product['uid'], 'now_money', $refund_price, 'uid');
            ModelBasic::checkTrans($res);
            if (!$res) return Json::fail('余额退款失败!');
        } else if ($product['pay_type'] == 'zhifubao') {
            if ($product['type'] == 0 && $product['combination_id'] > 0) {
                $mask = '拼团失败退款';
            } elseif ($product['type'] == 0 && $product['combination_id'] == 0) {
                $mask = '专题退款';
            } elseif ($product['type'] == 2) {
                $mask = '商品退款';
            }
            $res = AlipayTradeWapService::init()->AliPayRefund($product['order_id'], $product['trade_no'], $refund_price, $mask, 'refund');
            if (empty($res) || $res != 10000) {
                return Json::fail('支付宝退款失败!');
            }
        }
        $data['refund_reason_time'] = time();
        $resEdit = StoreOrderModel::edit($data, $id);
        if ($resEdit) {
            $data['type'] = $type;
            if ($data['type'] == 1 && $product['type'] == 0) {
                StorePink::setRefundPink($id);
                SpecialBuy::where('order_id', $product['order_id'])->delete();
            }
            if ($product['type'] == 0 && $product['combination_id'] > 0) {
                $title = '专题拼团退款';
                MerchantFlowingWater::orderRefund($id, $product['mer_id'], 0);
            } elseif ($product['type'] == 0 && $product['combination_id'] == 0) {
                $title = '专题退款';
                MerchantFlowingWater::orderRefund($id, $product['mer_id'], 0);
            } elseif ($product['type'] == 1) {
                $title = '会员退款';
            } elseif ($product['type'] == 2) {
                $title = '商品退款';
                MerchantFlowingWater::orderRefund($id, $product['mer_id'], 2);
            }
            $pay_type = $product['pay_type'] == 'yue' ? 'now_money' : $product['pay_type'];
            if ($product['pay_type'] == 'yue') {
                $balance = User::where(['uid' => $product['uid']])->value('now_money');
            } else {
                $balance = 0;
            }
            UserBill::income($title, $product['uid'], $pay_type, 'pay_product_refund', $refund_price, $product['id'], $balance, '订单退款' . floatval($refund_price) . '元');
            HookService::afterListen('store_product_order_refund_y', $data, $id, false, StoreProductBehavior::class);
            StoreOrderStatus::setStatus($id, 'refund_price', '退款给用户' . $refund_price . '元');
            return Json::successful('退款成功!');
        } else {
            StoreOrderStatus::setStatus($id, 'refund_price', '退款给用户' . $refund_price . '元失败');
            return Json::successful('退款失败!');
        }
    }

    /**订单详情
     * @param string $oid
     * @return mixed|void
     * @throws \think\exception\DbException
     */
    public function order_info($oid = '')
    {
        if (!$oid || !($orderInfo = StoreOrderModel::get($oid)))
            return $this->failed('订单不存在!');
        $userInfo = User::getAllUserinfo($orderInfo['uid']);
        if ($userInfo['spread_uid']) {
            $spread = User::where('uid', $userInfo['spread_uid'])->value('nickname');
        } else {
            $spread = '';
        }
        $gold_name = SystemConfigService::get('gold_name');
        $this->assign(compact('orderInfo', 'userInfo', 'spread', 'gold_name'));
        return $this->fetch();
    }

    /**退款原因
     * @param string $oid
     * @return mixed|void
     * @throws \think\exception\DbException
     */
    public function reason_refund($oid = '')
    {
        if (!$oid || !($orderInfo = StoreOrderModel::get($oid)))
            return $this->failed('订单不存在!');
        if (!is_null(json_decode($orderInfo['refund_reason_wap_img']))) {
            $orderInfo['refund_reason_wap_img'] = json_decode($orderInfo['refund_reason_wap_img']);
        }
        $this->assign(compact('orderInfo'));
        return $this->fetch();
    }

    public function express($oid = '')
    {
        if (!$oid || !($order = StoreOrderModel::get($oid)))
            return $this->failed('订单不存在!');
        if ($order['delivery_type'] != 'express' || !$order['delivery_id']) return $this->failed('该订单不存在快递单号!');
        $cacheName = $order['order_id'] . $order['delivery_id'];
        $result = CacheService::get($cacheName, null);
        if ($result === null) {
            $result = Express::query($order['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);
        }
        $this->assign([
            'order' => $order,
            'express' => $result
        ]);
        return $this->fetch();
    }

    /**
     * 修改配送信息
     * @param $id
     * @return mixed|\think\response\Json|void
     */
    public function distribution($id)
    {
        if (!$id) return $this->failed('数据不存在');
        $product = StoreOrderModel::get($id);
        if (!$product) return Json::fail('数据不存在!');
        $f = array();
        $f[] = Form::input('order_id', '退款单号', $product->getData('order_id'))->disabled(1);
        if ($product['delivery_type'] == 'send') {
            $f[] = Form::input('delivery_name', '送货人姓名', $product->getData('delivery_name'));
            $f[] = Form::input('delivery_id', '送货人电话', $product->getData('delivery_id'));
        } else if ($product['delivery_type'] == 'express') {
            $f[] = Form::select('delivery_name', '快递公司', $product->getData('delivery_name'))->setOptions(function () {
                $list = db('express')->where('is_show', 1)->column('id,name');
                $menus = [];
                foreach ($list as $k => $v) {
                    $menus[] = ['value' => $v, 'label' => $v];
                }
                return $menus;
            });
            $f[] = Form::input('delivery_id', '快递单号', $product->getData('delivery_id'));
        }
        $form = Form::make_post_form('配送信息', $f, Url::build('updateDistribution', array('id' => $id)), 2);
        $this->assign(compact('form'));
        return $this->fetch('public/form-builder');
    }

    /**修改配送信息
     * @param Request $request
     * @param $id
     */
    public function updateDistribution(Request $request, $id)
    {
        $data = parent::postMore([
            'delivery_name',
            'delivery_id',
        ], $request);
        if (!$id) return $this->failed('数据不存在');
        $product = StoreOrderModel::get($id);
        if (!$product) return Json::fail('数据不存在!');
        if ($product['delivery_type'] == 'send') {
            if (!$data['delivery_name']) return Json::fail('请输入送货人姓名');
            if (!(int)$data['delivery_id']) return Json::fail('请输入送货人电话号码');
            else if (!preg_match("/^1[3456789]{1}\d{9}$/", $data['delivery_id'])) return Json::fail('请输入正确的送货人电话号码');
        } else if ($product['delivery_type'] == 'express') {
            if (!$data['delivery_name']) return Json::fail('请选择快递公司');
            if (!$data['delivery_id']) return Json::fail('请输入快递单号');
        }
        StoreOrderModel::edit($data, $id);
        HookService::afterListen('store_product_order_distribution', $data, $id, false, StoreProductBehavior::class);
        StoreOrderStatus::setStatus($id, 'distribution', '修改发货信息为' . $data['delivery_name'] . '号' . $data['delivery_id']);
        return Json::successful('修改成功!');
    }

    /**
     * 修改退款状态
     * @param $id
     * @return mixed|\think\response\Json|void
     */
    public function refund_n($id)
    {
        if (!$id) return $this->failed('数据不存在');
        $product = StoreOrderModel::get($id);
        if (!$product) return Json::fail('数据不存在!');
        $f[] = Form::input('order_id', '退款单号', $product->getData('order_id'))->disabled(1);
        $f[] = Form::input('refund_reason', '不退款原因')->type('textarea');
        $form = Form::make_post_form('不退款', $f, Url::build('updateRefundN', array('id' => $id)), 4);
        $this->assign(compact('form'));
        return $this->fetch('public/form-builder');
    }

    /**不退款原因
     * @param Request $request
     * @param $id
     */
    public function updateRefundN(Request $request, $id)
    {
        $data = parent::postMore([
            'refund_reason',
        ], $request);
        if (!$id) return $this->failed('数据不存在');
        $product = StoreOrderModel::get($id);
        if (!$product) return Json::fail('数据不存在!');
        if (!$data['refund_reason']) return Json::fail('请输入退款原因');
        $data['refund_status'] = 0;
        $data['refund_reason_time'] = time();
        StoreOrderModel::edit($data, $id);
        HookService::afterListen('store_product_order_refund_n', $data['refund_reason'], $id, false, StoreProductBehavior::class);
        StoreOrderStatus::setStatus($id, 'refund_n', '不退款原因:' . $data['refund_reason']);
        return Json::successful('修改成功!');
    }

    /**
     * 修改虚拟币
     * @param $id
     * @return mixed|\think\response\Json|void
     */
    public function gold_back($id)
    {
        if (!$id) return $this->failed('数据不存在');
        $order = StoreOrderModel::get($id);
        if (!$order) return Json::fail('数据不存在!');
        $gold_name = SystemConfigService::get('gold_name');
        if ($order['paid'] == 1) {
            $f[] = Form::input('order_id', '退款单号', $order->getData('order_id'))->disabled(1);
            $f[] = Form::number('back_gold', $gold_name, $order->getData('use_gold'))->min(0);
            $form = Form::make_post_form('退' . $gold_name, $f, Url::build('updateGoldBack', array('id' => $id)), 2);
            $this->assign(compact('form'));
            return $this->fetch('public/form-builder');
        } else {
            return Json::fail('参数错误!');
        }
        return $this->fetch('public/form-builder');
    }

    /** 退虚拟币保存
     * @param Request $request
     * @param $id
     */
    public function updateGoldBack(Request $request, $id)
    {
        $data = parent::postMore([
            'back_gold',
        ], $request);
        if (!$id) return $this->failed('数据不存在');
        $order = StoreOrderModel::get($id);
        if (!$order) return Json::fail('数据不存在!');
        $gold_name = SystemConfigService::get('gold_name');
        if ($data['back_gold'] <= 0) return Json::fail('请输入' . $gold_name);
        if ($order['use_gold'] == $order['back_gold']) return Json::fail('已退完!不能再退' . $gold_name . '了');
        $back_gold = $data['back_gold'];
        $data['back_gold'] = bcadd($data['back_gold'], $order['back_gold'], 2);
        $bj = bccomp((float)$order['use_gold'], (float)$data['back_gold'], 2);
        if ($bj < 0) return Json::fail('退' . $gold_name . '大于支付' . $gold_name . '，请修改' . $gold_name);
        ModelBasic::beginTrans();
        $res1 = User::bcInc($order['uid'], 'gold_num', $back_gold, 'uid');
        $res2 = UserBill::income('商品退' . $gold_name, $order['uid'], 'gold_num', 'pay_product_gold_back', $back_gold, $order['id'], $order['pay_price'], '订单退' . floatval($back_gold) . $gold_name . '给用户');
        try {
            HookService::listen('store_order_gold_back', $order, $back_gold, false, StoreProductBehavior::class);
        } catch (\Exception $e) {
            ModelBasic::rollbackTrans();
            return Json::fail($e->getMessage());
        }
        $res = $res1 && $res2;
        ModelBasic::checkTrans($res);
        if (!$res) return Json::fail('退' . $gold_name . '失败!');
        StoreOrderModel::edit($data, $id);
        StoreOrderStatus::setStatus($id, 'gold_back', '商品退' . $gold_name . '：' . $data['back_gold']);
        return Json::successful('退' . $gold_name . '成功!');
    }

    public function remark(Request $request)
    {
        $data = parent::postMore(['id', 'remark'], $request);
        if (!$data['id']) return Json::fail('参数错误!');
        if ($data['remark'] == '') return Json::fail('请输入要备注的内容!');
        $id = $data['id'];
        unset($data['id']);
        StoreOrderModel::edit($data, $id);
        return Json::successful('备注成功!');
    }

    public function order_status($oid)
    {
        if (!$oid) return $this->failed('数据不存在');
        $this->assign(StoreOrderStatus::systemPage($oid));
        return $this->fetch();
    }

    /**订单删除
     * @param int $id
     */
    public function delete($id = 0)
    {
        if (!$id) return Json::fail('参数错误!');
        $orderInfo = StoreOrderModel::get($id);
        if (!$orderInfo) return Json::fail('订单不存在!');
        if ($orderInfo['type'] == 2 && $orderInfo['is_del'] != 1) {
            return Json::fail('该订单需要用户在前端删除后才能删除!');
        } else {
            $data['is_del'] = 1;
        }
        $data['is_system_del'] = 1;
        StoreOrderModel::edit($data, $id);
        return Json::successful('删除成功!');
    }
}
