Browse Source

Merge branch 'master' of http://git.liuniu946.com/PH/happ

Conflicts:
	app/admin/controller/setting/SystemConfig.php
	app/admin/controller/user/Out.php
	app/admin/model/order/StoreOrder.php
	app/admin/model/user/UserPartake.php
	app/admin/view/article/article/index.php
	app/admin/view/index/index.php
	app/admin/view/login/index.php
	app/admin/view/user/out/user_push.php
	app/admin/view/user/user_partake/index.php
	app/api/controller/AlipayController.php
	app/api/controller/Gmdemo.php
	app/api/controller/PublicController.php
	app/api/controller/order/StoreOrderController.php
	app/api/controller/phpcrypto.php
	app/api/controller/user/UserController.php
	app/api/controller/user/UserPartakeController.php
	app/models/store/StoreOrder.php
	app/models/user/UserPartake.php
	crmeb/repositories/OrderRepository.php
	crmeb/repositories/PaymentRepositories.php
	route/api/route.php
Kirin 2 years ago
parent
commit
98be9387ae

+ 379 - 0
app/admin/controller/setting/SystemConfig.php

@@ -1,3 +1,4 @@
+<<<<<<< HEAD
 <?php
 
 namespace app\admin\controller\setting;
@@ -374,3 +375,381 @@ class SystemConfig extends AuthController
     }
 
 }
+=======
+<?php
+
+namespace app\admin\controller\setting;
+
+use think\facade\Route as Url;
+use app\admin\controller\AuthController;
+use app\admin\model\system\{
+    SystemConfig as ConfigModel, SystemConfigTab as ConfigTabModel
+};
+use crmeb\services\{
+    CacheService,
+    FormBuilder as Form,
+    UtilService as Util,
+    JsonService as Json
+};
+use crmeb\services\upload\Upload;
+
+
+/**
+ *  配置列表控制器
+ * Class SystemConfig
+ * @package app\admin\controller\system
+ */
+class SystemConfig extends AuthController
+{
+    /**
+     * 基础配置
+     * */
+    public function index()
+    {
+        [$type, $tab_id, $children_tab_id] = Util::getMore([
+            ['type', 0],//配置类型
+            ['tab_id', 1],//当前分类ID
+            ['children_tab_id', null],//当前子集分类ID
+        ], null, true);
+
+        $config_tab = null;//顶级分类
+        $children_config_tab = null;//二级分类
+
+        if ($type == 3) {//其它分类
+            $config_tab = null;
+        } else {
+            $config_tab = ConfigModel::getConfigTabAll($type);//获取一级tab
+        }
+        $children_config_tab = ConfigModel::getConfigChildrenTabAll($tab_id);//获取二级tab
+
+        if (!$children_tab_id && $children_config_tab) {
+            $children_tab_id = $children_config_tab[0]['id'];
+        }
+
+        if ($children_tab_id) {
+            $tid = $children_tab_id;
+        } else {
+            $tid = $tab_id;
+        }
+
+        //获取分类配置参数
+        $list = ConfigModel::getAll($tid);
+        $formbuider = ConfigModel::builder_config_from_data($list);//生产表单json
+        $form = Form::make_post_form('编辑配置', $formbuider, Url::buildUrl('save_basics'));
+
+        $this->assign('tab_id', $tab_id);
+        $this->assign('children_tab_id', $children_tab_id);
+        $this->assign('config_tab', $config_tab);
+        $this->assign('children_config_tab', $children_config_tab);
+
+        $this->assign(compact('form'));
+        $this->assign('list', $list);
+        return $this->fetch();
+    }
+
+
+
+    /**
+     * 基础配置  单个
+     * @return mixed|void
+     */
+    public function index_alone()
+    {
+        $tab_id = input('tab_id');
+        if (!$tab_id) return $this->failed('参数错误,请重新打开');
+        $this->assign('tab_id', $tab_id);
+        $list = ConfigModel::getAll($tab_id);
+        foreach ($list as $k => $v) {
+            if (!is_null(json_decode($v['value'])))
+                $list[$k]['value'] = json_decode($v['value'], true);
+            if ($v['type'] == 'upload' && !empty($v['value'])) {
+                if ($v['upload_type'] == 1 || $v['upload_type'] == 3) $list[$k]['value'] = explode(',', $v['value']);
+            }
+        }
+        $this->assign('list', $list);
+        return $this->fetch();
+    }
+
+    /**
+     * 添加字段
+     * @return string
+     * @throws \FormBuilder\exception\FormBuilderException
+     */
+    public function create()
+    {
+        $data = Util::getMore(['type',]);//接收参数
+        $tab_id = !empty(request()->param('tab_id')) ? request()->param('tab_id') : 1;
+        //前面通用字段
+        $formbuiderheader = array();
+        $formbuiderheader[] = Form::select('config_tab_id', '分类', 0)->setOptions(function () {
+            $menuList = ConfigTabModel::field(['id', 'pid', 'title'])->select()->toArray();
+            $list = sort_list_tier($menuList, '顶级', 'pid', 'id');
+            $options = [['value' => 0, 'label' => '顶级按钮']];
+            foreach ($list as $option) {
+                $options[] = ['value' => $option['id'], 'label' => $option['html'] . $option['title']];
+            }
+            return $options;
+        })->filterable(1);
+        $formbuiderheader[] = Form::select('input_type', '类型')->setOptions(ConfigModel::texttype());
+        $formbuiderheader[] = Form::input('info', '配置名称')->autofocus(1);
+        $formbuiderheader[] = Form::input('menu_name', '字段变量')->placeholder('例如:site_url');
+        $formbuiderheader[] = Form::input('desc', '配置简介');
+        //不同类型不同字段
+        $formbuider = array();
+        switch ($data['type']) {
+            case 0://文本框
+                $formbuider = ConfigModel::createInputRule($tab_id);
+                break;
+            case 1://多行文本框
+                $formbuider = ConfigModel::createTextAreaRule($tab_id);
+                break;
+            case 2://单选框
+                $formbuider = ConfigModel::createRadioRule($tab_id);
+                break;
+            case 3://文件上传
+                $formbuider = ConfigModel::createUploadRule($tab_id);
+                break;
+            case 4://多选框
+                $formbuider = ConfigModel::createCheckboxRule($tab_id);
+                break;
+            case 5://下拉框
+                $formbuider = ConfigModel::createSelectRule($tab_id);
+                break;
+        }
+        //后面通用字段
+        $formbuiderfoot = array();
+        $formbuiderfoot[] = Form::number('sort', '排序');
+        $formbuiderfoot[] = Form::radio('status', '状态', 1)->options(ConfigModel::formstatus());
+        $formbuiders = array_merge($formbuiderheader, $formbuider, $formbuiderfoot);
+        $form = Form::make_post_form('添加字段', $formbuiders, Url::buildUrl('save'));
+        $this->assign(compact('form'));
+        $this->assign('get', request()->param());
+        return $this->fetch();
+    }
+
+    /**
+     * 保存字段
+     * */
+    public function save()
+    {
+        $data = Util::postMore([
+            'menu_name',
+            'type',
+            'input_type',
+            'config_tab_id',
+            'parameter',
+            'upload_type',
+            'required',
+            'width',
+            'high',
+            'value',
+            'info',
+            'desc',
+            'sort',
+            'status',]);
+        if (!$data['info']) return Json::fail('请输入配置名称');
+        if (!$data['menu_name']) return Json::fail('请输入字段名称');
+        if ($data['menu_name']) {
+            $oneConfig = ConfigModel::getOneConfig('menu_name', $data['menu_name']);
+            if (!empty($oneConfig)) return Json::fail('请重新输入字段名称,之前的已经使用过了');
+        }
+        if (!$data['desc']) return Json::fail('请输入配置简介');
+        if ($data['sort'] < 0) {
+            $data['sort'] = 0;
+        }
+        if ($data['type'] == 'text') {
+            if (!ConfigModel::valiDateTextRole($data)) return Json::fail(ConfigModel::getErrorInfo());
+        }
+        if ($data['type'] == 'textarea') {
+            if (!ConfigModel::valiDateTextareaRole($data)) return Json::fail(ConfigModel::getErrorInfo());
+        }
+        $data['parameter'] = htmlspecialchars_decode($data['parameter']);
+        if ($data['type'] == 'radio' || $data['type'] == 'checkbox') {
+            if (!$data['parameter']) return Json::fail('请输入配置参数');
+            if (!ConfigModel::valiDateRadioAndCheckbox($data)) return Json::fail(ConfigModel::getErrorInfo());
+            $data['value'] = json_encode($data['value']);
+        }
+        ConfigModel::create($data);
+        CacheService::clear();
+        return Json::successful('添加菜单成功!');
+    }
+
+    /**
+     * @param $id
+     */
+    public function update_config($id)
+    {
+        $type = request()->post('type');
+        if ($type == 'text' || $type == 'textarea' || $type == 'radio' || ($type == 'upload' && (request()->post('upload_type') == 1 || request()->post('upload_type') == 3))) {
+            $value = request()->post('value');
+        } else {
+            $value = request()->post('value/a');
+        }
+        $data = Util::postMore(['status', 'info', 'desc', 'sort', 'config_tab_id', 'required', 'parameter', ['value', $value], 'upload_type', 'input_type']);
+        $data['value'] = htmlspecialchars_decode(json_encode($data['value']));
+        $data['parameter'] = htmlspecialchars_decode($data['parameter']);
+        if (!ConfigModel::get($id)) return Json::fail('编辑的记录不存在!');
+        ConfigModel::edit($data, $id);
+        return Json::successful('修改成功!');
+    }
+
+    /**
+     * 修改是否显示子子段
+     * @param $id
+     * @return mixed
+     */
+    public function edit_config($id)
+    {
+        $menu = ConfigModel::get($id)->getData();
+        if (!$menu) return Json::fail('数据不存在!');
+        $formbuider = array();
+        $formbuider[] = Form::input('menu_name', '字段变量', $menu['menu_name'])->disabled(1);
+        $formbuider[] = Form::hidden('type', $menu['type']);
+//        $formbuider[] = Form::select('config_tab_id', '分类', (string)$menu['config_tab_id'])->setOptions(ConfigModel::getConfigTabAll(-1));
+        $formbuider[] = Form::select('config_tab_id', '分类', (string)$menu['config_tab_id'])->setOptions(function () {
+            $menuList = ConfigTabModel::field(['id', 'pid', 'title'])->select()->toArray();
+            $list = sort_list_tier($menuList, '顶级', 'pid', 'id');
+            $options = [['value' => 0, 'label' => '顶级按钮']];
+            foreach ($list as $option) {
+                $options[] = ['value' => $option['id'], 'label' => $option['html'] . $option['title']];
+            }
+            return $options;
+        })->filterable(1);
+        $formbuider[] = Form::input('info', '配置名称', $menu['info'])->autofocus(1);
+        $formbuider[] = Form::input('desc', '配置简介', $menu['desc']);
+        switch ($menu['type']) {
+            case 'text':
+                $menu['value'] = json_decode($menu['value'], true);
+                $formbuider[] = Form::select('input_type', '类型', $menu['input_type'])->setOptions(ConfigModel::texttype());
+                //输入框验证规则
+                $formbuider[] = Form::input('value', '默认值', $menu['value']);
+                if (!empty($menu['required'])) {
+                    $formbuider[] = Form::number('width', '文本框宽(%)', $menu['width']);
+                    $formbuider[] = Form::input('required', '验证规则', $menu['required'])->placeholder('多个请用,隔开例如:required:true,url:true');
+                }
+                break;
+            case 'textarea':
+                $menu['value'] = json_decode($menu['value'], true);
+                //多行文本
+                if (!empty($menu['high'])) {
+                    $formbuider[] = Form::textarea('value', '默认值', $menu['value'])->rows(5);
+                    $formbuider[] = Form::number('width', '文本框宽(%)', $menu['width']);
+                    $formbuider[] = Form::number('high', '多行文本框高(%)', $menu['high']);
+                } else {
+                    $formbuider[] = Form::input('value', '默认值', $menu['value']);
+                }
+                break;
+            case 'radio':
+                $menu['value'] = json_decode($menu['value'], true);
+                $parameter = explode("\n", htmlspecialchars_decode($menu['parameter']));
+                $options = [];
+                if ($parameter) {
+                    foreach ($parameter as $v) {
+                        $data = explode("=>", $v);
+                        $options[] = ['label' => $data[1], 'value' => $data[0]];
+                    }
+                    $formbuider[] = Form::radio('value', '默认值', $menu['value'])->options($options);
+                }
+                //单选和多选参数配置
+                if (!empty($menu['parameter'])) {
+                    $formbuider[] = Form::textarea('parameter', '配置参数', $menu['parameter'])->placeholder("参数方式例如:\n1=白色\n2=红色\n3=黑色");
+                }
+                break;
+            case 'checkbox':
+                $menu['value'] = json_decode($menu['value'], true) ?: [];
+                $parameter = explode("\n", htmlspecialchars_decode($menu['parameter']));
+                $options = [];
+                if ($parameter) {
+                    foreach ($parameter as $v) {
+                        $data = explode("=>", $v);
+                        $options[] = ['label' => $data[1], 'value' => $data[0]];
+                    }
+                    $formbuider[] = Form::checkbox('value', '默认值', $menu['value'])->options($options);
+                }
+                //单选和多选参数配置
+                if (!empty($menu['parameter'])) {
+                    $formbuider[] = Form::textarea('parameter', '配置参数', $menu['parameter'])->placeholder("参数方式例如:\n1=白色\n2=红色\n3=黑色");
+                }
+                break;
+            case 'upload':
+                if ($menu['upload_type'] == 1) {
+                    $menu['value'] = json_decode($menu['value'], true);
+                    $formbuider[] = Form::frameImageOne('value', '图片', Url::buildUrl('admin/widget.images/index', array('fodder' => 'value')), (string)$menu['value'])->icon('image')->width('100%')->height('550px');
+                } elseif ($menu['upload_type'] == 2) {
+                    $menu['value'] = json_decode($menu['value'], true) ?: [];
+                    $formbuider[] = Form::frameImages('value', '多图片', Url::buildUrl('admin/widget.images/index', array('fodder' => 'value')), $menu['value'])->maxLength(5)->icon('images')->width('100%')->height('550px')->spin(0);
+                } else {
+                    $menu['value'] = json_decode($menu['value'], true);
+                    $formbuider[] = Form::uploadFileOne('value', '文件', Url::buildUrl('file_upload'), $menu['value'])->name('file');
+                }
+                //上传类型选择
+                if (!empty($menu['upload_type'])) {
+                    $formbuider[] = Form::radio('upload_type', '上传类型', $menu['upload_type'])->options([['value' => 1, 'label' => '单图'], ['value' => 2, 'label' => '多图'], ['value' => 3, 'label' => '文件']]);
+                }
+                break;
+
+        }
+        $formbuider[] = Form::number('sort', '排序', $menu['sort']);
+        $formbuider[] = Form::radio('status', '状态', $menu['status'])->options([['value' => 1, 'label' => '显示'], ['value' => 2, 'label' => '隐藏']]);
+
+        $form = Form::make_post_form('编辑字段', $formbuider, Url::buildUrl('update_config', array('id' => $id)));
+        $this->assign(compact('form'));
+        return $this->fetch('public/form-builder');
+    }
+
+    /**
+     * 删除子字段
+     * @return \think\response\Json
+     */
+    public function delete_config()
+    {
+        $id = input('id');
+        if (!ConfigModel::del($id)) {
+            return Json::fail(ConfigModel::getErrorInfo('删除失败,请稍候再试!'));
+        } else {
+            CacheService::clear();
+            return Json::successful('删除成功!');
+        }
+    }
+
+    /**
+     * 保存数据    true
+     * */
+    public function save_basics()
+    {
+        $request = app('request');
+        if ($request->isPost()) {
+            $post = $request->post();
+            foreach ($post as $k => $v) {
+                if (is_array($v)) {
+                    $res = ConfigModel::where('menu_name', $k)->column('upload_type', 'type');
+                    foreach ($res as $kk => $vv) {
+                        if ($kk == 'upload') {
+                            if ($vv == 1 || $vv == 3) {
+                                $post[$k] = $v[0];
+                            }
+                        }
+                    }
+                }
+            }
+            foreach ($post as $k => $v) {
+                ConfigModel::edit(['value' => json_encode($v)], $k, 'menu_name');
+            }
+            CacheService::clear();
+            return $this->successful('修改成功');
+        }
+    }
+
+    /**
+     * 文件上传
+     * */
+    public function file_upload()
+    {
+        $upload = new Upload('local');
+        $res = $upload->to('config/file')->move($this->request->param('file', 'file'));
+        if ($res === false) return Json::fail($upload->getError());
+        return Json::successful('上传成功!', ['filePath' => $res->filePath]);
+    }
+
+}
+>>>>>>> 386b37d33e5ba817cba00df29efaefbd692e4dd1

+ 248 - 0
app/admin/controller/user/Out.php

@@ -1,3 +1,4 @@
+<<<<<<< HEAD
 <?php
 
 namespace app\admin\controller\user;
@@ -243,4 +244,251 @@ class Out extends AuthController
         return Json::successlayui($data);
     }
 
+=======
+<?php
+
+namespace app\admin\controller\user;
+
+use app\admin\controller\AuthController;
+use app\admin\controller\Union;
+use app\admin\model\order\StoreOrder;
+use app\admin\model\User;
+use crmeb\services\{ExpressService,
+    FormBuilder,
+    JsonService,
+    MiniProgramService,
+    upload\Upload,
+    WechatService,
+    FormBuilder as Form,
+    CacheService,
+    UtilService as Util,
+    JsonService as Json
+};
+use app\admin\model\system\{SystemAdmin,
+    SystemAttachment as SystemAttachmentModel,
+    SystemAttachmentCategory as Category
+};
+use think\Db;
+use think\facade\Route as Url;
+use think\facade\Validate;
+use app\admin\model\user\Out as model;
+
+class Out extends AuthController
+{
+
+
+    public function index()
+    {
+
+        $this->assign('admin', $this->adminInfo);
+        return $this->fetch();
+    }
+
+
+    public function list()
+    {
+        $where = Util::getMore([
+            ['status', ''],
+            ['page', 1],
+            ['limit', 20],
+            ['auction'],
+            ['uid'],
+            ['null']
+        ]);
+
+        $data = model::list($where);
+        return Json::successlayui($data);
+    }
+
+    /**
+     * 显示创建资源表单页.
+     *
+     * @return \think\Response
+     */
+    public function create($id = 0)
+    {
+        $f = [];
+        $f[] = Form::input('name', '名称')->col(12);
+        $f[] = Form::textarea('info', '简介');
+        $f[] = Form::number('number', '达标额度')->col(12);
+        $f[] = Form::frameImages('pics', '轮播图', Url::buildUrl('admin/widget.images/index', array('fodder' => 'pics')))->maxLength(5)->icon('image')->width('100%')->height('500px');
+        $f[] = Form::radio('status', '状态', 1)->options([['label' => '开启', 'value' => 1], ['label' => '关闭', 'value' => 0]]);
+        $form = Form::make_post_form('添加', $f, Url::buildUrl('save'));
+        $this->assign(compact('form'));
+        return $this->fetch('public/form-builder');
+    }
+
+
+    public function save()
+    {
+        $mode = new model;
+        $data = Util::postMore([
+            'name',
+            'info',
+            'number',
+            'status',
+            ['pics', []]
+        ]);
+        $validate = Validate::rule('name', 'require')->rule([
+            'name' => 'require',
+            'number' => 'require',
+        ]);
+        $validate->message([
+            'name.require' => '名称不能为空',
+            'number.require' => '达标额度不能为空',
+        ]);
+        $data['pics'] = implode(',', $data['pics']);
+        if (!$validate->check($data)) {
+            return Json::fail($validate->getError());
+        }
+        $res = $mode->save($data);
+        if ($res) {
+            return Json::success('添加成功!');
+        } else {
+            return Json::fail(\app\admin\model\auction\Auction::getErrorInfo());
+        }
+
+    }
+
+    /**
+     * 删除
+     * @param $id
+     * @return void
+     * @throws \Exception
+     */
+    public function delete($id)
+    {
+        if (!$id) Json::fail('删除失败');
+        $model = new model;
+
+        $res = $model->where('id', $id)->delete();
+        if ($res) {
+            return Json::success('删除成功!');
+        } else {
+            return Json::fail(\app\admin\model\auction\Auction::getErrorInfo());
+        }
+
+    }
+
+
+    public function set_status($id, $status)
+    {
+
+        if (empty($id)) return Json::fail('修改失败');
+
+        $res = model::update(['status' => $status, 'id' => $id]);
+        if ($res) {
+            return Json::success('修改成功!');
+        } else {
+            return Json::fail(\app\admin\model\auction\Auction::getErrorInfo());
+        }
+    }
+
+    public function edit($id)
+    {
+        if (!$id) Json::fail('数据不存在');
+        $data = model::find($id);
+        $f = [];
+        $f[] = Form::input('name', '名称', $data->getData('name'))->col(12);
+        $f[] = Form::textarea('info', '介绍', $data->getData('info'));
+        $f[] = Form::frameImages('pics', '轮播图', Url::buildUrl('admin/widget.images/index', array('fodder' => 'pics')), explode(',', $data->getData('pics')))->maxLength(5)->icon('image')->width('100%')->height('500px');
+        $f[] = Form::number('number', '达标额度', $data->getData('number'))->col(12);
+        $f[] = Form::radio('status', '状态', $data->getData('status'))->options([['label' => '开启', 'value' => 1], ['label' => '关闭', 'value' => 0]]);
+
+
+        $form = Form::make_post_form('修改', $f, Url::buildUrl('update', compact('id')));
+        $this->assign(compact('form'));
+        return $this->fetch('public/form-builder');
+    }
+
+    public function update()
+    {
+        $data = Util::postMore([
+            'id',
+            'name',
+            'info',
+            'status',
+            'number',
+            ['pics', []]
+        ]);
+
+        $validate = Validate::rule('name', 'require')->rule([
+            'name' => 'require',
+            'number' => 'require',
+        ]);
+        $validate->message([
+            'name.require' => '名称不能为空',
+            'number.require' => '达标数量不能为空',
+
+        ]);
+        $data['pics'] = implode(',', $data['pics']);
+        if (!$validate->check($data)) {
+            return Json::fail($validate->getError());
+        }
+        $res = model::update($data);
+        if ($res) {
+            return Json::success('修改成功!');
+        } else {
+            return Json::fail(\app\admin\model\auction\Auction::getErrorInfo());
+        }
+
+
+    }
+
+    public function edit_content($id)
+    {
+        if (!$id) return $this->failed('数据不存在');
+        $seckill = model::get($id);
+        if (!$seckill) return Json::fail('数据不存在!');
+        $this->assign([
+            'content' => htmlspecialchars_decode($seckill['content']),
+            'field' => 'content',
+            'action' => Url::buildUrl('change_field', ['id' => $id, 'field' => 'content'])
+        ]);
+        return $this->fetch('public/edit_content');
+    }
+
+    public function change_field($id)
+    {
+        if (!$id) return $this->failed('数据不存在');
+        $seckill = model::get($id);
+        if (!$seckill) return Json::fail('数据不存在!');
+        $data['content'] = request()->post('content');
+        $res = model::edit($data, $id);
+        if ($res)
+            return Json::successful('添加成功');
+        else
+            return Json::fail('添加失败');
+    }
+
+
+    /**
+     * 显示创建资源表单页.
+     *
+     * @return \think\Response
+     */
+    public function user_push($uid = 0)
+    {
+        return $this->fetch();
+    }
+
+
+    public function user_push_list()
+    {
+
+        $where = Util::getMore([
+            ['status', ''],
+            ['page', 1],
+            ['limit', 20],
+            ['auction'],
+            ['uid'],
+            ['spread_uid']
+        ]);
+
+        $data = StoreOrder::list($where);
+
+        return Json::successlayui($data);
+    }
+
+>>>>>>> 386b37d33e5ba817cba00df29efaefbd692e4dd1
 }

+ 1335 - 0
app/admin/model/order/StoreOrder.php

@@ -1,3 +1,4 @@
+<<<<<<< HEAD
 <?php
 /**
  *
@@ -1330,4 +1331,1338 @@ HTML;
 
     }
 
+=======
+<?php
+/**
+ *
+ * @author: xaboy<365615158@qq.com>
+ * @day: 2017/11/11
+ */
+
+namespace app\admin\model\order;
+
+use crmeb\basic\BaseModel;
+use crmeb\traits\ModelTrait;
+use think\facade\Route as Url;
+use app\models\store\StoreCart;
+use app\admin\model\wechat\WechatUser;
+use app\admin\model\store\StoreProduct;
+use app\models\routine\RoutineTemplate;
+use app\admin\model\user\{User, UserBill};
+use app\admin\model\ump\{StoreCouponUser, StorePink};
+use crmeb\services\{PHPExcelService, WechatService, WechatTemplateService};
+
+/**
+ * 订单管理Model
+ * Class StoreOrder
+ * @package app\admin\model\store
+ */
+class StoreOrder extends BaseModel
+{
+    /**
+     * 数据表主键
+     * @var string
+     */
+    protected $pk = 'id';
+
+    /**
+     * 模型名称
+     * @var string
+     */
+    protected $name = 'store_order';
+
+    use ModelTrait;
+
+    public static function orderCount()
+    {
+        $data['ys'] = self::statusByWhere(9, new self())->where(['is_system_del' => 0])->count();
+        $data['wz'] = self::statusByWhere(0, new self())->where(['is_system_del' => 0])->count();
+        $data['wf'] = self::statusByWhere(1, new self())->where(['is_system_del' => 0, 'shipping_type' => 1])->count();
+        $data['ds'] = self::statusByWhere(2, new self())->where(['is_system_del' => 0, 'shipping_type' => 1])->count();
+        $data['dp'] = self::statusByWhere(3, new self())->where(['is_system_del' => 0])->count();
+        $data['jy'] = self::statusByWhere(4, new self())->where(['is_system_del' => 0])->count();
+        $data['tk'] = self::statusByWhere(-1, new self())->where(['is_system_del' => 0])->count();
+        $data['yt'] = self::statusByWhere(-2, new self())->where(['is_system_del' => 0])->count();
+        $data['del'] = self::statusByWhere(-4, new self())->where(['is_system_del' => 0])->count();
+        $data['write_off'] = self::statusByWhere(5, new self())->where(['is_system_del' => 0])->count();
+        $data['general'] = self::where(['pink_id' => 0, 'combination_id' => 0, 'seckill_id' => 0, 'bargain_id' => 0, 'is_system_del' => 0])->count();
+        $data['pink'] = self::where('pink_id|combination_id', '>', 0)->where('is_system_del', 0)->count();
+        $data['seckill'] = self::where('seckill_id', '>', 0)->where('is_system_del', 0)->count();
+        $data['bargain'] = self::where('bargain_id', '>', 0)->where('is_system_del', 0)->count();
+        return $data;
+    }
+
+    public static function OrderList($where)
+    {
+        $model = self::getOrderWhere($where, self::alias('a')
+            ->join('user r', 'r.uid=a.uid', 'LEFT'), 'a.', 'r')
+            ->field('a.*,r.nickname,r.phone,r.spread_uid');
+        if ($where['order'] != '') {
+            $model = $model->order(self::setOrder($where['order']));
+        } else {
+            $model = $model->order('a.id desc');
+        }
+        if (isset($where['excel']) && $where['excel'] == 1) {
+            $data = ($data = $model->select()) && count($data) ? $data->toArray() : [];
+        } else {
+            $data = ($data = $model->page((int)$where['page'], (int)$where['limit'])->select()) && count($data) ? $data->toArray() : [];
+        }
+
+        foreach ($data as &$item) {
+            $_info = StoreOrderCartInfo::where('oid', $item['id'])->field('cart_info')->select();
+            $_info = count($_info) ? $_info->toArray() : [];
+            foreach ($_info as $k => $v) {
+                $cart_info = json_decode($v['cart_info'], true);
+                if (!isset($cart_info['productInfo'])) $cart_info['productInfo'] = [];
+                $_info[$k]['cart_info'] = $cart_info;
+                unset($cart_info);
+            }
+            $item['_info'] = $_info;
+            $item['spread_nickname'] = User::where('uid', $item['spread_uid'])->value('nickname');
+            $item['add_time'] = $item['add_time'] ? date('Y-m-d H:i:s', $item['add_time']) : '';
+            $item['back_integral'] = $item['back_integral'] ?: 0;
+            if ($item['pink_id'] || $item['combination_id']) {
+                $pinkStatus = StorePink::where('order_id_key', $item['id'])->value('status');
+                switch ($pinkStatus) {
+                    case 1:
+                        $item['pink_name'] = '[拼团订单]正在进行中';
+                        $item['color'] = '#f00';
+                        break;
+                    case 2:
+                        $item['pink_name'] = '[拼团订单]已完成';
+                        $item['color'] = '#00f';
+                        break;
+                    case 3:
+                        $item['pink_name'] = '[拼团订单]未完成';
+                        $item['color'] = '#f0f';
+                        break;
+                    default:
+                        $item['pink_name'] = '[拼团订单]历史订单';
+                        $item['color'] = '#457856';
+                        break;
+                }
+            } elseif ($item['seckill_id']) {
+                $item['pink_name'] = '[秒杀订单]';
+                $item['color'] = '#32c5e9';
+            } elseif ($item['bargain_id']) {
+                $item['pink_name'] = '[砍价订单]';
+                $item['color'] = '#12c5e9';
+            } else {
+                if ($item['shipping_type'] == 1) {
+                    $item['pink_name'] = '[普通订单]';
+                    $item['color'] = '#895612';
+                } else if ($item['shipping_type'] == 2) {
+                    $item['pink_name'] = '[核销订单]';
+                    $item['color'] = '#8956E8';
+                }
+            }
+            if ($item['paid'] == 1) {
+                switch ($item['pay_type']) {
+                    case 'weixin':
+                        $item['pay_type_name'] = '微信支付';
+                        break;
+                    case 'yue':
+                        $item['pay_type_name'] = '余额支付';
+                        break;
+                    case 'ali':
+                        $item['pay_type_name'] = '支付宝支付';
+                        break;
+                    case 'offline':
+                        $item['pay_type_name'] = '线下支付';
+                        break;
+                    default:
+                        $item['pay_type_name'] = '其他支付';
+                        break;
+                }
+            } else {
+                switch ($item['pay_type']) {
+                    default:
+                        $item['pay_type_name'] = '未支付';
+                        break;
+                    case 'offline':
+                        $item['pay_type_name'] = '线下支付';
+                        $item['pay_type_info'] = 1;
+                        break;
+                }
+            }
+            if ($item['paid'] == 0 && $item['status'] == 0) {
+                $item['status_name'] = '未支付';
+            } else if ($item['paid'] == 1 && $item['status'] == 0 && $item['shipping_type'] == 1 && $item['refund_status'] == 0) {
+                $item['status_name'] = '未发货';
+            } else if ($item['paid'] == 1 && $item['status'] == 0 && $item['shipping_type'] == 2 && $item['refund_status'] == 0) {
+                $item['status_name'] = '未核销';
+            } else if ($item['paid'] == 1 && $item['status'] == 1 && $item['shipping_type'] == 1 && $item['refund_status'] == 0) {
+                $item['status_name'] = '待收货';
+            } else if ($item['paid'] == 1 && $item['status'] == 1 && $item['shipping_type'] == 2 && $item['refund_status'] == 0) {
+                $item['status_name'] = '未核销';
+            } else if ($item['paid'] == 1 && $item['status'] == 2 && $item['refund_status'] == 0) {
+                $item['status_name'] = '待评价';
+            } else if ($item['paid'] == 1 && $item['status'] == 3 && $item['refund_status'] == 0) {
+                $item['status_name'] = '已完成';
+            } else if ($item['paid'] == 1 && $item['refund_status'] == 1) {
+                $refundReasonTime = date('Y-m-d H:i', $item['refund_reason_time']);
+                $refundReasonWapImg = json_decode($item['refund_reason_wap_img'], true);
+                $refundReasonWapImg = $refundReasonWapImg ? $refundReasonWapImg : [];
+                $img = '';
+                if (count($refundReasonWapImg)) {
+                    foreach ($refundReasonWapImg as $itemImg) {
+                        if (strlen(trim($itemImg)))
+                            $img .= '<img style="height:50px;" src="' . $itemImg . '" />';
+                    }
+                }
+                if (!strlen(trim($img))) $img = '无';
+                if (isset($where['excel']) && $where['excel'] == 1) {
+                    $refundImageStr = implode(',', $refundReasonWapImg);
+                    $item['status_name'] = <<<TEXT
+退款原因:{$item['refund_reason_wap']} 
+备注说明:{$item['refund_reason_wap_explain']}
+退款时间:{$refundReasonTime}
+凭证连接:{$refundImageStr}
+TEXT;
+                    unset($refundImageStr);
+                } else {
+                    $item['status_name'] = <<<HTML
+<b style="color:#f124c7">申请退款</b><br/>
+<span>退款原因:{$item['refund_reason_wap']}</span><br/>
+<span>备注说明:{$item['refund_reason_wap_explain']}</span><br/>
+<span>退款时间:{$refundReasonTime}</span><br/>
+<span>退款凭证:{$img}</span>
+HTML;
+                }
+            } else if ($item['paid'] == 1 && $item['refund_status'] == 2) {
+                $item['status_name'] = '已退款';
+            }
+            if ($item['paid'] == 1 && $item['status'] == 0 && $item['shipping_type'] == 2) {
+                $item['_status'] = 0;
+            } else if ($item['paid'] == 0 && $item['status'] == 0 && $item['refund_status'] == 0) {
+                $item['_status'] = 1;
+            } else if ($item['paid'] == 1 && $item['status'] == 0 && $item['refund_status'] == 0) {
+                $item['_status'] = 2;
+            } else if ($item['paid'] == 1 && $item['refund_status'] == 1) {
+                $item['_status'] = 3;
+            } else if ($item['paid'] == 1 && $item['status'] == 1 && $item['refund_status'] == 0) {
+                $item['_status'] = 4;
+            } else if ($item['paid'] == 1 && $item['status'] == 2 && $item['refund_status'] == 0) {
+                $item['_status'] = 5;
+            } else if ($item['paid'] == 1 && $item['status'] == 3 && $item['refund_status'] == 0) {
+                $item['_status'] = 6;
+            } else if ($item['paid'] == 1 && $item['refund_status'] == 2) {
+                $item['_status'] = 7;
+            }
+        }
+        if (isset($where['excel']) && $where['excel'] == 1) {
+            self::SaveExcel($data);
+        }
+        $count = self::getOrderWhere($where, self::alias('a')->join('user r', 'r.uid=a.uid', 'LEFT'), 'a.', 'r')->count();
+        return compact('count', 'data');
+    }
+
+    /*
+     * 保存并下载excel
+     * $list array
+     * return
+     */
+    public static function SaveExcel($list)
+    {
+        $export = [];
+        foreach ($list as $index => $item) {
+            $_info = StoreOrderCartInfo::where('oid', $item['id'])->column('cart_info');
+            $goodsName = [];
+            foreach ($_info as $k => $v) {
+                $v = json_decode($v, true);
+                $suk = '';
+                if (isset($v['productInfo']['attrInfo'])) {
+                    if (isset($v['productInfo']['attrInfo']['suk'])) {
+                        $suk = '(' . $v['productInfo']['attrInfo']['suk'] . ')';
+                    }
+                }
+                $goodsName[] = implode(
+                    [$v['productInfo']['store_name'],
+                        $suk,
+                        "[{$v['cart_num']} * {$v['truePrice']}]"
+                    ], ' ');
+            }
+            $item['cartInfo'] = $_info;
+            $sex = WechatUser::where('uid', $item['uid'])->value('sex');
+            if ($sex == 1) $sex_name = '男';
+            else if ($sex == 2) $sex_name = '女';
+            else $sex_name = '未知';
+            $export[] = [
+                $item['order_id'],
+                $sex_name,
+                $item['phone'],
+                $item['real_name'],
+                $item['user_phone'],
+                $item['user_address'],
+                $goodsName,
+                $item['total_price'],
+                $item['pay_price'],
+                $item['pay_postage'],
+                $item['coupon_price'],
+                $item['pay_type_name'],
+                $item['pay_time'] > 0 ? date('Y/m-d H:i', $item['pay_time']) : '暂无',
+                $item['status_name'],
+                $item['add_time'],
+                $item['mark']
+            ];
+        }
+        PHPExcelService::setExcelHeader(['订单号', '性别', '电话', '收货人姓名', '收货人电话', '收货地址', '商品信息',
+            '总价格', '实际支付', '邮费', '优惠金额', '支付状态', '支付时间', '订单状态', '下单时间', '用户备注'])
+            ->setExcelTile('订单导出' . date('YmdHis', time()), '订单信息' . time(), ' 生成时间:' . date('Y-m-d H:i:s', time()))
+            ->setExcelContent($export)
+            ->ExcelSave();
+    }
+
+    /**
+     * @param $where
+     * @return array
+     */
+    public static function systemPage($where, $userid = false)
+    {
+        $model = self::getOrderWhere($where, self::alias('a')
+            ->join('user r', 'r.uid=a.uid', 'LEFT'), 'a.', 'r')
+            ->field('a.*,r.nickname');
+        if ($where['order']) {
+            $model = $model->order('a.' . $where['order']);
+        } else {
+            $model = $model->order('a.id desc');
+        }
+        if ($where['export'] == 1) {
+            $list = $model->select()->toArray();
+            $export = [];
+            foreach ($list as $index => $item) {
+
+                if ($item['pay_type'] == 'weixin') {
+                    $payType = '微信支付';
+                } elseif ($item['pay_type'] == 'yue') {
+                    $payType = '余额支付';
+                } elseif ($item['pay_type'] == 'offline') {
+                    $payType = '线下支付';
+                } else {
+                    $payType = '其他支付';
+                }
+
+                $_info = StoreOrderCartInfo::where('oid', $item['id'])->column('cart_info', 'oid');
+                $goodsName = [];
+                foreach ($_info as $k => $v) {
+                    $v = json_decode($v, true);
+                    $goodsName[] = implode(
+                        [$v['productInfo']['store_name'],
+                            isset($v['productInfo']['attrInfo']) ? '(' . $v['productInfo']['attrInfo']['suk'] . ')' : '',
+                            "[{$v['cart_num']} * {$v['truePrice']}]"
+                        ], ' ');
+                }
+                $item['cartInfo'] = $_info;
+                $export[] = [
+                    $item['order_id'], $payType,
+                    $item['total_num'], $item['total_price'], $item['total_postage'], $item['pay_price'], $item['refund_price'],
+                    $item['mark'], $item['remark'],
+                    [$item['real_name'], $item['user_phone'], $item['user_address']],
+                    $goodsName,
+                    [$item['paid'] == 1 ? '已支付' : '未支付', '支付时间: ' . ($item['pay_time'] > 0 ? date('Y/md H:i', $item['pay_time']) : '暂无')]
+
+                ];
+                $list[$index] = $item;
+            }
+            PHPExcelService::setExcelHeader(['订单号', '支付方式', '商品总数', '商品总价', '邮费', '支付金额', '退款金额', '用户备注', '管理员备注', '收货人信息', '商品信息', '支付状态'])
+                ->setExcelTile('订单导出', '订单信息' . time(), ' 生成时间:' . date('Y-m-d H:i:s', time()))
+                ->setExcelContent($export)
+                ->ExcelSave();
+        }
+        return self::page($model, function ($item) {
+            $_info = StoreOrderCartInfo::where('oid', $item['id'])->field('cart_info')->select();
+            foreach ($_info as $k => $v) {
+                $_info[$k]['cart_info'] = json_decode($v['cart_info'], true);
+            }
+            $item['_info'] = $_info;
+            if ($item['pink_id'] && $item['combination_id']) {
+                $pinkStatus = StorePink::where('order_id_key', $item['id'])->value('status');
+                switch ($pinkStatus) {
+                    case 1:
+                        $item['pink_name'] = '[拼团订单]正在进行中';
+                        $item['color'] = '#f00';
+                        break;
+                    case 2:
+                        $item['pink_name'] = '[拼团订单]已完成';
+                        $item['color'] = '#00f';
+                        break;
+                    case 3:
+                        $item['pink_name'] = '[拼团订单]未完成';
+                        $item['color'] = '#f0f';
+                        break;
+                    default:
+                        $item['pink_name'] = '[拼团订单]历史订单';
+                        $item['color'] = '#457856';
+                        break;
+                }
+            } else {
+                if ($item['seckill_id']) {
+                    $item['pink_name'] = '[秒杀订单]';
+                    $item['color'] = '#32c5e9';
+                } elseif ($item['bargain_id']) {
+                    $item['pink_name'] = '[砍价订单]';
+                    $item['color'] = '#12c5e9';
+                } else {
+                    $item['pink_name'] = '[普通订单]';
+                    $item['color'] = '#895612';
+                }
+            }
+        }, $where);
+    }
+
+    public static function statusByWhere($status, $model = null, $alert = '')
+    {
+        if ($model == null) $model = new self;
+        if ('' === $status)
+            return $model;
+        else if ($status == 8)
+            return $model;
+        else if ($status == 0)//未支付
+            return $model->where($alert . 'paid', 0)->where($alert . 'status', 0)->where($alert . 'refund_status', 0)->where($alert . 'is_del', 0);
+        else if ($status == 1)//已支付 未发货
+            return $model->where($alert . 'paid', 1)->where($alert . 'status', 0)->where($alert . 'shipping_type', 1)->where($alert . 'refund_status', 0)->where($alert . 'is_del', 0);
+        else if ($status == 2)//已支付  待收货
+            return $model->where($alert . 'paid', 1)->where($alert . 'status', 1)->where($alert . 'shipping_type', 1)->where($alert . 'refund_status', 0)->where($alert . 'is_del', 0);
+        else if ($status == 5)//已支付  待核销
+            return $model->where($alert . 'paid', 1)->where($alert . 'status', 0)->where($alert . 'shipping_type', 2)->where($alert . 'refund_status', 0)->where($alert . 'is_del', 0);
+        else if ($status == 3)// 已支付  已收货  待评价
+            return $model->where($alert . 'paid', 1)->where($alert . 'status', 2)->where($alert . 'refund_status', 0)->where($alert . 'is_del', 0);
+        else if ($status == 4)// 交易完成
+            return $model->where($alert . 'paid', 1)->where($alert . 'status', 3)->where($alert . 'refund_status', 0)->where($alert . 'is_del', 0);
+        else if ($status == -1)//退款中
+            return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 1)->where($alert . 'is_del', 0);
+        else if ($status == -2)//已退款
+            return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 2)->where($alert . 'is_del', 0);
+        else if ($status == -3)//退款
+            return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 'in', '1,2')->where($alert . 'is_del', 0);
+        else if ($status == -4)//已删除
+            return $model->where($alert . 'is_del', 1);
+        else if ($status == 9)//已卖出
+            return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 0)->where($alert . 'is_del', 0);
+        else
+            return $model;
+    }
+
+    public static function timeQuantumWhere($startTime = null, $endTime = null, $model = null)
+    {
+        if ($model === null) $model = new self;
+        if ($startTime != null && $endTime != null)
+            $model = $model->where('add_time', '>', strtotime($startTime))->where('add_time', '<', strtotime($endTime));
+        return $model;
+    }
+
+    public static function changeOrderId($orderId)
+    {
+        $ymd = substr($orderId, 2, 8);
+        $key = substr($orderId, 16);
+        return 'wx' . $ymd . date('His') . $key;
+    }
+
+    /**
+     * 线下付款
+     * @param $id
+     * @return $this
+     */
+    public static function updateOffline($id)
+    {
+        $count = self::where('id', $id)->count();
+        if (!$count) return self::setErrorInfo('订单不存在');
+        $count = self::where('id', $id)->where('paid', 0)->count();
+        if (!$count) return self::setErrorInfo('订单已支付');
+        $res = self::where('id', $id)->update(['paid' => 1, 'pay_time' => time()]);
+        return $res;
+    }
+
+    /**
+     * TODO 公众号退款发送模板消息
+     * @param $oid
+     * $oid 订单id  key
+     */
+    public static function refundTemplate($data, $oid)
+    {
+        $order = self::where('id', $oid)->find();
+        WechatTemplateService::sendTemplate(WechatUser::where('uid', $order['uid'])->value('openid'), WechatTemplateService::ORDER_REFUND_STATUS, [
+            'first' => '亲,您购买的商品已退款,本次退款' . $data['refund_price'] . '金额',
+            'keyword1' => $order['order_id'],
+            'keyword2' => $order['pay_price'],
+            'keyword3' => date('Y-m-d H:i:s', $order['add_time']),
+            'remark' => '点击查看订单详情'
+        ], Url::buildUrl('/order/detail/' . $order['order_id'])->suffix('')->domain(true)->build());
+    }
+
+    /**
+     * TODO 小程序余额退款模板消息
+     * @param $oid
+     * @return bool|mixed
+     * @throws \think\db\exception\DataNotFoundException
+     * @throws \think\db\exception\ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+    public static function refundRoutineTemplate($oid)
+    {
+        $order = self::where('id', $oid)->find();
+        return RoutineTemplate::sendOrderRefundSuccess($order);
+    }
+
+    /**
+     * 处理where条件
+     * @param $where
+     * @param $model
+     * @return mixed
+     */
+    public static function getOrderWhere($where, $model, $aler = '', $join = '')
+    {
+//        $model = $model->where('combination_id',0);
+        $model = $model->where('is_system_del', 0);
+        if (isset($where['status']) && $where['status'] != '') {
+            $model = self::statusByWhere($where['status'], $model, $aler);
+        }
+        if (isset($where['is_del']) && $where['is_del'] != '' && $where['is_del'] != -1) $model = $model->where($aler . 'is_del', $where['is_del']);
+        if (isset($where['combination_id'])) {
+            if ($where['combination_id'] == '普通订单') {
+                $model = $model->where($aler . 'combination_id', 0)->where($aler . 'seckill_id', 0)->where($aler . 'bargain_id', 0);
+            }
+            if ($where['combination_id'] == '拼团订单') {
+                $model = $model->where($aler . 'combination_id', ">", 0)->where($aler . 'pink_id', ">", 0);
+            }
+            if ($where['combination_id'] == '秒杀订单') {
+                $model = $model->where($aler . 'seckill_id', ">", 0);
+            }
+            if ($where['combination_id'] == '砍价订单') {
+                $model = $model->where($aler . 'bargain_id', ">", 0);
+            }
+        }
+        if (isset($where['pay_type'])) {
+            switch ($where['pay_type']) {
+                case 1:
+                    $model = $model->where($aler . 'pay_type', 'weixin');
+                    break;
+                case 2:
+                    $model = $model->where($aler . 'pay_type', 'yue');
+                    break;
+                case 3:
+                    $model = $model->where($aler . 'pay_type', 'offline');
+                    break;
+            }
+        }
+        if (isset($where['type'])) {
+            switch ($where['type']) {
+                case 1:
+                    $model = $model->where($aler . 'combination_id', 0)->where($aler . 'seckill_id', 0)->where($aler . 'bargain_id', 0);
+                    break;
+                case 2:
+//                    $model = $model->where($aler.'combination_id',">",0)->where($aler.'pink_id',">",0);
+                    $model = $model->where($aler . 'combination_id', ">", 0);
+                    break;
+                case 3:
+                    $model = $model->where($aler . 'seckill_id', ">", 0);
+                    break;
+                case 4:
+                    $model = $model->where($aler . 'bargain_id', ">", 0);
+                    break;
+            }
+        }
+
+        if (isset($where['real_name']) && $where['real_name'] != '') {
+            $model = $model->where($aler . 'order_id|' . $aler . 'real_name|' . $aler . 'user_phone' . ($join ? '|' . $join . '.nickname|' . $join . '.uid|' . $join . '.phone' : ''), 'LIKE', "%$where[real_name]%");
+        }
+        if (isset($where['data']) && $where['data'] !== '') {
+            $model = self::getModelTime($where, $model, $aler . 'add_time');
+        }
+        return $model;
+    }
+
+    public static function getBadge($where)
+    {
+        $price = self::getOrderPrice($where);
+        return [
+            [
+                'name' => '订单数量',
+                'field' => '件',
+                'count' => $price['count_sum'],
+                'background_color' => 'layui-bg-blue',
+                'col' => 2
+            ],
+            [
+                'name' => '售出商品',
+                'field' => '件',
+                'count' => $price['total_num'],
+                'background_color' => 'layui-bg-blue',
+                'col' => 2
+            ],
+            [
+                'name' => '订单金额',
+                'field' => '元',
+                'count' => $price['pay_price'],
+                'background_color' => 'layui-bg-blue',
+                'col' => 2
+            ],
+            [
+                'name' => '退款金额',
+                'field' => '元',
+                'count' => $price['refund_price'],
+                'background_color' => 'layui-bg-blue',
+                'col' => 2
+            ],
+            [
+                'name' => '微信支付金额',
+                'field' => '元',
+                'count' => $price['pay_price_wx'],
+                'background_color' => 'layui-bg-blue',
+                'col' => 2
+            ],
+            [
+                'name' => '余额支付金额',
+                'field' => '元',
+                'count' => $price['pay_price_yue'],
+                'background_color' => 'layui-bg-blue',
+                'col' => 2
+            ],
+            [
+                'name' => '运费金额',
+                'field' => '元',
+                'count' => $price['pay_postage'],
+                'background_color' => 'layui-bg-blue',
+                'col' => 2
+            ],
+            [
+                'name' => '分佣金额',
+                'field' => '元',
+                'count' => $price['brokerage'],
+                'background_color' => 'layui-bg-blue',
+                'col' => 2
+            ],
+            [
+                'name' => '线下支付金额',
+                'field' => '元',
+                'count' => $price['pay_price_offline'],
+                'background_color' => 'layui-bg-blue',
+                'col' => 2
+            ],
+            [
+                'name' => '积分抵扣',
+                'field' => '分',
+                'count' => $price['use_integral'] . '(抵扣金额:¥' . $price['deduction_price'] . ')',
+                'background_color' => 'layui-bg-blue',
+                'col' => 2
+            ],
+            [
+                'name' => '退回积分',
+                'field' => '元',
+                'count' => $price['back_integral'],
+                'background_color' => 'layui-bg-blue',
+                'col' => 2
+            ]
+        ];
+    }
+
+    /**
+     * 处理订单金额
+     * @param $where
+     * @return array
+     */
+    public static function getOrderPrice($where)
+    {
+        $where['is_del'] = 0;//删除订单不统计
+        $model = new self;
+        $price = [];
+        $price['pay_price'] = 0;//支付金额
+        $price['refund_price'] = 0;//退款金额
+        $price['pay_price_wx'] = 0;//微信支付金额
+        $price['pay_price_yue'] = 0;//余额支付金额
+        $price['pay_price_offline'] = 0;//线下支付金额
+        $price['pay_price_other'] = 0;//其他支付金额
+        $price['use_integral'] = 0;//用户使用积分
+        $price['back_integral'] = 0;//退积分总数
+        $price['deduction_price'] = 0;//抵扣金额
+        $price['total_num'] = 0; //商品总数
+        $price['count_sum'] = 0; //商品总数
+        $price['brokerage'] = 0;
+        $price['pay_postage'] = 0;
+        $whereData = ['is_del' => 0];
+        if ($where['status'] == '') {
+            $whereData['paid'] = 1;
+            $whereData['refund_status'] = 0;
+        }
+        $ids = self::getOrderWhere($where, $model)->where($whereData)->column('id');
+        if (count($ids)) {
+            $price['brokerage'] = UserBill::where(['category' => 'now_money', 'type' => 'brokerage'])->where('link_id', 'in', $ids)->sum('number');
+        }
+        $price['refund_price'] = self::getOrderWhere($where, $model)->where(['is_del' => 0, 'paid' => 1, 'refund_status' => 2])->sum('refund_price');
+        $sumNumber = self::getOrderWhere($where, $model)->where($whereData)->field([
+            'sum(total_num) as sum_total_num',
+            'count(id) as count_sum',
+            'sum(pay_price) as sum_pay_price',
+            'sum(pay_postage) as sum_pay_postage',
+            'sum(use_integral) as sum_use_integral',
+            'sum(back_integral) as sum_back_integral',
+            'sum(deduction_price) as sum_deduction_price'
+        ])->find();
+        if ($sumNumber) {
+            $price['count_sum'] = $sumNumber['count_sum'];
+            $price['total_num'] = $sumNumber['sum_total_num'];
+            $price['pay_price'] = $sumNumber['sum_pay_price'];
+            $price['pay_postage'] = $sumNumber['sum_pay_postage'];
+            $price['use_integral'] = $sumNumber['sum_use_integral'];
+            $price['back_integral'] = $sumNumber['sum_back_integral'];
+            $price['deduction_price'] = $sumNumber['sum_deduction_price'];
+        }
+        $list = self::getOrderWhere($where, $model)->where($whereData)->group('pay_type')->column('sum(pay_price) as sum_pay_price,pay_type', 'id');
+        foreach ($list as $v) {
+            if ($v['pay_type'] == 'weixin') {
+                $price['pay_price_wx'] = $v['sum_pay_price'];
+            } elseif ($v['pay_type'] == 'yue') {
+                $price['pay_price_yue'] = $v['sum_pay_price'];
+            } elseif ($v['pay_type'] == 'offline') {
+                $price['pay_price_offline'] = $v['sum_pay_price'];
+            } else {
+                $price['pay_price_other'] = $v['sum_pay_price'];
+            }
+        }
+        return $price;
+    }
+
+    public static function systemPagePink($where)
+    {
+        $model = new self;
+        $model = self::getOrderWherePink($where, $model);
+        $model = $model->order('id desc');
+
+        if ($where['export'] == 1) {
+            $list = $model->select()->toArray();
+            $export = [];
+            foreach ($list as $index => $item) {
+
+                if ($item['pay_type'] == 'weixin') {
+                    $payType = '微信支付';
+                } elseif ($item['pay_type'] == 'yue') {
+                    $payType = '余额支付';
+                } elseif ($item['pay_type'] == 'offline') {
+                    $payType = '线下支付';
+                } else {
+                    $payType = '其他支付';
+                }
+
+                $_info = StoreOrderCartInfo::where('oid', $item['id'])->column('cart_info', 'oid');
+                $goodsName = [];
+                foreach ($_info as $k => $v) {
+                    $v = json_decode($v, true);
+                    $goodsName[] = implode(
+                        [$v['productInfo']['store_name'],
+                            isset($v['productInfo']['attrInfo']) ? '(' . $v['productInfo']['attrInfo']['suk'] . ')' : '',
+                            "[{$v['cart_num']} * {$v['truePrice']}]"
+                        ], ' ');
+                }
+                $item['cartInfo'] = $_info;
+                $export[] = [
+                    $item['order_id'], $payType,
+                    $item['total_num'], $item['total_price'], $item['total_postage'], $item['pay_price'], $item['refund_price'],
+                    $item['mark'], $item['remark'],
+                    [$item['real_name'], $item['user_phone'], $item['user_address']],
+                    $goodsName,
+                    [$item['paid'] == 1 ? '已支付' : '未支付', '支付时间: ' . ($item['pay_time'] > 0 ? date('Y/md H:i', $item['pay_time']) : '暂无')]
+
+                ];
+                $list[$index] = $item;
+            }
+            ExportService::exportCsv($export, '订单导出' . time(), ['订单号', '支付方式', '商品总数', '商品总价', '邮费', '支付金额', '退款金额', '用户备注', '管理员备注', '收货人信息', '商品信息', '支付状态']);
+        }
+
+        return self::page($model, function ($item) {
+            $item['nickname'] = WechatUser::where('uid', $item['uid'])->value('nickname');
+            $_info = StoreOrderCartInfo::where('oid', $item['id'])->field('cart_info')->select();
+            foreach ($_info as $k => $v) {
+                $_info[$k]['cart_info'] = json_decode($v['cart_info'], true);
+            }
+            $item['_info'] = $_info;
+        }, $where);
+    }
+
+    /**
+     * 处理where条件
+     * @param $where
+     * @param $model
+     * @return mixed
+     */
+    public static function getOrderWherePink($where, $model)
+    {
+        $model = $model->where('combination_id', '>', 0);
+        if ($where['status'] != '') $model = $model::statusByWhere($where['status']);
+//        if($where['is_del'] != '' && $where['is_del'] != -1) $model = $model->where('is_del',$where['is_del']);
+        if ($where['real_name'] != '') {
+            $model = $model->where('order_id|real_name|user_phone', 'LIKE', "%$where[real_name]%");
+        }
+        if ($where['data'] !== '') {
+            $model = self::getModelTime($where, $model, 'add_time');
+        }
+        return $model;
+    }
+
+    /**
+     * 处理订单金额
+     * @param $where
+     * @return array
+     */
+    public static function getOrderPricePink($where)
+    {
+        $model = new self;
+        $price = [];
+        $price['pay_price'] = 0;//支付金额
+        $price['refund_price'] = 0;//退款金额
+        $price['pay_price_wx'] = 0;//微信支付金额
+        $price['pay_price_yue'] = 0;//余额支付金额
+        $price['pay_price_offline'] = 0;//线下支付金额
+        $price['pay_price_other'] = 0;//其他支付金额
+        $price['use_integral'] = 0;//用户使用积分
+        $price['back_integral'] = 0;//退积分总数
+        $price['deduction_price'] = 0;//抵扣金额
+        $price['total_num'] = 0; //商品总数
+        $model = self::getOrderWherePink($where, $model);
+        $list = $model->select()->toArray();
+        foreach ($list as $v) {
+            $price['total_num'] = bcadd($price['total_num'], $v['total_num'], 0);
+            $price['pay_price'] = bcadd($price['pay_price'], $v['pay_price'], 2);
+            $price['refund_price'] = bcadd($price['refund_price'], $v['refund_price'], 2);
+            $price['use_integral'] = bcadd($price['use_integral'], $v['use_integral'], 2);
+            $price['back_integral'] = bcadd($price['back_integral'], $v['back_integral'], 2);
+            $price['deduction_price'] = bcadd($price['deduction_price'], $v['deduction_price'], 2);
+            if ($v['pay_type'] == 'weixin') {
+                $price['pay_price_wx'] = bcadd($price['pay_price_wx'], $v['pay_price'], 2);
+            } elseif ($v['pay_type'] == 'yue') {
+                $price['pay_price_yue'] = bcadd($price['pay_price_yue'], $v['pay_price'], 2);
+            } elseif ($v['pay_type'] == 'offline') {
+                $price['pay_price_offline'] = bcadd($price['pay_price_offline'], $v['pay_price'], 2);
+            } else {
+                $price['pay_price_other'] = bcadd($price['pay_price_other'], $v['pay_price'], 2);
+            }
+        }
+        return $price;
+    }
+
+    /**
+     * 获取昨天的订单   首页在使用
+     * @param int $preDay
+     * @param int $day
+     * @return $this|StoreOrder
+     */
+    public static function isMainYesterdayCount($preDay = 0, $day = 0)
+    {
+        $model = new self();
+        $model = $model->where('add_time', '>', $preDay);
+        $model = $model->where('add_time', '<', $day);
+        return $model;
+    }
+
+    /**
+     * 获取用户购买次数
+     * @param int $uid
+     * @return int|string
+     */
+    public static function getUserCountPay($uid = 0)
+    {
+        if (!$uid) return 0;
+        return self::where('uid', $uid)->where('paid', 1)->count();
+    }
+
+    /**
+     * 获取单个用户购买列表
+     * @param array $where
+     * @return array
+     */
+    public static function getOneorderList($where)
+    {
+        return self::where('uid', $where['uid'])
+            ->order('add_time desc')
+            ->page((int)$where['page'], (int)$where['limit'])
+            ->field(['order_id,real_name,total_num,total_price,pay_price,FROM_UNIXTIME(pay_time,"%Y-%m-%d") as pay_time,paid,pay_type,pink_id,seckill_id,bargain_id'
+            ])->select()
+            ->toArray();
+    }
+
+    /**
+     * 设置订单统计图搜索
+     * @param array $where 条件
+     * @param null $status
+     * @param null $time
+     * @return array
+     */
+    public static function setEchatWhere($where, $status = null, $time = null)
+    {
+        $model = self::statusByWhere($where['status'])->where('is_system_del', 0);
+        if ($status !== null) $where['type'] = $status;
+        if ($time === true) $where['data'] = '';
+        switch ($where['type']) {
+            case 1:
+                //普通商品
+                $model = $model->where('combination_id', 0)->where('seckill_id', 0)->where('bargain_id', 0);
+                break;
+            case 2:
+                //拼团商品
+                $model = $model->where('combination_id', ">", 0)->where('pink_id', ">", 0);
+                break;
+            case 3:
+                //秒杀商品
+                $model = $model->where('seckill_id', ">", 0);
+                break;
+            case 4:
+                //砍价商品
+                $model = $model->where('bargain_id', '>', 0);
+                break;
+        }
+        return self::getModelTime($where, $model);
+    }
+
+    /*
+     * 获取订单数据统计图
+     * $where array
+     * $limit int
+     * return array
+     */
+    public static function getEchartsOrder($where, $limit = 20)
+    {
+        $orderlist = self::setEchatWhere($where)->field(
+            'FROM_UNIXTIME(add_time,"%Y-%m-%d") as _add_time,sum(total_num) total_num,count(*) count,sum(total_price) total_price,sum(refund_price) refund_price,group_concat(cart_id SEPARATOR "|") cart_ids'
+        )->group('_add_time')->order('_add_time asc')->select();
+        count($orderlist) && $orderlist = $orderlist->toArray();
+        $legend = ['商品数量', '订单数量', '订单金额', '退款金额'];
+        $seriesdata = [
+            [
+                'name' => $legend[0],
+                'type' => 'line',
+                'data' => [],
+            ],
+            [
+                'name' => $legend[1],
+                'type' => 'line',
+                'data' => []
+            ],
+            [
+                'name' => $legend[2],
+                'type' => 'line',
+                'data' => []
+            ],
+            [
+                'name' => $legend[3],
+                'type' => 'line',
+                'data' => []
+            ]
+        ];
+        $xdata = [];
+        $zoom = '';
+        foreach ($orderlist as $item) {
+            $xdata[] = $item['_add_time'];
+            $seriesdata[0]['data'][] = $item['total_num'];
+            $seriesdata[1]['data'][] = $item['count'];
+            $seriesdata[2]['data'][] = $item['total_price'];
+            $seriesdata[3]['data'][] = $item['refund_price'];
+        }
+        count($xdata) > $limit && $zoom = $xdata[$limit - 5];
+        $badge = self::getOrderBadge($where);
+        $bingpaytype = self::setEchatWhere($where)->group('pay_type')->field('count(*) as count,pay_type')->select();
+        count($bingpaytype) && $bingpaytype = $bingpaytype->toArray();
+        $bing_xdata = ['微信支付', '余额支付', '其他支付'];
+        $color = ['#ffcccc', '#99cc00', '#fd99cc', '#669966'];
+        $bing_data = [];
+        foreach ($bingpaytype as $key => $item) {
+            if ($item['pay_type'] == 'weixin') {
+                $value['name'] = $bing_xdata[0];
+            } else if ($item['pay_type'] == 'yue') {
+                $value['name'] = $bing_xdata[1];
+            } else {
+                $value['name'] = $bing_xdata[2];
+            }
+            $value['value'] = $item['count'];
+            $value['itemStyle']['color'] = isset($color[$key]) ? $color[$key] : $color[0];
+            $bing_data[] = $value;
+        }
+        return compact('zoom', 'xdata', 'seriesdata', 'badge', 'legend', 'bing_data', 'bing_xdata');
+    }
+
+    public static function getOrderBadge($where)
+    {
+        return [
+            [
+                'name' => '拼团订单数量',
+                'field' => '个',
+                'count' => self::setEchatWhere($where, 2)->count(),
+                'content' => '拼团总订单数量',
+                'background_color' => 'layui-bg-cyan',
+                'sum' => self::setEchatWhere($where, 2, true)->count(),
+                'class' => 'fa fa-line-chart',
+                'col' => 2
+            ],
+            [
+                'name' => '砍价订单数量',
+                'field' => '个',
+                'count' => self::setEchatWhere($where, 4)->count(),
+                'content' => '砍价总订单数量',
+                'background_color' => 'layui-bg-cyan',
+                'sum' => self::setEchatWhere($where, 4, true)->count(),
+                'class' => 'fa fa-line-chart',
+                'col' => 2
+            ],
+            [
+                'name' => '秒杀订单数量',
+                'field' => '个',
+                'count' => self::setEchatWhere($where, 3)->count(),
+                'content' => '秒杀总订单数量',
+                'background_color' => 'layui-bg-cyan',
+                'sum' => self::setEchatWhere($where, 3, true)->count(),
+                'class' => 'fa fa-line-chart',
+                'col' => 2
+            ],
+            [
+                'name' => '普通订单数量',
+                'field' => '个',
+                'count' => self::setEchatWhere($where, 1)->count(),
+                'content' => '普通总订单数量',
+                'background_color' => 'layui-bg-cyan',
+                'sum' => self::setEchatWhere($where, 1, true)->count(),
+                'class' => 'fa fa-line-chart',
+                'col' => 2,
+            ],
+            [
+                'name' => '使用优惠卷金额',
+                'field' => '元',
+                'count' => self::setEchatWhere($where)->sum('coupon_price'),
+                'content' => '普通总订单数量',
+                'background_color' => 'layui-bg-cyan',
+                'sum' => self::setEchatWhere($where, null, true)->sum('coupon_price'),
+                'class' => 'fa fa-line-chart',
+                'col' => 2
+            ],
+            [
+                'name' => '积分消耗数',
+                'field' => '个',
+                'count' => self::setEchatWhere($where)->sum('use_integral'),
+                'content' => '积分消耗总数',
+                'background_color' => 'layui-bg-cyan',
+                'sum' => self::setEchatWhere($where, null, true)->sum('use_integral'),
+                'class' => 'fa fa-line-chart',
+                'col' => 2
+            ],
+            [
+                'name' => '积分抵扣金额',
+                'field' => '个',
+                'count' => self::setEchatWhere($where)->sum('deduction_price'),
+                'content' => '积分抵扣总金额',
+                'background_color' => 'layui-bg-cyan',
+                'sum' => self::setEchatWhere($where, null, true)->sum('deduction_price'),
+                'class' => 'fa fa-money',
+                'col' => 2
+            ],
+            [
+                'name' => '在线支付金额',
+                'field' => '元',
+                'count' => self::setEchatWhere($where)->where(['paid' => 1, 'refund_status' => 0])->where('pay_type', 'weixin')->sum('pay_price'),
+                'content' => '在线支付总金额',
+                'background_color' => 'layui-bg-cyan',
+                'sum' => self::setEchatWhere($where, null, true)->where(['paid' => 1, 'refund_status' => 0])->where('pay_type', 'weixin')->sum('pay_price'),
+                'class' => 'fa fa-weixin',
+                'col' => 2
+            ],
+            [
+                'name' => '余额支付金额',
+                'field' => '元',
+                'count' => self::setEchatWhere($where)->where('pay_type', 'yue')->where(['paid' => 1, 'refund_status' => 0])->sum('pay_price'),
+                'content' => '余额支付总金额',
+                'background_color' => 'layui-bg-cyan',
+                'sum' => self::setEchatWhere($where, null, true)->where(['paid' => 1, 'refund_status' => 0])->where('pay_type', 'yue')->sum('pay_price'),
+                'class' => 'fa  fa-balance-scale',
+                'col' => 2
+            ],
+            [
+                'name' => '赚取积分',
+                'field' => '分',
+                'count' => self::setEchatWhere($where)->sum('gain_integral'),
+                'content' => '赚取总积分',
+                'background_color' => 'layui-bg-cyan',
+                'sum' => self::setEchatWhere($where, null, true)->sum('gain_integral'),
+                'class' => 'fa fa-gg-circle',
+                'col' => 2
+            ],
+            [
+                'name' => '交易额',
+                'field' => '元',
+                'count' => self::setEchatWhere($where)->where(['paid' => 1, 'refund_status' => 0])->sum('pay_price'),
+                'content' => '总交易额',
+                'background_color' => 'layui-bg-cyan',
+                'sum' => self::setEchatWhere($where, null, true)->where(['paid' => 1, 'refund_status' => 0])->sum('pay_price'),
+                'class' => 'fa fa-jpy',
+                'col' => 2
+            ],
+            [
+                'name' => '订单商品数量',
+                'field' => '元',
+                'count' => self::setEchatWhere($where)->sum('total_num'),
+                'content' => '订单商品总数量',
+                'background_color' => 'layui-bg-cyan',
+                'sum' => self::setEchatWhere($where, null, true)->sum('total_num'),
+                'class' => 'fa fa-cube',
+                'col' => 2
+            ]
+        ];
+    }
+
+    /**
+     * 微信 订单发货
+     * @param $oid
+     * @param array $postageData
+     * @throws \think\db\exception\DataNotFoundException
+     * @throws \think\db\exception\ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+    public static function orderPostageAfter($oid, $postageData = [])
+    {
+        $order = self::where('id', $oid)->find();
+        $url = Url::buildUrl('/order/detail/' . $order['order_id'])->suffix('')->domain(true)->build();
+        $group = [
+            'first' => '亲,您的订单已发货,请注意查收',
+            'remark' => '点击查看订单详情'
+        ];
+        if ($postageData['delivery_type'] == 'send') {//送货
+            $goodsName = StoreOrderCartInfo::getProductNameList($order['id']);
+            if ($order['is_channel'] == 1) {
+                //小程序送货模版消息
+                RoutineTemplate::sendOrderPostage($order);
+            } else {//公众号
+                $openid = WechatUser::where('uid', $order['uid'])->value('openid');
+                $group = array_merge($group, [
+                    'keyword1' => $goodsName,
+                    'keyword2' => $order['pay_type'] == 'offline' ? '线下支付' : date('Y/m/d H:i', $order['pay_time']),
+                    'keyword3' => $order['user_address'],
+                    'keyword4' => $postageData['delivery_name'],
+                    'keyword5' => $postageData['delivery_id']
+                ]);
+                WechatTemplateService::sendTemplate($openid, WechatTemplateService::ORDER_DELIVER_SUCCESS, $group, $url);
+            }
+        } else if ($postageData['delivery_type'] == 'express') {//发货
+            if ($order['is_channel'] == 1) {
+                //小程序发货模版消息
+                RoutineTemplate::sendOrderPostage($order, 1);
+            } else {//公众号
+                try {
+                    $openid = WechatUser::where('uid', $order['uid'])->value('openid');
+                    $content = "亲,您的订单{$order['order_id']}已发货,请注意查收!\n快递公司:{$order['delivery_name']}\n快递单号:{$order['delivery_id']}\n";
+                    $content .= '<a href="https://m.kuaidi100.com/result.jsp?nu=' . $order['delivery_id'] . '">点击查看物流信息</a>';
+                    WechatService::staffService()->message($content)->to($openid)->send();
+                }catch (\Exception $e){
+
+                }
+                //                $group = array_merge($group, [
+//                    'keyword1' => $order['order_id'],
+//                    'keyword2' => $postageData['delivery_name'],
+//                    'keyword3' => $postageData['delivery_id']
+//                ]);
+//                WechatTemplateService::sendTemplate($openid, WechatTemplateService::ORDER_POSTAGE_SUCCESS, $group, $url);
+            }
+        }
+
+    }
+
+    /** 收货后发送模版消息
+     * @param $order
+     */
+    public static function orderTakeAfter($order)
+    {
+        $title = '';
+        $cartInfo = StoreOrderCartInfo::where('oid', $order['id'])->column('cart_info', 'oid');
+
+        if (count($cartInfo)) {
+            foreach ($cartInfo as $key => &$cart) {
+                $cart = json_decode($cart, true);
+                $title .= $cart['productInfo']['store_name'] . ',';
+            }
+        }
+        if (strlen(trim($title)))
+            $title = substr($title, 0, bcsub(strlen($title), 1, 0));
+        else {
+            $cartInfo = StoreCart::alias('a')->where('a.id', 'in', implode(',', json_decode($order['cart_id'], true)))->find();
+            $title = StoreProduct::where('id', $cartInfo['product_id'])->value('store_name');
+        }
+
+        if ($order['is_channel'] == 1) {//小程序
+            RoutineTemplate::sendOrderTakeOver($order, $title);
+        } else {
+            $openid = WechatUser::where('uid', $order['uid'])->value('openid');
+            WechatTemplateService::sendTemplate($openid, WechatTemplateService::ORDER_TAKE_SUCCESS, [
+                'first' => '亲,您的订单已收货',
+                'keyword1' => $order['order_id'],
+                'keyword2' => '已收货',
+                'keyword3' => date('Y-m-d H:i:s', time()),
+                'keyword4' => $title,
+                'remark' => '感谢您的光临!'
+            ]);
+        }
+    }
+
+    /**
+     * 不退款发送模板消息
+     * @param int $id 订单id
+     * @param array $data 退款详情
+     * */
+    public static function refundNoPrieTemplate($id, $data)
+    {
+        $order = self::get($id);
+        if ($order) return false;
+        //小程序模板消息
+        $cartInfo = StoreOrderCartInfo::where('oid', $order['id'])->column('product_id', 'oid') ?: [];
+        $title = '';
+        foreach ($cartInfo as $k => $productId) {
+            $store_name = StoreProduct::where('id', $productId)->value('store_name');
+            $title .= $store_name . ',';
+        }
+        if ($order->is_channel == 1) {
+            RoutineTemplate::sendOrderRefundFail($order, $title);
+        } else {
+            WechatTemplateService::sendTemplate(WechatUser::where('uid', $order->uid)->value('openid'), WechatTemplateService::ORDER_REFUND_STATUS, [
+                'first' => '很抱歉您的订单退款失败,失败原因:' . $data,
+                'keyword1' => $order->order_id,
+                'keyword2' => $order->pay_price,
+                'keyword3' => date('Y-m-d H:i:s', time()),
+                'remark' => '给您带来的不便,请谅解!'
+            ], Url::buildUrl('/order/detail/' . $order['order_id'])->suffix('')->domain(true)->build());
+        }
+    }
+
+    /**
+     * 获取订单总数
+     * @param int $uid
+     * @return int|string
+     */
+    public static function getOrderCount($uid = 0)
+    {
+        if (!$uid) return 0;
+        return self::where('uid', $uid)->where('paid', 1)->where('refund_status', 0)->where('status', 2)->count();
+    }
+
+    /**
+     * 获取已支付的订单
+     * @param int $is_promoter
+     * @return int|string
+     */
+    public static function getOrderPayCount($is_promoter = 0)
+    {
+        return self::where('o.paid', 1)->alias('o')->join('User u', 'u.uid=o.uid')->where('u.is_promoter', $is_promoter)->count();
+    }
+
+    /**
+     * 获取最后一个月已支付的订单
+     * @param int $is_promoter
+     * @return int|string
+     */
+    public static function getOrderPayMonthCount($is_promoter = 0)
+    {
+        return self::where('o.paid', 1)->alias('o')->whereTime('o.pay_time', 'last month')->join('User u', 'u.uid=o.uid')->where('u.is_promoter', $is_promoter)->count();
+    }
+
+    /** 订单收货处理积分
+     * @param $order
+     * @return bool
+     */
+    public static function gainUserIntegral($order, bool $open = true)
+    {
+        if ($order['gain_integral'] > 0) {
+            $userInfo = User::get($order['uid']);
+            $open && BaseModel::beginTrans();
+            $integral = bcadd($userInfo['integral'], $order['gain_integral'], 2);
+            $res1 = false != User::where('uid', $userInfo['uid'])->update(['integral' => $integral]);
+            $res2 = false != UserBill::income('购买商品赠送积分', $order['uid'], 'integral', 'gain', $order['gain_integral'], $order['id'], bcadd($userInfo['integral'], $order['gain_integral'], 2), '购买商品赠送' . floatval($order['gain_integral']) . '积分');
+            $res = $res1 && $res2;
+            $open && BaseModel::checkTrans($res);
+            RoutineTemplate::sendUserIntegral($order['uid'], $order, $order['gain_integral'], $integral);
+            return $res;
+        }
+        return true;
+    }
+
+    public static function integralBack($id)
+    {
+        $order = self::get($id)->toArray();
+        if (!(float)bcsub($order['use_integral'], 0, 2) && !$order['back_integral']) return true;
+        if ($order['back_integral'] && !(int)$order['use_integral']) return true;
+        BaseModel::beginTrans();
+        $data['back_integral'] = bcsub($order['use_integral'], $order['use_integral'], 0);
+        if (!$data['back_integral']) return true;
+        $data['use_integral'] = 0;
+        $data['deduction_price'] = 0.00;
+        $data['pay_price'] = 0.00;
+        $data['coupon_id'] = 0.00;
+        $data['coupon_price'] = 0.00;
+        $res4 = true;
+        $integral = User::where('uid', $order['uid'])->value('integral');
+        $res1 = User::bcInc($order['uid'], 'integral', $data['back_integral'], 'uid');
+        $res2 = UserBill::income('商品退积分', $order['uid'], 'integral', 'pay_product_integral_back', $data['back_integral'], $order['id'], bcadd($integral, $data['back_integral'], 2), '订单退积分' . floatval($data['back_integral']) . '积分到用户积分');
+        $res3 = self::edit($data, $id);
+        if ($order['coupon_id']) $res4 = StoreCouponUser::recoverCoupon($order['coupon_id']);
+        StoreOrderStatus::setStatus($id, 'integral_back', '商品退积分:' . $data['back_integral']);
+        $res = $res1 && $res2 && $res3 && $res4;
+        BaseModel::checkTrans($res);
+        return $res;
+    }
+
+    /**
+     * 订单数量 支付方式
+     * @return array
+     */
+    public static function payTypeCount()
+    {
+        $where['status'] = 8;
+        $where['is_del'] = 0;
+        $where['real_name'] = '';
+        $where['data'] = '';
+        $where['type'] = '';
+        $where['order'] = '';
+        $where['pay_type'] = 1;
+        $weixin = self::getOrderWhere($where, new self)->count();
+        $where['pay_type'] = 2;
+        $yue = self::getOrderWhere($where, new self)->count();
+        $where['pay_type'] = 3;
+        $offline = self::getOrderWhere($where, new self)->count();
+        return compact('weixin', 'yue', 'offline');
+    }
+
+    public static function list($where)
+    {
+        $model = self::alias('a')
+            ->field('*')
+            ->order('id DESC');
+
+
+        if ($where['uid']) $model->where('uid', $where['uid']);
+        if ($where['spread_uid']){
+            $uids = User::where('spread_uid', $where['spread_uid'])->column('uid');
+            $model->where('uid', 'in', $uids);
+        }
+
+        $data['count'] = $model->count();
+        if ($where['page'] && $where['limit']){
+            $model->page($where['page'], $where['limit']);
+        }else{
+            $model->page(20, 1);
+        }
+
+
+        $list = $model->select();
+        $list = count($list) ? $list->toArray() : [];
+
+        foreach ($list as &$item)
+        {
+            $user = User::where('uid', $item['uid'])->find();
+            if ($user['spread_uid']){
+                $spread = User::where('uid', $user['spread_uid'])->find();
+            }else{
+                $spread['nickname'] = '没有推广人';
+            }
+            $item['nickname'] = $user['nickname'].'/'.$user['uid'];
+            $item['spread_name'] = $spread['nickname'].'/'.$user['spread_uid'];
+
+        }
+
+        $data['data'] = $list;
+        return $data;
+
+    }
+
+>>>>>>> 386b37d33e5ba817cba00df29efaefbd692e4dd1
 }

+ 83 - 0
app/admin/model/user/UserPartake.php

@@ -1,3 +1,4 @@
+<<<<<<< HEAD
 <?php
 
 namespace app\admin\model\user;
@@ -78,4 +79,86 @@ class UserPartake extends BaseModel
 
     }
 
+=======
+<?php
+
+namespace app\admin\model\user;
+
+use app\admin\model\order\StoreOrder;
+use app\models\store\StoreProduct;
+use crmeb\services\SystemConfigService;
+use think\facade\Db;
+use crmeb\traits\ModelTrait;
+use crmeb\basic\BaseModel;
+
+/**
+ * TODO 场馆model
+ * Class Article
+ * @package app\models\article
+ */
+class UserPartake extends BaseModel
+{
+    /**
+     * 数据表主键
+     * @var string
+     */
+    protected $pk = 'id';
+
+    /**
+     * 模型名称
+     * @var string
+     */
+    protected $name = 'user_partake';
+    protected $autoWriteTimestamp = true;
+
+    use ModelTrait;
+
+    public static function list($where)
+    {
+        $model = self::alias('a')
+            ->field('a.*,b.nickname,c.name,c.number')
+            ->order('a.id DESC')
+            ->leftJoin('user b', 'b.uid = a.uid')
+            ->leftJoin('out c', 'c.id = a.out_id');
+
+        if ($where['name']) $model->where('b.nickname|a.uid', 'like', '%'.$where['name'].'%');
+        if ($where['status'] == 1){
+            $model->where('a.status', 0);
+        }
+        if ($where['status'] == 2){
+            $model->where('a.status', 1);
+        }
+        if ($where['status'] == 3){
+            $model->where('a.status', 2);
+        }
+        if ($where['status'] == 4){
+            $model->where('a.status', -1);
+        }
+
+        $data['count'] = $model->count();
+        if ($where['page'] && $where['limit']){
+            $model->page($where['page'], $where['limit']);
+        }else{
+            $model->page(20, 1);
+        }
+
+
+        $list = $model->select();
+        $list = count($list) ? $list->toArray() : [];
+        foreach ($list as &$item)
+        {
+            $uids = User::where('spread_uid', $item['uid'])->column('uid');
+            if ($item['money'] == 0){
+                $item['money'] = StoreOrder::where('uid', 'in', $uids)
+                    ->where('paid', 1)
+                    ->where('is_participate', 0)
+                    ->sum('pay_price');
+            }
+        }
+        $data['data'] = $list;
+        return $data;
+
+    }
+
+>>>>>>> 386b37d33e5ba817cba00df29efaefbd692e4dd1
 }

+ 128 - 0
app/admin/view/article/article/index.php

@@ -1,3 +1,4 @@
+<<<<<<< HEAD
 {extend name="public/container"}
 {block name="head_top"}
 <link href="{__MODULE_PATH}wechat/news/css/index.css" type="text/css" rel="stylesheet">
@@ -123,3 +124,130 @@
     })
 </script>
 {/block}
+=======
+{extend name="public/container"}
+{block name="head_top"}
+<link href="{__MODULE_PATH}wechat/news/css/index.css" type="text/css" rel="stylesheet">
+{/block}
+{block name="content"}
+<style>
+    tr td img{height: 50px;}
+</style>
+<div class="row">
+    <div class="col-sm-3">
+      	<div class="ibox">
+           	<div class="ibox-title">分类</div>
+      		<div class="ibox-content">
+            <ul  class="folder-list m-b-md">
+              	{volist name="tree" id="vo"}
+                   <li class="p-xxs"><a href="{:Url('article.article/index',array('pid'=>$vo.id))}">{$vo.html}{$vo.title}</a></li>
+                {/volist}
+            </ul>
+          	</div>
+        </div>
+    </div>
+    <div class="col-sm-9 m-l-n-md">
+        <div class="ibox">
+            <div class="ibox-title">
+<!--                <button type="button" class="btn btn-w-m btn-primary" onclick="$eb.createModalFrame(this.innerText,'{:Url('create',array('cid'=>$where.cid))}',{w:1100,h:760})">添加文章</button>-->
+                <div style="margin-top: 2rem"></div>
+                <div class="row">
+                    <div class="m-b m-l">
+                        <form action="" class="form-inline">
+
+                            <div class="input-group">
+                                <input type="text" name="title" value="{$where.title}" placeholder="请输入关键词" class="input-sm form-control"> <span class="input-group-btn"><button type="submit" class="btn btn-sm btn-primary"> <i class="fa fa-search" ></i>搜索</button> </span>
+                            </div>
+                        </form>
+                    </div>
+                </div>
+            </div>
+            <div class="ibox-content">
+                <table class="footable table table-striped  table-bordered " data-page-size="20">
+                    <thead>
+                    <tr>
+                        <th class="text-center" width="5%">id</th>
+                        <th class="text-center" width="10%">图片</th>
+                        <th class="text-left" >[分类]标题</th>
+                        <th class="text-center" width="8%">浏览量</th>
+                        <th class="text-center">关联标题</th>
+                        <th class="text-center" width="15%">添加时间</th>
+                        <th class="text-center" width="20%">操作</th>
+                    </tr>
+                    </thead>
+                    <tbody>
+                    {volist name="list" id="vo"}
+                    <tr>
+                        <td>{$vo.id}</td>
+                        <td>
+                            <img src="{$vo.image_input}"/>
+                        </td>
+                        <td>[{$vo.catename}]{$vo.title}</td>
+                        <td>{$vo.visit}</td>
+                        <td>{$vo.store_name}</td>
+                        <td>{$vo.add_time|date="Y-m-d H:i:s"}</td>
+
+                        <td class="text-center">
+                            <button style="margin-top: 5px;" class="btn btn-info btn-xs" type="button"  onclick="$eb.createModalFrame('编辑','{:Url('create',array('id'=>$vo['id'],'cid'=>$where.cid))}',{w:1100,h:760})"><i class="fa fa-edit"></i> 编辑</button>
+<!--                            {if $vo.product_id}-->
+<!--                            <button style="margin-top: 5px;" class="btn btn-warning btn-xs underline" data-id="{$vo.id}" type="button" data-url="{:Url('unrelation',array('id'=>$vo['id']))}" ><i class="fa fa-chain-broken"></i> 取消关联</button>-->
+<!--                            {else}-->
+<!--                            <button style="margin-top: 5px;" class="btn btn-warning btn-xs openWindow" data-id="{$vo.id}" type="button" data-url="{:Url('relation',array('id'=>$vo['id']))}" ><i class="fa fa-chain"></i> 关联产品</button>-->
+<!--                            {/if}-->
+<!--                            <button  style="margin-top: 5px;" class="btn btn-danger btn-xs del_news_one" data-id="{$vo.id}" type="button" data-url="{:Url('delete',array('id'=>$vo['id']))}" ><i class="fa fa-times"></i> 删除</button>-->
+                        </td>
+                    </tr>
+                    {/volist}
+                    </tbody>
+                </table>
+            </div>
+        </div>
+        <div style="margin-left: 10px">
+            {include file="public/inner_page"}
+        </div>
+    </div>
+
+</div>
+
+{/block}
+{block name="script"}
+<script>
+
+    $('.del_news_one').on('click',function(){
+        window.t = $(this);
+        var _this = $(this),url =_this.data('url');
+        $eb.$swal('delete',function(){
+            $eb.axios.get(url).then(function(res){
+                console.log(res);
+                if(res.status == 200 && res.data.code == 200) {
+                    $eb.$swal('success',res.data.msg);
+                    _this.parents('tr').remove();
+                }else
+                    return Promise.reject(res.data.msg || '删除失败')
+            }).catch(function(err){
+                $eb.$swal('error',err);
+            });
+        })
+    });
+
+    $('.openWindow').on('click',function () {
+        return $eb.createModalFrame('选择产品',$(this).data('url'));
+    });
+
+    $('.underline').on('click',function () {
+        var url=$(this).data('url');
+        $eb.$swal('delete',function(){
+            $eb.axios.get(url).then(function(res){
+                if(res.status == 200 && res.data.code == 200) {
+                    $eb.$swal('success',res.data.msg);
+                    window.location.reload();
+                }else
+                    return Promise.reject(res.data.msg || '取消失败')
+            }).catch(function(err){
+                $eb.$swal('error',err);
+            });
+        },{title:'确认取消关联产品?',text:'取消后可再关联页选择产品重新关联',confirm:'确定'})
+    })
+</script>
+{/block}
+>>>>>>> 386b37d33e5ba817cba00df29efaefbd692e4dd1

+ 276 - 0
app/admin/view/index/index.php

@@ -1,3 +1,4 @@
+<<<<<<< HEAD
 <!DOCTYPE html>
 <html>
 <head>
@@ -271,3 +272,278 @@
 <script src="{__FRAME_PATH}js/index.js"></script>
 </body>
 </html>
+=======
+<!DOCTYPE html>
+<html>
+<head>
+    <meta charset="utf-8">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <meta name="renderer" content="webkit">
+    <meta http-equiv="Cache-Control" content="no-siteapp" />
+    <title>宏根蒂集团管理系统</title>
+    <!--[if lt IE 9]>
+    <meta http-equiv="refresh" content="0;ie.html" />
+    <![endif]-->
+    <link rel="shortcut icon" href="/favicon.ico">
+    <link href="{__FRAME_PATH}css/bootstrap.min.css" rel="stylesheet">
+    <link href="{__FRAME_PATH}css/font-awesome.min.css" rel="stylesheet">
+    <link href="{__FRAME_PATH}css/animate.min.css" rel="stylesheet">
+    <link href="{__FRAME_PATH}css/style.min.css" rel="stylesheet">
+    <style>
+        .swal2-container{z-index: 100000000000!important;}
+    </style>
+</head>
+<body class="fixed-sidebar full-height-layout gray-bg" style="overflow:hidden">
+<div id="wrapper">
+    <!--左侧导航开始-->
+    <nav class="navbar-default navbar-static-side" role="navigation">
+        <div class="nav-close"><i class="fa fa-times-circle"></i>
+        </div>
+        <div class="sidebar-collapse">
+            <ul class="nav" id="side-menu">
+                <li class="nav-header">
+                    <div class="dropdown profile-element admin_open">
+                        <span>
+                            <img alt="image" class="imgbox" src="{$site_logo}" onerror="javascript:this.src='{__ADMIN_PATH}images/admin_logo.png';"/>
+                        </span>
+                        <a data-toggle="dropdown" class="dropdown-toggle" href="#">
+                            <span class="clear" style="margin-top: 20px;">
+                               <span class="block m-t-xs"><strong class="font-bold">{$_admin['real_name']}</strong></span>
+                                <span class="text-muted text-xs block">{$role_name.role_name ? $role_name.role_name : '管理员'}<b class="caret"></b></span>
+                            </span>
+                        </a>
+                        <ul class="dropdown-menu animated fadeInRight m-t-xs">
+                            <li><a class="J_menuItem admin_close" href="{:Url('setting.systemAdmin/admin_info')}">个人资料</a>
+                            </li>
+<!--                            <li><a class="admin_close" target="_blank" href="http://www.crmeb.com/">联系我们</a>-->
+<!--                            </li>-->
+                            <li class="divider"></li>
+                            <li><a href="{:Url('login/logout')}">安全退出</a>
+                            </li>
+                        </ul>
+                    </div>
+                    <div class="logo-element">CB
+                    </div>
+                </li>
+                <!--  菜单  -->
+                {volist name="menuList" id="menu"}
+                <?php if(isset($menu['child']) && count($menu['child']) > 0){ ?>
+                    <li>
+                        <a href="#"><i class="fa fa-{$menu.icon}"></i> <span class="nav-label">{$menu.menu_name}</span><span class="fa arrow"></span></a>
+                        <ul class="nav nav-second-level">
+                            {volist name="menu.child" id="child"}
+                            <li>
+                                <?php if(isset($child['child']) && count($child['child']) > 0){ ?>
+                                    <a href="#"><i class="fa fa-{$child.icon}"></i>{$child.menu_name}<span class="fa arrow"></span></a>
+                                    <ul class="nav nav-third-level">
+                                        {volist name="child.child" id="song"}
+                                        <li><a class="J_menuItem" href="{$song.url}"><i class="fa fa-{$song.icon}"></i> {$song.menu_name}</a></li>
+                                        {/volist}
+                                    </ul>
+                                <?php }else{ ?>
+                                    <a class="J_menuItem" href="{$child.url}"><i class="fa fa-{$child.icon}"></i>{$child.menu_name}</a>
+                                <?php } ?>
+                            </li>
+                            {/volist}
+                        </ul>
+                    </li>
+                <?php } ?>
+                {/volist}
+            </ul>
+        </div>
+    </nav>
+    <!--左侧导航结束-->
+    <!--右侧部分开始-->
+    <div id="page-wrapper" class="gray-bg dashbard-1">
+        <div class="row content-tabs" @touchmove.prevent  >
+            <button class="roll-nav roll-left navbar-minimalize" style="padding: 0;margin: 0;"><i class="fa fa-bars"></i></button>
+
+            <nav class="page-tabs J_menuTabs">
+                <div class="page-tabs-content">
+                    <a href="javascript:;" class="active J_menuTab" data-id="{:Url('Index/main')}">首页</a>
+                </div>
+            </nav>
+            <button class="roll-nav roll-right J_tabLeft"><i class="fa fa-backward"></i></button>
+            <button class="roll-nav roll-right J_tabRight"><i class="fa fa-forward"></i></button>
+
+            <a href="javascript:void(0);" class="roll-nav roll-right J_tabReply" title="返回"><i class="fa fa-reply"></i> </a>
+            <a href="javascript:void(0);" class="roll-nav roll-right J_tabRefresh" title="刷新"><i class="fa fa-refresh"></i> </a>
+            <a href="javascript:void(0);" class="roll-nav roll-right J_tabFullScreen" title="全屏"><i class="fa fa-arrows"></i> </a>
+            <a href="javascript:void(0);" class="roll-nav roll-right J_notice" data-toggle="dropdown" aria-expanded="true" title="消息"><i class="fa fa-bell"></i> <span class="badge badge-danger" id="msgcount">0</span></a>
+            <ul class="dropdown-menu dropdown-alerts dropdown-menu-right" >
+                <li>
+                    <a class="J_menuItem" href="{:Url('order.store_order/index')}">
+                        <div>
+                            <i class="fa fa-building-o"></i> 待发货
+                            <span class="pull-right text-muted small" id="ordernum">0个</span>
+                        </div>
+                    </a>
+                </li>
+                <li class="divider"></li>
+                <li>
+                    <a class="J_menuItem" href="{:Url('store.store_product/index',array('type'=>5))}">
+                        <div>
+                            <i class="fa fa-pagelines"></i> 库存预警 <span class="pull-right text-muted small" id="inventory">0个</span>
+                        </div>
+                    </a>
+                </li>
+                <li class="divider"></li>
+                <li>
+                    <a class="J_menuItem" href="{:Url('store.store_product_reply/index')}">
+                        <div>
+                            <i class="fa fa-comments-o"></i> 新评论 <span class="pull-right text-muted small" id="commentnum">0个</span>
+                        </div>
+                    </a>
+                </li>
+                <li class="divider"></li>
+                <li>
+                    <a class="J_menuItem" href="{:Url('finance.user_extract/index')}">
+                        <div>
+                            <i class="fa fa-cny"></i> 申请提现 <span class="pull-right text-muted small" id="reflectnum">0个</span>
+                        </div>
+                    </a>
+                </li>
+            </ul>
+            <a href="javascript:void(0);" class="roll-nav roll-right J_tabSetting right-sidebar-toggle" title="更多"><i class="fa fa-tasks"></i></a>
+            <div class="btn-group roll-nav roll-right">
+                <button class="dropdown J_tabClose" data-toggle="dropdown">关闭<span class="caret"></span>
+                </button>
+                <ul role="menu" class="dropdown-menu dropdown-menu-right">
+                    <li class="J_tabShowActive"><a>定位当前选项卡</a>
+                    </li>
+                    <li class="divider"></li>
+                    <li class="J_tabCloseAll"><a>关闭全部选项卡</a>
+                    </li>
+                    <li class="J_tabCloseOther"><a>关闭其他选项卡</a>
+                    </li>
+                </ul>
+            </div>
+        </div>
+        <!--内容展示模块-->
+        <div class="row J_mainContent" id="content-main">
+            <iframe class="J_iframe" name="iframe_crmeb_main" width="100%" height="100%" src="{:Url('Index/main')}" frameborder="0" data-id="{:Url('Index/main')}" seamless></iframe>
+        </div>
+        <!--底部版权-->
+<!--        <div class="footer"  @touchmove.prevent>-->
+<!--            <div class="pull-right">© 2017-2020 <a href="http://www.crmeb.com/" target="_blank">CRMEB</a>-->
+<!--            </div>-->
+<!--        </div>-->
+    </div>
+    <!--右侧部分结束-->
+    <!--右侧边栏开始-->
+    <div id="right-sidebar">
+        <div class="sidebar-container">
+            <ul class="nav nav-tabs navs-3">
+<!--                <li class="active">-->
+<!--                    <a data-toggle="tab" href="#tab-1">-->
+<!--                        <i class="fa fa-bell"></i>通知-->
+<!--                    </a>-->
+<!--                </li>-->
+                <li class="active">
+                    <a data-toggle="tab" href="#tab-1">
+                        <i class="fa fa-gear"></i> 设置
+                    </a>
+                </li>
+                
+            </ul>
+            <div class="tab-content">
+<!--                <div id="tab-1" class="tab-pane active">-->
+<!--                    <div class="sidebar-title">-->
+<!--                        <h3><i class="fa fa-comments-o"></i> 最新通知</h3>-->
+<!--                        <small><i class="fa fa-tim"></i> 您当前有0条未读信息</small>-->
+<!--                    </div>-->
+<!--                    <div>-->
+<!--                    </div>-->
+<!--                </div>-->
+                <div id="tab-1" class="tab-pane active">
+                    <div class="sidebar-title">
+                        <h3><i class="fa fa-comments-o"></i> 提示</h3>
+                        <small><i class="fa fa-tim"></i> 你可以从这里选择和预览主题的布局和样式,这些设置会被保存在本地,下次打开的时候会直接应用这些设置。</small>
+                    </div>
+                    <div class="skin-setttings">
+                        <div class="title">设置</div>
+                        <div class="setings-item">
+                            <span>收起左侧菜单</span>
+                            <div class="switch">
+                                <div class="onoffswitch">
+                                    <input type="checkbox" name="collapsemenu" class="onoffswitch-checkbox" id="collapsemenu">
+                                    <label class="onoffswitch-label" for="collapsemenu">
+                                        <span class="onoffswitch-inner"></span> <span class="onoffswitch-switch"></span>
+                                    </label>
+                                </div>
+                            </div>
+                        </div>
+
+                        <div class="setings-item">
+                                <span>固定宽度</span>
+                            <div class="switch">
+                                <div class="onoffswitch">
+                                    <input type="checkbox" name="boxedlayout" class="onoffswitch-checkbox" id="boxedlayout">
+                                    <label class="onoffswitch-label" for="boxedlayout">
+                                        <span class="onoffswitch-inner"></span> <span class="onoffswitch-switch"></span>
+                                    </label>
+                                </div>
+                            </div>
+                        </div>
+                        <div class="setings-item">
+                            <span>菜单点击刷新</span>
+                            <div class="switch">
+                                <div class="onoffswitch">
+                                    <input type="checkbox" name="refresh" class="onoffswitch-checkbox" id="refresh">
+                                    <label class="onoffswitch-label" for="refresh">
+                                        <span class="onoffswitch-inner"></span> <span class="onoffswitch-switch"></span>
+                                    </label>
+                                </div>
+                            </div>
+                        </div>
+                        <div class="title">皮肤选择</div>
+                        <div class="setings-item default-skin nb">
+                                <span class="skin-name ">
+                         <a href="#" class="s-skin-0">
+                             默认皮肤
+                         </a>
+                    </span>
+                        </div>
+                        <div class="setings-item blue-skin nb">
+                                <span class="skin-name ">
+                        <a href="#" class="s-skin-1">
+                            蓝色主题
+                        </a>
+                    </span>
+                        </div>
+                        <div class="setings-item yellow-skin nb">
+                                <span class="skin-name ">
+                        <a href="#" class="s-skin-3">
+                            黄色/紫色主题
+                        </a>
+                    </span>
+                        </div>
+                    </div>
+                </div>
+
+            </div>
+        </div>
+    </div>
+
+    <!--右侧边栏结束-->
+</div>
+<!--vue调用不能删除-->
+<div id="vm"></div>
+<script src="{__FRAME_PATH}js/jquery.min.js"></script>
+<script src="{__FRAME_PATH}js/bootstrap.min.js"></script>
+<script src="{__STATIC_PATH}plug/helper.js"></script>
+<script src="{__FRAME_PATH}js/plugins/metisMenu/jquery.metisMenu.js"></script>
+<script src="{__FRAME_PATH}js/plugins/slimscroll/jquery.slimscroll.min.js"></script>
+<script src="{__FRAME_PATH}js/plugins/layer/layer.min.js"></script>
+<script src="{__FRAME_PATH}js/hplus.min.js"></script>
+<script src="{__FRAME_PATH}js/contabs.min.js"></script>
+<script src="{__FRAME_PATH}js/plugins/pace/pace.min.js"></script>
+{include file="public/style"}
+<script>
+    window.newOrderAudioLink= '{$new_order_audio_link}';
+    window.workermanPort = '{$workermanPort}';
+</script>
+<script src="{__FRAME_PATH}js/index.js"></script>
+</body>
+</html>
+>>>>>>> 386b37d33e5ba817cba00df29efaefbd692e4dd1

+ 69 - 0
app/admin/view/login/index.php

@@ -1,3 +1,4 @@
+<<<<<<< HEAD
 <!DOCTYPE html>
 <html>
 <head>
@@ -64,4 +65,72 @@
 <!--统计代码,可删除-->
 <!--点击刷新验证码-->
 </body>
+=======
+<!DOCTYPE html>
+<html>
+<head>
+    <meta charset="utf-8">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <meta name="robots" content="noindex,nofollow" />
+    <title>登录管理系统</title>
+    <meta name="generator" content="CRMEB! v2.5" />
+    <meta name="author" content="CRMEB! Team and CRMEB UI Team" />
+    <link href="{__FRAME_PATH}css/bootstrap.min.css?v=3.4.0" rel="stylesheet">
+    <link href="{__PLUG_PATH}layui/css/layui.css" rel="stylesheet">
+    <link href="{__FRAME_PATH}css/font-awesome.min.css?v=4.3.0" rel="stylesheet">
+    <link href="{__FRAME_PATH}css/animate.min.css" rel="stylesheet">
+    <link href="{__FRAME_PATH}css/style.min.css?v=3.0.0" rel="stylesheet">
+    <script>
+        top != window && (top.location.href = location.href);
+    </script>
+</head>
+<body class="gray-bg login-bg">
+<!--<canvas id="canvas" width="900" height="300" style="position: fixed;top: -50px;width: 60%;left: 20%"></canvas>-->
+<div class="middle-box text-center loginscreen  animated fadeInDown">
+    <div class="login-group">
+        <h3 class="login-logo">
+            宏根蒂集团
+        </h3>
+        <form role="form" action="{:url('verify')}" method="post" id="form" onsubmit="return false">
+            <div class="form-group">
+                <div class="input-group m-b"><span class="input-group-addon"><i class="fa fa-user"></i> </span>
+                    <input type="text" id="account" name="account" placeholder="用户名" placeholder="用户名" class="form-control">
+                </div>
+            </div>
+            <div class="form-group">
+                <div class="input-group m-b"><span class="input-group-addon"><i class="fa fa-unlock-alt"></i> </span>
+                    <input type="password" class="form-control" id="pwd" name="pwd" placeholder="密码" required="">
+                </div>
+
+            </div>
+            <div class="form-group">
+                <div class="input-group">
+                    <input type="text" class="form-control" id="verify" name="verify" placeholder="验证码" required="">
+                    <span class="input-group-btn" style="padding: 0;margin: 0;">
+                        <img id="verify_img" src="{:Url('captcha')}" alt="验证码" style="padding: 0;height: 34px;margin: 0;">
+                    </span>
+                </div>
+            </div>
+            <button type="submit" class="btn btn-primary block full-width m-b">登 录</button>
+            <?php /*  <p class="text-muted text-center"> <a href="{:url('./forgetpwd')}"><small>忘记密码了?</small></a> | <a href="{:url('./register')}">注册一个新账号</a>
+              </p>  */ ?>
+        </form>
+    </div>
+</div>
+<!--<div class="footer" style=" position: fixed;bottom: 0;width: 100%;left: 0;margin: 0;opacity: 0.8;">-->
+<!--    <div class="pull-right">© 2017-2020 <a href="http://www.crmeb.com/" target="_blank">CRMEB</a>-->
+<!--    </div>-->
+<!--</div>-->
+
+<!-- 全局js -->
+<script src="{__PLUG_PATH}jquery-1.10.2.min.js"></script>
+<script src="{__FRAME_PATH}js/bootstrap.min.js?v=3.4.0"></script>
+<script src="{__MODULE_PATH}login/flaotfont.js"></script>
+<script src="{__MODULE_PATH}login/ios-parallax.js"></script>
+<script src="{__PLUG_PATH}layui/layui.all.js"></script>
+<script src="{__MODULE_PATH}login/index.js"></script>
+<!--统计代码,可删除-->
+<!--点击刷新验证码-->
+</body>
+>>>>>>> 386b37d33e5ba817cba00df29efaefbd692e4dd1
 </html>

+ 180 - 0
app/admin/view/user/out/user_push.php

@@ -1,3 +1,4 @@
+<<<<<<< HEAD
 {extend name="public/container"}
 {block name="head_top"}
 
@@ -175,4 +176,183 @@
         }
     });
 </script>
+=======
+{extend name="public/container"}
+{block name="head_top"}
+
+{/block}
+{block name="content"}
+<style>
+    .btn-outline {
+        border: none;
+    }
+
+    .btn-outline:hover {
+        background-color: #0e9aef;
+        color: #fff;
+    }
+
+    .layui-form-item .layui-btn {
+        margin-top: 5px;
+        margin-right: 10px;
+    }
+
+    .layui-btn-primary {
+        margin-right: 10px;
+        margin-left: 0 !important;
+    }
+
+    label {
+        margin-bottom: 0 !important;
+        margin-top: 4px;
+    }
+</style>
+<div class="layui-fluid">
+    <div class="layui-row layui-col-space15" id="app">
+        搜索条件
+                <div class="layui-col-md12">
+                    <div class="layui-card">
+                        <div class="layui-card-header">搜索条件</div>
+                        <div class="layui-card-body">
+                            <div class="layui-carousel layadmin-carousel layadmin-shortcut" lay-anim="" lay-indicator="inside" lay-arrow="none" style="background:none">
+                                <form class="layui-form layui-form-pane" action="">
+                                    <div class="layui-form-item">
+
+                                        <div class="layui-col-lg12">
+                                            <label class="layui-form-label" style="top: -5.5px;">推广人</label>
+                                            <div class="layui-input-inline">
+                                                <input type="text" id="spread_uid" name="spread_uid" class="layui-input" placeholder="推广人">
+                                            </div>
+                                            <label class="layui-form-label" style="top: -5.5px;">消费人</label>
+                                            <div class="layui-input-inline">
+                                                <input type="text" id="uid" name="uid" class="layui-input" placeholder="消费人">
+                                            </div>
+                                        </div>
+                                        <div class="layui-inline">
+                                            <div class="layui-input-inline">
+                                                <button class="layui-btn layui-btn-sm layui-btn-normal" lay-submit="search" lay-filter="search">
+                                                    <i class="layui-icon layui-icon-search"></i>搜索</button>
+                                            </div>
+                                        </div>
+                                    </div>
+                                </form>
+                            </div>
+                        </div>
+                    </div>
+                </div>
+
+        <!-- 中间详细信息-->
+        <div :class="item.col!=undefined ? 'layui-col-sm'+item.col+' '+'layui-col-md'+item.col:'layui-col-sm6 layui-col-md3'"
+             v-for="item in badge" v-cloak="" v-if="item.count > 0">
+        </div>
+        <!--enb-->
+    </div>
+    <!--列表-->
+    <div class="layui-row layui-col-space15">
+        <div class="layui-col-md12">
+            <div class="layui-card">
+                <div class="layui-card-header">消费列表</div>
+                <div class="layui-card-body">
+                    <table class="layui-hide" id="List" lay-filter="List"></table>
+
+
+                    <script type="text/html" id="image">
+                        <img style="cursor: pointer" lay-event="open_image" src="{{d.image}}">
+                    </script>
+                    <script type="text/html" id="is_participate">
+                        {{# if(d.is_participate == 0){ }}
+                        <button type="button" class="layui-btn layui-btn-primary layui-btn-xs" style="color: red">未结算</button>
+                        {{# } }}
+                        {{# if(d.is_participate == 1){ }}
+                        <button type="button" class="layui-btn layui-btn-primary layui-btn-xs">已结算</button>
+                        {{# } }}
+                    </script>
+                    <script type="text/html" id="act">
+                        <button type="button" class="layui-btn layui-btn-xs layui-btn-normal"
+                                onclick="$eb.createModalFrame('{{d.title}}-编辑','{:Url('edit')}?id={{d.id}}',{h:700,w:1100})">
+                            编辑
+                        </button>
+                        <button type="button" class="layui-btn layui-btn-xs layui-btn-normal"
+                                onclick="$eb.createModalFrame('{{d.title}}-编辑内容','{:Url('edit_content')}?id={{d.id}}')">
+                            编辑内容
+                        </button>
+                        <button type="button" class="layui-btn layui-btn-xs layui-btn-danger" lay-event='delete' id="">
+                            删除
+                        </button>
+                    </script>
+                </div>
+            </div>
+        </div>
+    </div>
+    <!--end-->
+</div>
+<script src="{__ADMIN_PATH}js/layuiList.js"></script>
+{/block}
+{block name="script"}
+<script>
+    layList.tableList('List', "{:Url('user_push_list')}", function () {
+        return [
+            {type: 'checkbox'},
+            {field: 'id', title: 'ID', sort: true, event: 'id', width: '5%', templet: '#id'},
+            {field: 'spread_name', title: '推广人', align: 'center'},
+            {field: 'nickname', title: '消费人', align: 'center'},
+            {field: 'pay_price', title: '消费额度', align: 'center'},
+            {field: 'is_participate', title: '是否结算',templet: '#is_participate', align: 'center'},
+            // {field: 'status', title: '状态', templet: '#status', align: 'center'},
+            // {field: 'right', title: '操作', align: 'center', toolbar: '#act'},
+        ];
+    });
+
+    //查询
+    layList.search('search', function (where) {
+        layList.reload(where, true);
+    });
+
+    //点击事件绑定
+    layList.tool(function (event, data, obj) {
+        switch (event) {
+            case 'delete':
+                var url = layList.U({c: 'user.out', a: 'delete', q: {id: data.id}});
+                var code = {title: "操作提示", text: "确定将该商品移入回收站吗?", type: 'info', confirm: '是的,移入回收站'};
+                $eb.$swal('delete', function () {
+                    $eb.axios.get(url).then(function (res) {
+                        if (res.status == 200 && res.data.code == 200) {
+                            $eb.$swal('success', res.data.msg);
+                            obj.del();
+                            location.reload();
+                        } else
+                            return Promise.reject(res.data.msg || '删除失败')
+                    }).catch(function (err) {
+                        $eb.$swal('error', err);
+                    });
+                }, code)
+                break;
+            case 'open_image':
+                $eb.openImage(data.image);
+                break;
+            case 'edit':
+                location.href = layList.U({a: 'edit', q: {id: data.id}});
+                break;
+        }
+    })
+
+
+    //改状态
+    layList.switch('status', function (odj, value) {
+        if (odj.elem.checked == true) {
+            layList.baseGet(layList.Url({c: 'user.out', a: 'set_status', p: {status: 1, id: value}}), function (res) {
+                layList.msg(res.msg, function () {
+                    layList.reload();
+                });
+            });
+        } else {
+            layList.baseGet(layList.Url({c: 'user.out', a: 'set_status', p: {status: 0, id: value}}), function (res) {
+                layList.msg(res.msg, function () {
+                    layList.reload();
+                });
+            });
+        }
+    });
+</script>
+>>>>>>> 386b37d33e5ba817cba00df29efaefbd692e4dd1
 {/block}

+ 229 - 0
app/admin/view/user/user_partake/index.php

@@ -1,3 +1,4 @@
+<<<<<<< HEAD
 {extend name="public/container"}
 {block name="head_top"}
 
@@ -224,4 +225,232 @@
         }
     });
 </script>
+=======
+{extend name="public/container"}
+{block name="head_top"}
+
+{/block}
+{block name="content"}
+<style>
+    .btn-outline{
+        border:none;
+    }
+    .btn-outline:hover{
+        background-color: #0e9aef;
+        color: #fff;
+    }
+    .layui-form-item .layui-btn {
+        margin-top: 5px;
+        margin-right: 10px;
+    }
+    .layui-btn-primary{
+        margin-right: 10px;
+        margin-left: 0!important;
+    }
+    label{
+        margin-bottom: 0!important;
+        margin-top: 4px;
+    }
+</style>
+<div class="layui-fluid">
+    <div class="layui-row layui-col-space15" id="app">
+        <!--搜索条件-->
+        <div class="layui-col-md12">
+            <div class="layui-card">
+                <div class="layui-card-header">搜索条件</div>
+                <div class="layui-card-body">
+                    <div class="layui-carousel layadmin-carousel layadmin-shortcut" lay-anim="" lay-indicator="inside" lay-arrow="none" style="background:none">
+                        <form class="layui-form layui-form-pane" action="">
+                            <div class="layui-form-item">
+
+                                <div class="layui-inline">
+                                    <div class="layui-col-lg12">
+                                        <label class="layui-form-label" style="top: -5.5px;">搜索条件</label>
+                                        <div class="layui-input-inline">
+                                            <input type="text" id="auction" name="name" class="layui-input" placeholder="请输入昵称">
+                                        </div>
+                                    </div>
+                                </div>
+                                <div class="layui-inline">
+                                    <label class="layui-form-label" style="top: -4.5px">状态</label>
+                                    <div class="layui-input-block">
+                                        <select name="status">
+                                            <option value="">全部</option>
+                                            <option value="1">正常</option>
+                                            <option value="2">待核销</option>
+                                            <option value="3">已核销</option>
+                                            <option value="4">未完成</option>
+                                        </select>
+                                    </div>
+                                </div>
+
+                                <div class="layui-inline">
+                                    <div class="layui-input-inline">
+                                        <button class="layui-btn layui-btn-sm layui-btn-normal" lay-submit="search" lay-filter="search">
+                                            <i class="layui-icon layui-icon-search"></i>搜索</button>
+                                    </div>
+                                </div>
+                            </div>
+                        </form>
+                    </div>
+                </div>
+            </div>
+        </div>
+
+        <!-- 中间详细信息-->
+        <div :class="item.col!=undefined ? 'layui-col-sm'+item.col+' '+'layui-col-md'+item.col:'layui-col-sm6 layui-col-md3'"
+             v-for="item in badge" v-cloak="" v-if="item.count > 0">
+        </div>
+        <!--enb-->
+    </div>
+    <!--列表-->
+    <div class="layui-row layui-col-space15">
+        <div class="layui-col-md12">
+            <div class="layui-card">
+                <div class="layui-card-header">出局奖励列表</div>
+                <div class="layui-card-body">
+                    <div class="layui-btn-container" id="container-action">
+<!--                        <a class="layui-btn layui-btn-sm" onclick="$eb.createModalFrame(this.innerText,'{:Url('create')}',{h:700,w:1100})">添加出局奖励</a>-->
+<!--                        <button class="layui-btn layui-btn-sm" data-type="del_auction">批量删除</button>-->
+                    </div>
+                    <table class="layui-hide" id="List" lay-filter="List"></table>
+
+
+                    <script type="text/html" id="status">
+                        {{# if(d.status == -1){ }}
+                        <button type="button" class="layui-btn layui-btn-primary layui-btn-xs" style="color: red">未完成</button>
+                        {{# } }}
+                        {{# if(d.status == 0){ }}
+                        <button type="button" class="layui-btn layui-btn-primary layui-btn-xs">正常</button>
+                        {{# } }}
+                        {{# if(d.status == 1){ }}
+                        <button type="button" class="layui-btn layui-btn-primary layui-btn-xs" style="color: #00b7ee">待核销</button>
+                        {{# } }}
+                        {{# if(d.status == 2){ }}
+                        <button type="button" class="layui-btn layui-btn-primary layui-btn-xs" style="color: yellowgreen">已核销</button>
+                        {{# } }}
+
+
+                    </script>
+                    <script type="text/html" id="act">
+                        {{# if(d.status == 0){ }}
+                        <button type="button" class="layui-btn layui-btn-xs layui-btn-warm" lay-event='hx' id="">
+                            核销
+                        </button>
+                        <button type="button" class="layui-btn layui-btn-xs layui-btn-warm" lay-event='wwc' id="">
+                            未完成
+                        </button>
+                        {{# } }}
+                        <button type="button" class="layui-btn layui-btn-xs layui-btn-danger" lay-event='delete' id="">
+                            删除
+                        </button>
+                    </script>
+                </div>
+            </div>
+        </div>
+    </div>
+    <!--end-->
+</div>
+<script src="{__ADMIN_PATH}js/layuiList.js"></script>
+{/block}
+{block name="script"}
+<script>
+    layList.form.render();
+    layList.tableList('List', "{:Url('list')}", function () {
+        return [
+            {type: 'checkbox'},
+            {field: 'id', title: 'ID', sort: true, event: 'id', width: '5%', templet: '#id'},
+            {field: 'uid', title: 'UID', align: 'center'},
+            {field: 'nickname', title: '用户昵称', align: 'center'},
+            {field: 'name', title: '出局名称', align: 'center'},
+            {field: 'status', title: '状态', templet: '#status', align: 'center'},
+            {field: 'number', title: '达标额度', align: 'center'},
+            {field: 'money', title: '累计金额', align: 'center'},
+            {field: 'create_time', title: '参与时间', align: 'center'},
+            {field: 'right', title: '操作', align: 'center', toolbar: '#act'},
+        ];
+    });
+
+    //查询
+    layList.search('search',function(where){
+        layList.reload(where,true);
+    });
+
+    //点击事件绑定
+    layList.tool(function (event,data,obj) {
+        switch (event) {
+            case 'hx':
+                var url=layList.U({c:'user.user_partake',a:'set_status',q:{id:data.id,status:2}});
+                var code = {title:"操作提示",text:"确定核销吗?",type:'info',confirm:'是的'};
+                $eb.$swal('delete',function(){
+                    $eb.axios.get(url).then(function(res){
+                        if(res.status == 200 && res.data.code == 200) {
+                            $eb.$swal('success',res.data.msg);
+                            location.reload();
+                        }else
+                            return Promise.reject(res.data.msg || '失败')
+                    }).catch(function(err){
+                        $eb.$swal('error',err);
+                    });
+                },code)
+                break;
+            case 'wwc':
+                var url=layList.U({c:'user.user_partake',a:'set_status',q:{id:data.id,status:-1}});
+                var code = {title:"操作提示",text:"确定未完成吗?",type:'info',confirm:'是的'};
+                $eb.$swal('delete',function(){
+                    $eb.axios.get(url).then(function(res){
+                        if(res.status == 200 && res.data.code == 200) {
+                            $eb.$swal('success',res.data.msg);
+                            location.reload();
+                        }else
+                            return Promise.reject(res.data.msg || '失败')
+                    }).catch(function(err){
+                        $eb.$swal('error',err);
+                    });
+                },code)
+                break;
+            case 'delete':
+                var url=layList.U({c:'user.user_partake',a:'delete',q:{id:data.id}});
+                var code = {title:"操作提示",text:"确定将移入回收站吗?",type:'info',confirm:'是的,移入回收站'};
+                $eb.$swal('delete',function(){
+                    $eb.axios.get(url).then(function(res){
+                        if(res.status == 200 && res.data.code == 200) {
+                            $eb.$swal('success',res.data.msg);
+                            obj.del();
+                            location.reload();
+                        }else
+                            return Promise.reject(res.data.msg || '删除失败')
+                    }).catch(function(err){
+                        $eb.$swal('error',err);
+                    });
+                },code)
+                break;
+            case 'open_image':
+                $eb.openImage(data.image);
+                break;
+            case 'edit':
+                location.href = layList.U({a:'edit',q:{id:data.id}});
+                break;
+        }
+    })
+
+
+    //改状态
+    layList.switch('status',function (odj,value) {
+        if(odj.elem.checked==true){
+            layList.baseGet(layList.Url({c:'user.out',a:'set_status',p:{status:1,id:value}}),function (res) {
+                layList.msg(res.msg, function () {
+                    layList.reload();
+                });
+            });
+        }else{
+            layList.baseGet(layList.Url({c:'user.out',a:'set_status',p:{status:0,id:value}}),function (res) {
+                layList.msg(res.msg, function () {
+                    layList.reload();
+                });
+            });
+        }
+    });
+</script>
+>>>>>>> 386b37d33e5ba817cba00df29efaefbd692e4dd1
 {/block}

+ 35 - 0
app/api/controller/AlipayController.php

@@ -1,3 +1,4 @@
+<<<<<<< HEAD
 <?php
 
 namespace app\api\controller;
@@ -30,4 +31,38 @@ class AlipayController
             exit();
         }
     }
+=======
+<?php
+
+namespace app\api\controller;
+
+use app\Request;
+use crmeb\repositories\PaymentRepositories;
+use crmeb\services\AlipayService;
+use crmeb\services\SystemConfigService;
+use crmeb\utils\Hook;
+
+class AlipayController
+{
+    public function Notify()
+    {
+        $alipay = SystemConfigService::more(['alipay_app_id', 'alipay_pub_key', 'alipay_private_key', 'alipay_key']);
+        $Pay = new AlipayService();
+        $Pay->setAlipayPublicKey($alipay['alipay_key']);
+        $result = $Pay->rsaCheck($_POST, $_POST['sign_type']);
+        if ($result === true && $_POST['trade_status'] == 'TRADE_SUCCESS') {
+            $out_trade_no = input('out_trade_no', '');
+            if (($count = strpos(input('out_trade_no'), '_')) !== false) {
+                $out_trade_no = substr(input('out_trade_no'), $count + 1);
+            }
+            parse_str(input('passback_params'), $attach);
+            (new Hook(PaymentRepositories::class, 'ali'))->listen($attach['attach'], $out_trade_no);
+            echo 'success';
+            exit();
+        } else {
+            echo 'error';
+            exit();
+        }
+    }
+>>>>>>> 386b37d33e5ba817cba00df29efaefbd692e4dd1
 }

+ 43 - 0
app/api/controller/Gmdemo.php

@@ -18,18 +18,31 @@ namespace app\api\controller;
 
 
 use app\api\controller\AuthController as Controller;
+<<<<<<< HEAD
 // require '/www/wwwroot/hgd.liuniu946.com/app/api/controller/php crypto.php';
+=======
+
+>>>>>>> 386b37d33e5ba817cba00df29efaefbd692e4dd1
 class Gmdemo extends Controller{
 
     //以下参数都需要金融云提供
     //AES偏移量
     protected $iv = 'abcdefghABCDEFGH';
+<<<<<<< HEAD
     protected $appID = "93f1a51c1-39d4-48e1-8119-a37b63c0ed8c";
     protected $appSecretKey = "66a81e7a-dea3-4870-9c63-58712e13aa9b";
     protected $tokenUrl = "https://mouldai.com/apiSIT/tzyj/approveDev";//回归环境
     protected $token;
     //合作机构自有公钥
     const PUBLIC_KEY = "MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAE6mJz31IQpqtv42a67pfUe6q6UKUa/Lxf2rzJC4iAK0p3dOooG/d+N2fs6qmzK+7smovqcP7VhA8D+OIvaVjMsw==";
+=======
+    protected $appID = "96c8268e-cfa4-497f-9329-a5e3417f0825";
+    protected $appSecretKey = "921b3c06-eaed-7b1c-e053-010000717745";
+    protected $tokenUrl = "https://mouldai.com/apiSIT/tzyj/approveDev";//回归环境
+    protected $token;
+    //合作机构自有公钥
+    const PUBLIC_KEY = "DE3w4DgjV+np0oHQzSDUgvlxGKPhi/gHBRp8dtjun+z6uqrRJE6B1qswZpaSCs3tp0tm98ZjjL9RTuNh4dyUuA==";
+>>>>>>> 386b37d33e5ba817cba00df29efaefbd692e4dd1
     //合作机构自有私钥
     const PRIVATE_KEY = "778NKKZgdS9IGm/crvajNPoq5CHJNEKXptciF/1SU3I=";
     //泰隆银行公钥
@@ -39,7 +52,11 @@ class Gmdemo extends Controller{
     {
         // 初始化加密扩展
         echo "--------php_crypto_init 初始化开始--------\n";
+<<<<<<< HEAD
        $path = "/www/wwwroot/hgd.liuniu946.com/public/opt/php/libcryptAPIsm_lnx64.so";//国密动态库路径
+=======
+        $path = "/opt/php/libcryptAPIsm_lnx64.so";
+>>>>>>> 386b37d33e5ba817cba00df29efaefbd692e4dd1
         php_crypto_init($path);
         echo "--------php_crypto_init 初始化结束-------\n";
     }
@@ -68,12 +85,18 @@ class Gmdemo extends Controller{
 		
             
         //初始化转换密钥信息
+<<<<<<< HEAD
         // php_HextoAsc($this->string2hex(base64_decode(self::PRIVATE_KEY)),$k1);
         // php_HextoAsc($this->string2hex(base64_decode(self::PUBLIC_KEY)),$k2);
         // php_HextoAsc($this->string2hex(base64_decode(self::CGB_PUBLIC_KEY)),$gf_k);
         $this->string2hex(base64_decode(self::PRIVATE_KEY));
         $this->string2hex(base64_decode(self::PUBLIC_KEY));
         $this->string2hex(base64_decode(self::CGB_PUBLIC_KEY));
+=======
+        php_HextoAsc($this->string2hex(base64_decode(self::PRIVATE_KEY)),$k1);
+        php_HextoAsc($this->string2hex(base64_decode(self::PUBLIC_KEY)),$k2);
+        php_HextoAsc($this->string2hex(base64_decode(self::CGB_PUBLIC_KEY)),$gf_k);
+>>>>>>> 386b37d33e5ba817cba00df29efaefbd692e4dd1
 
         //拼接参数数组
         $data = [
@@ -120,6 +143,7 @@ class Gmdemo extends Controller{
     //业务请求封装
     public function scanPaymentCode($array=[])
     {
+<<<<<<< HEAD
         
         $k1 = self::PUBLIC_KEY;
         $k2 = self::PRIVATE_KEY;
@@ -134,6 +158,18 @@ class Gmdemo extends Controller{
         
         //数据转json
         
+=======
+        //初始化转换密钥信息
+        php_HextoAsc($this->string2hex(base64_decode(self::PRIVATE_KEY)),$k1);
+        php_HextoAsc($this->string2hex(base64_decode(self::PUBLIC_KEY)),$k2);
+        php_HextoAsc($this->string2hex(base64_decode(self::CGB_PUBLIC_KEY)),$gf_k);
+//        $this->string2hex(base64_decode(self::PRIVATE_KEY));
+//        $this->string2hex(base64_decode(self::PUBLIC_KEY));
+//        $this->string2hex(base64_decode(self::CGB_PUBLIC_KEY));
+
+
+        //数据转json
+>>>>>>> 386b37d33e5ba817cba00df29efaefbd692e4dd1
         $json = json_encode($array, JSON_UNESCAPED_UNICODE);
         //获取随机6位字符串数字
         $seqNO = (string)rand(100000,999999);
@@ -146,9 +182,16 @@ class Gmdemo extends Controller{
             'signMethod' => "SM3",
             'encryptMethod' => "SM4",
             'appAccessToken'=> $this->getToken(),//获取token
+<<<<<<< HEAD
             'sm2EncryptData' => $this->SM2Encrypt($key,self::PUBLIC_KEY), //sm2加密key
             'sm2Sign' => $this->SM2Sign($key,$k2,$k1), //sm2加密key
         ];
+=======
+            'sm2EncryptData' => $this->SM2Encrypt($key,$gf_k), //sm2加密key
+            'sm2Sign' => $this->SM2Sign($key,$k2,$k1), //sm2加密key
+        ];
+
+>>>>>>> 386b37d33e5ba817cba00df29efaefbd692e4dd1
         //拼接签名参数,md5转大写
         $data['sign'] = $this->SM3Crypt($json . $data['seqNO'] . $this->appSecretKey . $key);
         //AES加密业务数据

+ 364 - 0
app/api/controller/PublicController.php

@@ -1,3 +1,4 @@
+<<<<<<< HEAD
 <?php
 
 namespace app\api\controller;
@@ -359,4 +360,367 @@ class PublicController
 
     }
 
+=======
+<?php
+
+namespace app\api\controller;
+
+use app\admin\model\system\SystemAttachment;
+use app\models\store\StoreCategory;
+use app\models\store\StoreCouponIssue;
+use app\models\store\StoreProduct;
+use app\models\store\StoreService;
+use app\models\system\Express;
+use app\models\system\SystemCity;
+use app\models\system\SystemStore;
+use app\models\system\SystemStoreStaff;
+use app\models\user\UserBill;
+use app\models\user\UserLevel;
+use app\models\user\WechatUser;
+use app\Request;
+use crmeb\services\CacheService;
+use crmeb\services\SystemConfigService;
+use crmeb\services\UtilService;
+use crmeb\services\workerman\ChannelService;
+use think\db\exception\DataNotFoundException;
+use think\db\exception\DbException;
+use think\db\exception\ModelNotFoundException;
+use think\facade\Cache;
+use crmeb\services\upload\Upload;
+
+/**
+ * 公共类
+ * Class PublicController
+ * @package app\api\controller
+ */
+class PublicController
+{
+
+    public function test()
+    {
+        UserLevel::setLevelComplete(9);
+    }
+
+    /**
+     * @param Request $request
+     * @return mixed
+     * @throws DataNotFoundException
+     * @throws ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+    public function index(Request $request)
+    {
+        $banner = sys_data('routine_home_banner') ?: [];//TODO 首页banner图
+        $menus = sys_data('routine_home_menus') ?: [];//TODO 首页按钮
+        $roll = sys_data('routine_home_roll_news') ?: [];//TODO 首页滚动新闻
+        $activity = sys_data('routine_home_activity', 3) ?: [];//TODO 首页活动区域图片
+        $site_name = sys_config('site_name');
+        $routine_index_page = sys_data('routine_index_page');
+        $info['fastInfo'] = $routine_index_page[0]['fast_info'] ?? '';//sys_config('fast_info');//TODO 快速选择简介
+        $info['bastInfo'] = $routine_index_page[0]['bast_info'] ?? '';//sys_config('bast_info');//TODO 精品推荐简介
+        $info['firstInfo'] = $routine_index_page[0]['first_info'] ?? '';//sys_config('first_info');//TODO 首发新品简介
+        $info['salesInfo'] = $routine_index_page[0]['sales_info'] ?? '';//sys_config('sales_info');//TODO 促销单品简介
+        $logoUrl = sys_config('routine_index_logo');//TODO 促销单品简介
+        if (strstr($logoUrl, 'http') === false && $logoUrl) $logoUrl = sys_config('site_url') . $logoUrl;
+        $logoUrl = str_replace('\\', '/', $logoUrl);
+        $fastNumber = sys_config('fast_number', 0);//TODO 快速选择分类个数
+        $bastNumber = sys_config('bast_number', 0);//TODO 精品推荐个数
+        $firstNumber = sys_config('first_number', 0);//TODO 首发新品个数
+        $promotionNumber = sys_config('promotion_number', 0);//TODO 首发新品个数
+        $info['fastList'] = StoreCategory::byIndexList((int)$fastNumber, false);//TODO 快速选择分类个数
+        $info['bastList'] = StoreProduct::getBestProduct('id,image,store_name,cate_id,price,ot_price,IFNULL(sales,0) + IFNULL(ficti,0) as sales,unit_name', (int)$bastNumber, $request->uid(), false);//TODO 精品推荐个数
+        $info['firstList'] = StoreProduct::getNewProduct('id,image,store_name,cate_id,price,unit_name,IFNULL(sales,0) + IFNULL(ficti,0) as sales', (int)$firstNumber, $request->uid(), false);//TODO 首发新品个数
+        $info['bastBanner'] = sys_data('routine_home_bast_banner') ?? [];//TODO 首页精品推荐图片
+        $benefit = StoreProduct::getBenefitProduct('id,image,store_name,cate_id,price,ot_price,stock,unit_name', $promotionNumber);//TODO 首页促销单品
+        $lovely = sys_data('routine_home_new_banner') ?: [];//TODO 首发新品顶部图
+        $likeInfo = StoreProduct::getHotProduct('id,image,store_name,cate_id,price,ot_price,unit_name', 3);//TODO 热门榜单 猜你喜欢
+        $couponList = StoreCouponIssue::getIssueCouponList($request->uid(), 3);
+        if ($request->uid()) {
+            $subscribe = WechatUser::where('uid', $request->uid())->value('subscribe') ? true : false;
+        } else {
+            $subscribe = true;
+        }
+        $newGoodsBananr = sys_config('new_goods_bananr');
+        $tengxun_map_key = sys_config('tengxun_map_key');
+        return app('json')->successful(compact('banner', 'menus', 'roll', 'info', 'activity', 'lovely', 'benefit', 'likeInfo', 'logoUrl', 'couponList', 'site_name', 'subscribe', 'newGoodsBananr', 'tengxun_map_key'));
+    }
+
+    /**
+     * @param Request $request
+     * @return mixed
+     * @throws DataNotFoundException
+     * @throws DbException
+     * @throws ModelNotFoundException
+     */
+    public function cityArea(Request $request)
+    {
+        $province = SystemCity::where('level', 0)->where('parent_id', 0)->field('name,city_id')->select()->each(function ($item) {
+            $item['city'] = SystemCity::where('level', 1)
+                ->where('parent_id', $item['city_id'])
+                ->field('name,city_id')
+                ->select()->each(function ($sub_item) {
+                    $sub_item['area'] = SystemCity::where('level', 2)
+                        ->where('parent_id', $sub_item['city_id'])
+                        ->column('name');
+                    unset($sub_item['city_id']);
+                })->toArray();
+            unset($item['city_id']);
+        });
+        return app('json')->success('ok', $province->toArray());
+    }
+
+    /**
+     * 获取分享配置
+     * @return mixed
+     */
+    public function share()
+    {
+        $data['img'] = sys_config('wechat_share_img');
+        if (strstr($data['img'], 'http') === false) $data['img'] = sys_config('site_url') . $data['img'];
+        $data['img'] = str_replace('\\', '/', $data['img']);
+        $data['title'] = sys_config('wechat_share_title');
+        $data['synopsis'] = sys_config('wechat_share_synopsis');
+        return app('json')->successful(compact('data'));
+    }
+
+
+    /**
+     * 获取个人中心菜单
+     * @param Request $request
+     * @return mixed
+     * @throws DataNotFoundException
+     * @throws ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+    public function menu_user(Request $request)
+    {
+        $menusInfo = sys_data('routine_my_menus') ?? [];
+        $user = $request->user();
+        $vipOpen = sys_config('vip_open');
+        $vipOpen = is_string($vipOpen) ? (int)$vipOpen : $vipOpen;
+        foreach ($menusInfo as $key => &$value) {
+            $value['pic'] = set_file_url($value['pic']);
+            if ($value['id'] == 137 && !(intval(sys_config('store_brokerage_statu')) == 2 || $user->is_promoter == 1))
+                unset($menusInfo[$key]);
+            if ($value['id'] == 174 && !StoreService::orderServiceStatus($user->uid))
+                unset($menusInfo[$key]);
+            if (((!StoreService::orderServiceStatus($user->uid)) && (!SystemStoreStaff::verifyStatus($user->uid))) && $value['wap_url'] === '/order/order_cancellation')
+                unset($menusInfo[$key]);
+            if (((!StoreService::orderServiceStatus($user->uid)) && (!SystemStoreStaff::verifyStatus($user->uid))) && $value['wap_url'] === '/admin/order_cancellation/index')
+                unset($menusInfo[$key]);
+            if ((!StoreService::orderServiceStatus($user->uid)) && $value['wap_url'] === '/admin/order/index')
+                unset($menusInfo[$key]);
+            if ($value['wap_url'] == '/user/vip' && !$vipOpen)
+                unset($menusInfo[$key]);
+            if ($value['wap_url'] == '/customer/index' && !StoreService::orderServiceStatus($user->uid))
+                unset($menusInfo[$key]);
+        }
+        return app('json')->successful(['routine_my_menus' => $menusInfo]);
+    }
+
+    /**
+     * 热门搜索关键字获取
+     * @return mixed
+     * @throws DataNotFoundException
+     * @throws ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+    public function search()
+    {
+        $routineHotSearch = sys_data('routine_hot_search') ?? [];
+        $searchKeyword = [];
+        if (count($routineHotSearch)) {
+            foreach ($routineHotSearch as $key => &$item) {
+                array_push($searchKeyword, $item['title']);
+            }
+        }
+        return app('json')->successful($searchKeyword);
+    }
+
+
+    /**
+     * 图片上传
+     * @param Request $request
+     * @return mixed
+     * @throws \Psr\SimpleCache\InvalidArgumentException
+     */
+    public function upload_image(Request $request)
+    {
+        $data = UtilService::postMore([
+            ['filename', 'file'],
+        ], $request);
+        if (!$data['filename']) return app('json')->fail('参数有误');
+        if (Cache::has('start_uploads_' . $request->uid()) && Cache::get('start_uploads_' . $request->uid()) >= 100) return app('json')->fail('非法操作');
+        $upload_type = sys_config('upload_type', 1);
+        $upload = new Upload((int)$upload_type, [
+            'accessKey' => sys_config('accessKey'),
+            'secretKey' => sys_config('secretKey'),
+            'uploadUrl' => sys_config('uploadUrl'),
+            'storageName' => sys_config('storage_name'),
+            'storageRegion' => sys_config('storage_region'),
+        ]);
+        $info = $upload->to('store/comment')->validate()->move($data['filename']);
+        if ($info === false) {
+            return app('json')->fail($upload->getError());
+        }
+        $res = $upload->getUploadInfo();
+        SystemAttachment::attachmentAdd($res['name'], $res['size'], $res['type'], $res['dir'], $res['thumb_path'], 1, $upload_type, $res['time'], 2);
+        if (Cache::has('start_uploads_' . $request->uid()))
+            $start_uploads = (int)Cache::get('start_uploads_' . $request->uid());
+        else
+            $start_uploads = 0;
+        $start_uploads++;
+        Cache::set('start_uploads_' . $request->uid(), $start_uploads, 86400);
+        $res['dir'] = path_to_url($res['dir']);
+        if (strpos($res['dir'], 'http') === false) $res['dir'] = $request->domain() . $res['dir'];
+        return app('json')->successful('图片上传成功!', ['name' => $res['name'], 'url' => $res['dir']]);
+    }
+
+    /**
+     * 物流公司
+     * @return mixed
+     */
+    public function logistics()
+    {
+        $expressList = Express::lst();
+        if (!$expressList) return app('json')->successful([]);
+        return app('json')->successful($expressList->hidden(['code', 'id', 'sort', 'is_show'])->toArray());
+    }
+
+    /**
+     * 短信购买异步通知
+     *
+     * @param Request $request
+     * @return mixed
+     */
+    public function sms_pay_notify(Request $request)
+    {
+        list($order_id, $price, $status, $num, $pay_time, $attach) = UtilService::postMore([
+            ['order_id', ''],
+            ['price', 0.00],
+            ['status', 400],
+            ['num', 0],
+            ['pay_time', time()],
+            ['attach', 0],
+        ], $request, true);
+        if ($status == 200) {
+            ChannelService::instance()->send('PAY_SMS_SUCCESS', ['price' => $price, 'number' => $num], [$attach]);
+            return app('json')->successful();
+        }
+        return app('json')->fail();
+    }
+
+    /**
+     * 记录用户分享
+     * @param Request $request
+     * @return mixed
+     */
+    public function user_share(Request $request)
+    {
+        return app('json')->successful(UserBill::setUserShare($request->uid()));
+    }
+
+    /**
+     * 获取图片base64
+     * @param Request $request
+     * @return mixed
+     */
+    public function get_image_base64(Request $request)
+    {
+        list($imageUrl, $codeUrl) = UtilService::postMore([
+            ['image', ''],
+            ['code', ''],
+        ], $request, true);
+        try {
+            $codeTmp = $code = $codeUrl ? image_to_base64($codeUrl) : false;
+            if (!$codeTmp) {
+                $putCodeUrl = put_image($codeUrl);
+                $code = $putCodeUrl ? image_to_base64($_SERVER['HTTP_HOST'] . '/' . $putCodeUrl) : false;
+                $code ?? unlink($_SERVER["DOCUMENT_ROOT"] . '/' . $putCodeUrl);
+            }
+
+            $imageTmp = $image = $imageUrl ? image_to_base64($imageUrl) : false;
+            if (!$imageTmp) {
+                $putImageUrl = put_image($imageUrl);
+                $image = $putImageUrl ? image_to_base64($_SERVER['HTTP_HOST'] . '/' . $putImageUrl) : false;
+                $image ?? unlink($_SERVER["DOCUMENT_ROOT"] . '/' . $putImageUrl);
+            }
+            return app('json')->successful(compact('code', 'image'));
+        } catch (\Exception $e) {
+            return app('json')->fail($e->getMessage());
+        }
+    }
+
+    /**
+     * 门店列表
+     * @return mixed
+     */
+    public function store_list(Request $request)
+    {
+        list($latitude, $longitude, $page, $limit) = UtilService::getMore([
+            ['latitude', ''],
+            ['longitude', ''],
+            ['page', 1],
+            ['limit', 10]
+        ], $request, true);
+        $list = SystemStore::lst($latitude, $longitude, $page, $limit);
+        if (!$list) $list = [];
+        $data['list'] = $list;
+        $data['tengxun_map_key'] = sys_config('tengxun_map_key');
+        return app('json')->successful($data);
+    }
+
+    /**
+     * 查找城市数据
+     * @param Request $request
+     * @return mixed
+     */
+    public function city_list(Request $request)
+    {
+        $list = CacheService::get('CITY_LIST', function () {
+            $list = SystemCity::with('children')->field(['city_id', 'name', 'id', 'parent_id'])->where('parent_id', 0)->order('id asc')->select()->toArray();
+            $data = [];
+            foreach ($list as &$item) {
+                $value = ['v' => $item['city_id'], 'n' => $item['name']];
+                if ($item['children']) {
+                    foreach ($item['children'] as $key => &$child) {
+                        $value['c'][$key] = ['v' => $child['city_id'], 'n' => $child['name']];
+                        unset($child['id'], $child['area_code'], $child['merger_name'], $child['is_show'], $child['level'], $child['lng'], $child['lat'], $child['lat']);
+                        if (SystemCity::where('parent_id', $child['city_id'])->count()) {
+                            $child['children'] = SystemCity::where('parent_id', $child['city_id'])->field(['city_id', 'name', 'id', 'parent_id'])->select()->toArray();
+                            foreach ($child['children'] as $kk => $vv) {
+                                $value['c'][$key]['c'][$kk] = ['v' => $vv['city_id'], 'n' => $vv['name']];
+                            }
+                        }
+                    }
+                }
+                $data[] = $value;
+            }
+            return $data;
+        }, 0);
+        return app('json')->successful($list);
+    }
+
+    /**
+     * 版本更新
+     * @param Request $request
+     * @return void
+     */
+    public function version(Request $request)
+    {
+        $config = SystemConfigService::more(['version', 'apk']);
+        $data = [
+            'version' => $config['version'],
+            'url' =>   $request->domain().'/'.$config['apk'],
+        ];
+        $msg = [
+            'status' => 200,
+            'msg' => 'ok',
+            'data' => $data
+        ];
+        return app('json')->successful($data);
+
+    }
+
+>>>>>>> 386b37d33e5ba817cba00df29efaefbd692e4dd1
 }

+ 733 - 0
app/api/controller/order/StoreOrderController.php

@@ -1,3 +1,4 @@
+<<<<<<< HEAD
 <?php
 
 namespace app\api\controller\order;
@@ -728,4 +729,736 @@ class StoreOrderController
     {
         return app('json')->successful(StoreOrder::getUserOrderSearchList($request->uid(), 0, 0, 0, ''));
     }
+=======
+<?php
+
+namespace app\api\controller\order;
+
+use app\api\controller\Gmdemo;
+use app\admin\model\system\{
+    SystemAttachment, ShippingTemplates
+};
+use app\admin\model\user\User;
+use app\models\routine\RoutineFormId;
+use crmeb\repositories\OrderRepository;
+use app\models\store\{
+    StoreBargainUser,
+    StoreCart,
+    StoreCoupon,
+    StoreCouponIssue,
+    StoreCouponUser,
+    StoreOrder,
+    StoreOrderCartInfo,
+    StoreOrderStatus,
+    StorePink,
+    StoreProductReply
+};
+use app\models\system\SystemStore;
+use app\models\user\UserAddress;
+use app\models\user\UserLevel;
+use app\Request;
+use crmeb\services\{
+    CacheService,
+    ExpressService,
+    SystemConfigService,
+    UtilService
+};
+
+/**
+ * 订单类
+ * Class StoreOrderController
+ * @package app\api\controller\order
+ */
+class StoreOrderController
+{
+    /**
+     * 订单确认
+     * @param Request $request
+     * @return mixed
+     */
+    public function confirm(Request $request)
+    {
+        $temp = ShippingTemplates::get(1);
+        if (!$temp) return app('json')->fail('默认模板未配置,无法下单');
+        list($cartId) = UtilService::postMore(['cartId'], $request, true);
+        if (!is_string($cartId) || !$cartId) return app('json')->fail('请提交购买的商品');
+        $uid = $request->uid();
+        $cartGroup = StoreCart::getUserProductCartList($uid, $cartId, 1);
+        if (count($cartGroup['invalid'])) return app('json')->fail($cartGroup['invalid'][0]['productInfo']['store_name'] . '已失效!');
+        if (!$cartGroup['valid']) return app('json')->fail('请提交购买的商品');
+        $cartInfo = $cartGroup['valid'];
+        $addr = UserAddress::where('uid', $uid)->where('is_default', 1)->find();
+        $priceGroup = StoreOrder::getOrderPriceGroup($cartInfo, $addr);
+        if ($priceGroup === false) {
+            return app('json')->fail(StoreOrder::getErrorInfo('运费模板不存在'));
+        }
+        $other = [
+            'offlinePostage' => sys_config('offline_postage'),
+            'integralRatio' => sys_config('integral_ratio')
+        ];
+        $usableCoupons = StoreCouponUser::getUsableCouponList($uid, $cartGroup, $priceGroup['totalPrice']);
+        $usableCoupon = isset($usableCoupons[0]) ? $usableCoupons[0] : null;
+        $cartIdA = explode(',', $cartId);
+        $seckill_id = 0;
+        $combination_id = 0;
+        $bargain_id = 0;
+        if (count($cartIdA) == 1) {
+            $seckill_id = StoreCart::where('id', $cartId)->value('seckill_id');
+            $combination_id = StoreCart::where('id', $cartId)->value('combination_id');
+            $bargain_id = StoreCart::where('id', $cartId)->value('bargain_id');
+        }
+        $data['deduction'] = $seckill_id || $combination_id || $bargain_id;
+        $data['usableCoupon'] = $usableCoupon;
+        $data['addressInfo'] = UserAddress::getUserDefaultAddress($uid);
+        $data['seckill_id'] = $seckill_id;
+        $data['combination_id'] = $combination_id;
+        $data['bargain_id'] = $bargain_id;
+        $data['cartInfo'] = $cartInfo;
+        $data['priceGroup'] = $priceGroup;
+        $data['orderKey'] = StoreOrder::cacheOrderInfo($uid, $cartInfo, $priceGroup, $other);
+        $data['offlinePostage'] = $other['offlinePostage'];
+        $vipId = UserLevel::getUserLevel($uid);
+        $user = $request->user();
+        if (isset($user['pwd'])) unset($user['pwd']);
+        $user['vip'] = $vipId !== false ? true : false;
+        if ($user['vip']) {
+            $user['vip_id'] = $vipId;
+            $user['discount'] = UserLevel::getUserLevelInfo($vipId, 'discount');
+        }
+        $data['userInfo'] = $user;
+        $data['integralRatio'] = $other['integralRatio'];
+        $data['offline_pay_status'] = (int)sys_config('offline_pay_status') ?? (int)2;
+        $data['store_self_mention'] = (int)sys_config('store_self_mention') ?? 0;//门店自提是否开启
+        $data['system_store'] = ($res = SystemStore::getStoreDispose()) ? $res : [];//门店信息
+        return app('json')->successful($data);
+    }
+
+    /**
+     * 计算订单金额
+     * @param Request $request
+     * @param $key
+     * @return mixed
+     * @throws \think\Exception
+     * @throws \think\db\exception\DataNotFoundException
+     * @throws \think\db\exception\ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+    public function computedOrder(Request $request, $key)
+    {
+
+//        $priceGroup = StoreOrder::getOrderPriceGroup($cartInfo);
+        if (!$key) return app('json')->fail('参数错误!');
+        $uid = $request->uid();
+        if (StoreOrder::be(['order_id|unique' => $key, 'uid' => $uid, 'is_del' => 0]))
+            return app('json')->status('extend_order', '订单已生成', ['orderId' => $key, 'key' => $key]);
+        list($addressId, $couponId, $payType, $useIntegral, $mark, $combinationId, $pinkId, $seckill_id, $formId, $bargainId, $shipping_type) = UtilService::postMore([
+            'addressId', 'couponId', ['payType', 'yue'], ['useIntegral', 0], 'mark', ['combinationId', 0], ['pinkId', 0], ['seckill_id', 0], ['formId', ''], ['bargainId', ''],
+            ['shipping_type', 1],
+        ], $request, true);
+        $payType = strtolower($payType);
+        if ($bargainId) {
+            $bargainUserTableId = StoreBargainUser::getBargainUserTableId($bargainId, $uid);//TODO 获取用户参与砍价表编号
+            if (!$bargainUserTableId)
+                return app('json')->fail('砍价失败');
+            $status = StoreBargainUser::getBargainUserStatusEnd($bargainUserTableId);
+            if ($status == 3)
+                return app('json')->fail('砍价已支付');
+            StoreBargainUser::setBargainUserStatus($bargainId, $uid); //修改砍价状态
+        }
+        if ($pinkId) {
+            if (StorePink::getIsPinkUid($pinkId, $request->uid()))
+                return app('json')->status('ORDER_EXIST', '订单生成失败,你已经在该团内不能再参加了', ['orderId' => StoreOrder::getStoreIdPink($pinkId, $request->uid())]);
+            if (StoreOrder::getIsOrderPink($pinkId, $request->uid()))
+                return app('json')->status('ORDER_EXIST', '订单生成失败,你已经参加该团了,请先支付订单', ['orderId' => StoreOrder::getStoreIdPink($pinkId, $request->uid())]);
+        }
+        $priceGroup = StoreOrder::cacheKeyCreateOrder($request->uid(), $key, $addressId, $payType, (int)$useIntegral, $couponId, $mark, $combinationId, $pinkId, $seckill_id, $bargainId, true, 0, $shipping_type);
+        if ($priceGroup)
+            return app('json')->status('NONE', 'ok', $priceGroup);
+        else
+            return app('json')->fail(StoreOrder::getErrorInfo('计算失败'));
+    }
+
+    /**
+     * 订单创建
+     * @param Request $request
+     * @param $key
+     * @return mixed
+     * @throws \think\Exception
+     * @throws \think\db\exception\DataNotFoundException
+     * @throws \think\db\exception\ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+    public function create(Request $request, $key)
+    {
+        if (!$key) return app('json')->fail('参数错误!');
+        $uid = $request->uid();
+        if (StoreOrder::be(['order_id|unique' => $key, 'uid' => $uid, 'is_del' => 0]))
+            return app('json')->status('extend_order', '订单已生成', ['orderId' => $key, 'key' => $key]);
+        list($addressId, $couponId, $payType, $useIntegral, $mark, $combinationId, $pinkId, $seckill_id, $formId, $bargainId, $from, $shipping_type, $real_name, $phone, $storeId) = UtilService::postMore([
+            'addressId', 'couponId', 'payType', ['useIntegral', 0], 'mark', ['combinationId', 0], ['pinkId', 0], ['seckill_id', 0], ['formId', ''], ['bargainId', ''], ['from', 'weixin'],
+            ['shipping_type', 1], ['real_name', ''], ['phone', ''], ['store_id', 0]
+        ], $request, true);
+        $payType = strtolower($payType);
+        if ($bargainId) {
+            $bargainUserTableId = StoreBargainUser::getBargainUserTableId($bargainId, $uid);//TODO 获取用户参与砍价表编号
+            if (!$bargainUserTableId)
+                return app('json')->fail('砍价失败');
+            $status = StoreBargainUser::getBargainUserStatusEnd($bargainUserTableId);
+            if ($status == 3)
+                return app('json')->fail('砍价已支付');
+            StoreBargainUser::setBargainUserStatus($bargainId, $uid); //修改砍价状态
+        }
+        if ($pinkId) {
+            if (StorePink::getIsPinkUid($pinkId, $request->uid()))
+                return app('json')->status('ORDER_EXIST', '订单生成失败,你已经在该团内不能再参加了', ['orderId' => StoreOrder::getStoreIdPink($pinkId, $request->uid())]);
+            if (StoreOrder::getIsOrderPink($pinkId, $request->uid()))
+                return app('json')->status('ORDER_EXIST', '订单生成失败,你已经参加该团了,请先支付订单', ['orderId' => StoreOrder::getStoreIdPink($pinkId, $request->uid())]);
+        }
+        $isChannel = 1;
+        if ($from == 'weixin')
+            $isChannel = 0;
+        elseif ($from == 'weixinh5')
+            $isChannel = 2;
+        $order = StoreOrder::cacheKeyCreateOrder($request->uid(), $key, $addressId, $payType, (int)$useIntegral, $couponId, $mark, $combinationId, $pinkId, $seckill_id, $bargainId, false, $isChannel, $shipping_type, $real_name, $phone, $storeId);
+        if ($order === false) return app('json')->fail(StoreOrder::getErrorInfo('订单生成失败'));
+        $orderId = $order['order_id'];
+        $info = compact('orderId', 'key');
+        if ($orderId) {
+            event('OrderCreated', [$order]); //订单创建成功事件
+            event('ShortMssageSend', [$orderId, 'AdminPlaceAnOrder']);//发送管理员通知
+            switch ($payType) {
+                case "weixin":
+                    $orderInfo = StoreOrder::where('order_id', $orderId)->find();
+                    if (!$orderInfo || !isset($orderInfo['paid'])) return app('json')->fail('支付订单不存在!');
+                    $orderInfo = $orderInfo->toArray();
+                    if ($orderInfo['paid']) return app('json')->fail('支付已支付!');
+                    //支付金额为0
+                    if (bcsub((float)$orderInfo['pay_price'], 0, 2) <= 0) {
+                        //创建订单jspay支付
+                        $payPriceStatus = StoreOrder::jsPayPrice($orderId, $uid, $formId);
+                        if ($payPriceStatus)//0元支付成功
+                            return app('json')->status('success', '微信支付成功', $info);
+                        else
+                            return app('json')->status('pay_error', StoreOrder::getErrorInfo());
+                    } else {
+                        try {
+                            if ($from == 'routine') {
+                                $jsConfig = OrderRepository::jsPay($orderId); //创建订单jspay
+                            } else if ($from == 'weixinh5') {
+                                $jsConfig = OrderRepository::h5Pay($orderId);
+                            } else {
+                                $jsConfig = OrderRepository::wxPay($orderId);
+                            }
+                        } catch (\Exception $e) {
+                            return app('json')->status('pay_error', $e->getMessage(), $info);
+                        }
+                        $info['jsConfig'] = $jsConfig;
+                        if ($from == 'weixinh5') {
+                            return app('json')->status('wechat_h5_pay', '订单创建成功', $info);
+                        } else {
+                            return app('json')->status('wechat_pay', '订单创建成功', $info);
+                        }
+                    }
+                    break;
+
+                case "ali":
+                    $orderInfo = StoreOrder::where('order_id', $orderId)->find();
+                    if (!$orderInfo || !isset($orderInfo['paid'])) return app('json')->fail('支付订单不存在!');
+                    $orderInfo = $orderInfo->toArray();
+                    if ($orderInfo['paid']) return app('json')->fail('支付已支付!');
+                    //支付金额为0
+                    if (bcsub((float)$orderInfo['pay_price'], 0, 2) <= 0) {
+                        //创建订单jspay支付
+                        $payPriceStatus = StoreOrder::jsPayPrice($orderId, $request->uid());
+                        if ($payPriceStatus)//0元支付成功
+                            return app('json')->status('success', '支付成功');
+                        else
+                            return app('json')->status('pay_error', StoreOrder::getErrorInfo());
+                    } else {
+                        try {
+                            $jsConfig = OrderRepository::aliPay($orderId); //创建订单jspay
+                        } catch (\Exception $e) {
+                            return app('json')->status('pay_error', $e->getMessage());
+                        }
+                        $info['jsConfig'] = $jsConfig;
+                        return app('json')->status('ali_pay', '订单创建成功', $info);
+                    }
+                    break;
+                case 'yue':
+                    if (StoreOrder::yuePay($orderId, $request->uid(), $formId))
+                        return app('json')->status('success', '余额支付成功', $info);
+                    else {
+                        $errorinfo = StoreOrder::getErrorInfo();
+                        if (is_array($errorinfo))
+                            return app('json')->status($errorinfo['status'], $errorinfo['msg'], $info);
+                        else
+                            return app('json')->status('pay_error', $errorinfo);
+                    }
+                    break;
+                case 'offline':
+                    return app('json')->status('success', '订单创建成功', $info);
+                    break;
+            }
+        } else return app('json')->fail(StoreOrder::getErrorInfo('订单生成失败!'));
+    }
+
+    /**
+     * 订单 再次下单
+     * @param Request $request
+     * @return mixed
+     */
+    public function again(Request $request)
+    {
+        list($uni) = UtilService::postMore([
+            ['uni', ''],
+        ], $request, true);
+        if (!$uni) return app('json')->fail('参数错误!');
+        $order = StoreOrder::getUserOrderDetail($request->uid(), $uni);
+        if (!$order) return app('json')->fail('订单不存在!');
+        $order = StoreOrder::tidyOrder($order, true);
+        $res = [];
+        foreach ($order['cartInfo'] as $v) {
+            if ($v['combination_id']) return app('json')->fail('拼团产品不能再来一单,请在拼团产品内自行下单!');
+            else if ($v['bargain_id']) return app('json')->fail('砍价产品不能再来一单,请在砍价产品内自行下单!');
+            else if ($v['seckill_id']) return app('json')->ail('秒杀产品不能再来一单,请在秒杀产品内自行下单!');
+            else $res[] = StoreCart::setCart($request->uid(), $v['product_id'], $v['cart_num'], isset($v['productInfo']['attrInfo']['unique']) ? $v['productInfo']['attrInfo']['unique'] : '', 'product', 0, 0);
+        }
+        $cateId = [];
+        foreach ($res as $v) {
+            if (!$v) return app('json')->fail('再来一单失败,请重新下单!');
+            $cateId[] = $v['id'];
+        }
+        event('OrderCreateAgain', implode(',', $cateId));
+        return app('json')->successful('ok', ['cateId' => implode(',', $cateId)]);
+    }
+
+
+    /**
+     * 订单支付
+     * @param Request $request
+     * @return mixed
+     */
+    public function pay(Request $request)
+    {
+        list($uni, $paytype, $from) = UtilService::postMore([
+            ['uni', ''],
+            ['paytype', 'weixin'],
+            ['from', 'weixin']
+        ], $request, true);
+        if (!$uni) return app('json')->fail('参数错误!');
+        $order = StoreOrder::getUserOrderDetail($request->uid(), $uni);
+        if (!$order)
+            return app('json')->fail('订单不存在!');
+        if ($order['paid'])
+            return app('json')->fail('该订单已支付!');
+        if ($order['pink_id']) if (StorePink::isPinkStatus($order['pink_id']))
+            return app('json')->fail('该订单已失效!');
+
+        if ($from == 'weixin') {//0
+            if (in_array($order->is_channel, [1, 2]))
+                $order['order_id'] = mt_rand(100, 999) . '_' . $order['order_id'];
+        }
+        if ($from == 'weixinh5') {//2
+            if (in_array($order->is_channel, [0, 1]))
+                $order['order_id'] = mt_rand(100, 999) . '_' . $order['order_id'];
+        }
+        if ($from == 'routine') {//1
+            if (in_array($order->is_channel, [0, 2]))
+                $order['order_id'] = mt_rand(100, 999) . '_' . $order['order_id'];
+        }
+
+        $order['pay_type'] = $paytype; //重新支付选择支付方式
+        switch ($order['pay_type']) {
+            case 'weixin':
+                try {
+                    if ($from == 'routine') {
+                        $jsConfig = OrderRepository::jsPay($order); //订单列表发起支付
+                    } else if ($from == 'weixinh5') {
+                        $jsConfig = OrderRepository::h5Pay($order);
+                    } else {
+                        $jsConfig = OrderRepository::wxPay($order);
+                    }
+                } catch (\Exception $e) {
+                    return app('json')->fail($e->getMessage());
+                }
+                if ($from == 'weixinh5') {
+                    return app('json')->status('wechat_h5_pay', ['jsConfig' => $jsConfig, 'order_id' => $order['order_id']]);
+                } else {
+                    return app('json')->status('wechat_pay', ['jsConfig' => $jsConfig, 'order_id' => $order['order_id']]);
+                }
+                break;
+            case 'yue':
+                if (StoreOrder::yuePay($order['order_id'], $request->uid()))
+                    return app('json')->status('success', '余额支付成功');
+                else {
+                    $error = StoreOrder::getErrorInfo();
+                    return app('json')->fail(is_array($error) && isset($error['msg']) ? $error['msg'] : $error);
+                }
+                break;
+            case 'ztpay':
+                $gm = new Gmdemo();
+                $data = [
+                    'mechNo' => 123456,// 商户号
+                    'inetNo' => $order['order_id'],//订单号
+                    'sndTmstmp' => date('YmdHis', time()),
+                    'pdDsc' => '=商品购买',
+                    'pymntAmt' => $order['pay_price'] * 100, // 交 易 单 位 为 分
+                    'ccy' => 156,
+                    'channelCode' => ''//渠道号
+                ];
+                $res = $gm->scanPaymentCode($data);
+                halt($res);
+
+            case 'offline':
+                StoreOrder::createOrderTemplate($order);
+                if (StoreOrder::setOrderTypePayOffline($order['order_id']))
+                    return app('json')->status('success', '订单创建成功');
+                else
+                    return app('json')->status('success', '支付失败');
+                break;
+            case "ali":
+                $orderInfo = StoreOrder::where('order_id', $order['order_id'])->find();
+                if (!$orderInfo || !isset($orderInfo['paid'])) return app('json')->fail('支付订单不存在!');
+                $orderInfo = $orderInfo->toArray();
+                if ($orderInfo['paid']) return app('json')->fail('支付已支付!');
+                //支付金额为0
+                if (bcsub((float)$orderInfo['pay_price'], 0, 2) <= 0) {
+                    //创建订单jspay支付
+                    $payPriceStatus = StoreOrder::jsPayPrice($order['order_id'], $request->uid());
+                    if ($payPriceStatus)//0元支付成功
+                        return app('json')->status('success', '支付成功');
+                    else
+                        return app('json')->status('pay_error', StoreOrder::getErrorInfo());
+                } else {
+                    try {
+                        $jsConfig = OrderRepository::aliPay($order['order_id']); //创建订单jspay
+                    } catch (\Exception $e) {
+                        return app('json')->status('pay_error', $e->getMessage());
+                    }
+                    $info['jsConfig'] = $jsConfig;
+                    return app('json')->status('ali_pay', '订单创建成功', $info);
+                }
+                break;
+        }
+        return app('json')->fail('支付方式错误');
+    }
+
+    /**
+     * 订单列表
+     * @param Request $request
+     * @return mixed
+     */
+    public function lst(Request $request)
+    {
+        list($type, $page, $limit, $search) = UtilService::getMore([
+            ['type', ''],
+            ['page', 0],
+            ['limit', ''],
+            ['search', ''],
+        ], $request, true);
+        return app('json')->successful(StoreOrder::getUserOrderSearchList($request->uid(), $type, $page, $limit, $search));
+    }
+
+    /**
+     * 订单详情
+     * @param Request $request
+     * @param $uni
+     * @return mixed
+     */
+    public function detail(Request $request, $uni)
+    {
+        if (!strlen(trim($uni))) return app('json')->fail('参数错误');
+        $order = StoreOrder::getUserOrderDetail($request->uid(), $uni);
+        if (!$order) return app('json')->fail('订单不存在');
+        $order = $order->toArray();
+        //是否开启门店自提
+        $store_self_mention = sys_config('store_self_mention');
+        //关闭门店自提后 订单隐藏门店信息
+        if ($store_self_mention == 0) $order['shipping_type'] = 1;
+        if ($order['verify_code']) {
+            $verify_code = $order['verify_code'];
+            $verify[] = substr($verify_code, 0, 4);
+            $verify[] = substr($verify_code, 4, 4);
+            $verify[] = substr($verify_code, 8);
+            $order['_verify_code'] = implode(' ', $verify);
+        }
+        $order['add_time_y'] = date('Y-m-d', $order['add_time']);
+        $order['add_time_h'] = date('H:i:s', $order['add_time']);
+        $order['system_store'] = SystemStore::getStoreDispose($order['store_id']);
+        if ($order['shipping_type'] === 2 && $order['verify_code']) {
+            $name = $order['verify_code'] . '.jpg';
+            $imageInfo = SystemAttachment::getInfo($name, 'name');
+            $siteUrl = sys_config('site_url');
+            if (!$imageInfo) {
+                $imageInfo = UtilService::getQRCodePath($order['verify_code'], $name);
+                if (is_array($imageInfo)) {
+                    SystemAttachment::attachmentAdd($imageInfo['name'], $imageInfo['size'], $imageInfo['type'], $imageInfo['dir'], $imageInfo['thumb_path'], 1, $imageInfo['image_type'], $imageInfo['time'], 2);
+                    $url = $imageInfo['dir'];
+                } else
+                    $url = '';
+            } else $url = $imageInfo['att_dir'];
+            if (isset($imageInfo['image_type']) && $imageInfo['image_type'] == 1) $url = $siteUrl . $url;
+            $order['code'] = $url;
+        }
+        $order['mapKey'] = sys_config('tengxun_map_key');
+        return app('json')->successful('ok', StoreOrder::tidyOrder($order, true, true));
+    }
+
+    /**
+     * 订单删除
+     * @param Request $request
+     * @return mixed
+     */
+    public function del(Request $request)
+    {
+        list($uni) = UtilService::postMore([
+            ['uni', ''],
+        ], $request, true);
+        if (!$uni) return app('json')->fail('参数错误!');
+        $res = StoreOrder::removeOrder($uni, $request->uid());
+        if ($res)
+            return app('json')->successful();
+        else
+            return app('json')->fail(StoreOrder::getErrorInfo());
+    }
+
+    /**
+     * 订单收货
+     * @param Request $request
+     * @return mixed
+     */
+    public function take(Request $request)
+    {
+        list($uni) = UtilService::postMore([
+            ['uni', ''],
+        ], $request, true);
+        if (!$uni) return app('json')->fail('参数错误!');
+        $res = StoreOrder::takeOrder($uni, $request->uid());
+        if ($res) {
+            $order_info = StoreOrder::where('order_id', $uni)->find();
+            $gain_integral = intval($order_info['gain_integral']);
+
+            $gain_coupon = StoreCouponIssue::alias('a')
+                ->join('store_coupon b', 'a.cid = b.id')
+                ->where('a.status', 1)
+                ->where('a.is_full_give', 1)
+                ->where('a.is_del', 0)
+                ->where('a.full_reduction', '<=', $order_info['total_price'])
+                ->sum('b.coupon_price');
+
+            return app('json')->successful(['gain_integral' => $gain_integral, 'gain_coupon' => $gain_coupon]);
+        } else
+            return app('json')->fail(StoreOrder::getErrorInfo());
+    }
+
+
+    /**
+     * 订单 查看物流
+     * @param Request $request
+     * @param $uni
+     * @return mixed
+     */
+    public function express(Request $request, $uni)
+    {
+        if (!$uni || !($order = StoreOrder::getUserOrderDetail($request->uid(), $uni))) return app('json')->fail('查询订单不存在!');
+        if ($order['delivery_type'] != 'express' || !$order['delivery_id']) return app('json')->fail('该订单不存在快递单号!');
+        $cacheName = $uni . $order['delivery_id'];
+        $result = CacheService::get($cacheName, null);
+        if ($result === NULL) {
+            $result = ExpressService::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);
+        }
+        $orderInfo = [];
+        $cartInfo = StoreOrderCartInfo::where('oid', $order['id'])->column('cart_info', 'unique') ?? [];
+        $info = [];
+        $cartNew = [];
+        foreach ($cartInfo as $k => $cart) {
+            $cart = json_decode($cart, true);
+            $cartNew['cart_num'] = $cart['cart_num'];
+            $cartNew['truePrice'] = $cart['truePrice'];
+            $cartNew['productInfo']['image'] = $cart['productInfo']['image'];
+            $cartNew['productInfo']['store_name'] = $cart['productInfo']['store_name'];
+            $cartNew['productInfo']['unit_name'] = $cart['productInfo']['unit_name'] ?? '';
+            array_push($info, $cartNew);
+            unset($cart);
+        }
+        $orderInfo['delivery_id'] = $order['delivery_id'];
+        $orderInfo['delivery_name'] = $order['delivery_name'];
+        $orderInfo['delivery_type'] = $order['delivery_type'];
+        $orderInfo['cartInfo'] = $info;
+        return app('json')->successful(['order' => $orderInfo, 'express' => $result ? $result : []]);
+    }
+
+    /**
+     * 订单评价
+     * @param Request $request
+     * @return mixed
+     * @throws \think\db\exception\DataNotFoundException
+     * @throws \think\db\exception\ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+    public function comment(Request $request)
+    {
+        $group = UtilService::postMore([
+            ['unique', ''], ['comment', ''], ['pics', ''], ['product_score', 5], ['service_score', 5]
+        ], $request);
+        $unique = $group['unique'];
+        unset($group['unique']);
+        if (!$unique) return app('json')->fail('参数错误!');
+        $cartInfo = StoreOrderCartInfo::where('unique', $unique)->find();
+        $uid = $request->uid();
+        $user_info = User::get($uid);
+        $group['nickname'] = $user_info['nickname'];
+        $group['avatar'] = $user_info['avatar'];
+        if (!$cartInfo) return app('json')->fail('评价产品不存在!');
+        $orderUid = StoreOrder::getOrderInfo($cartInfo['oid'], 'uid')['uid'];
+        if ($uid != $orderUid) return app('json')->fail('评价产品不存在!');
+        if (StoreProductReply::be(['oid' => $cartInfo['oid'], 'unique' => $unique]))
+            return app('json')->fail('该产品已评价!');
+        $group['comment'] = htmlspecialchars(trim($group['comment']));
+        if ($group['product_score'] < 1) return app('json')->fail('请为产品评分');
+        else if ($group['service_score'] < 1) return app('json')->fail('请为商家服务评分');
+        if ($cartInfo['cart_info']['combination_id']) $productId = $cartInfo['cart_info']['product_id'];
+        else if ($cartInfo['cart_info']['seckill_id']) $productId = $cartInfo['cart_info']['product_id'];
+        else if ($cartInfo['cart_info']['bargain_id']) $productId = $cartInfo['cart_info']['product_id'];
+        else $productId = $cartInfo['product_id'];
+        if ($group['pics']) $group['pics'] = json_encode(is_array($group['pics']) ? $group['pics'] : explode(',', $group['pics']));
+        $group = array_merge($group, [
+            'uid' => $uid,
+            'oid' => $cartInfo['oid'],
+            'unique' => $unique,
+            'product_id' => $productId,
+            'add_time' => time(),
+            'reply_type' => 'product'
+        ]);
+        StoreProductReply::beginTrans();
+        $res = StoreProductReply::reply($group, 'product');
+        if (!$res) {
+            StoreProductReply::rollbackTrans();
+            return app('json')->fail('评价失败!');
+        }
+        try {
+            StoreOrder::checkOrderOver($cartInfo['oid']);
+        } catch (\Exception $e) {
+            StoreProductReply::rollbackTrans();
+            return app('json')->fail($e->getMessage());
+        }
+        StoreProductReply::commitTrans();
+        event('UserCommented', $res);
+        event('AdminNewPush');
+        return app('json')->successful();
+    }
+
+    /**
+     * 订单统计数据
+     * @param Request $request
+     * @return mixed
+     */
+    public function data(Request $request)
+    {
+        return app('json')->successful(StoreOrder::getOrderData($request->uid()));
+    }
+
+    /**
+     * 订单退款理由
+     * @return mixed
+     */
+    public function refund_reason()
+    {
+        $reason = sys_config('stor_reason') ?: [];//退款理由
+        $reason = str_replace("\r\n", "\n", $reason);//防止不兼容
+        $reason = explode("\n", $reason);
+        return app('json')->successful($reason);
+    }
+
+    /**
+     * 订单退款审核
+     * @param Request $request
+     * @return mixed
+     */
+    public function refund_verify(Request $request)
+    {
+        $data = UtilService::postMore([
+            ['text', ''],
+            ['refund_reason_wap_img', ''],
+            ['refund_reason_wap_explain', ''],
+            ['uni', '']
+        ], $request);
+        $uni = $data['uni'];
+        unset($data['uni']);
+        if ($data['refund_reason_wap_img']) $data['refund_reason_wap_img'] = explode(',', $data['refund_reason_wap_img']);
+        if (!$uni || $data['text'] == '') return app('json')->fail('参数错误!');
+        $res = StoreOrder::orderApplyRefund($uni, $request->uid(), $data['text'], $data['refund_reason_wap_explain'], $data['refund_reason_wap_img']);
+        if ($res)
+            return app('json')->successful('提交申请成功');
+        else
+            return app('json')->fail(StoreOrder::getErrorInfo());
+    }
+
+
+    /**
+     * 订单取消   未支付的订单回退积分,回退优惠券,回退库存
+     * @param Request $request
+     * @return mixed
+     * @throws \think\db\exception\DataNotFoundException
+     * @throws \think\db\exception\ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+    public function cancel(Request $request)
+    {
+        list($id) = UtilService::postMore([['id', 0]], $request, true);
+        if (!$id) return app('json')->fail('参数错误');
+        if (StoreOrder::cancelOrder($id, $request->uid()))
+            return app('json')->successful('取消订单成功');
+        return app('json')->fail(StoreOrder::getErrorInfo('取消订单失败'));
+    }
+
+
+    /**
+     * 订单产品信息
+     * @param Request $request
+     * @return mixed
+     * @throws \think\db\exception\DataNotFoundException
+     * @throws \think\db\exception\ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+    public function product(Request $request)
+    {
+        list($unique) = UtilService::postMore([['unique', '']], $request, true);
+        if (!$unique || !StoreOrderCartInfo::be(['unique' => $unique]) || !($cartInfo = StoreOrderCartInfo::where('unique', $unique)->find())) return app('json')->fail('评价产品不存在!');
+        $cartInfo = $cartInfo->toArray();
+        $cartProduct = [];
+        $cartProduct['cart_num'] = $cartInfo['cart_info']['cart_num'];
+        $cartProduct['productInfo']['image'] = isset($cartInfo['cart_info']['productInfo']['image']) ? $cartInfo['cart_info']['productInfo']['image'] : '';
+        $cartProduct['productInfo']['price'] = isset($cartInfo['cart_info']['productInfo']['price']) ? $cartInfo['cart_info']['productInfo']['price'] : 0;
+        $cartProduct['productInfo']['store_name'] = isset($cartInfo['cart_info']['productInfo']['store_name']) ? $cartInfo['cart_info']['productInfo']['store_name'] : '';
+        if (isset($cartInfo['cart_info']['productInfo']['attrInfo'])) {
+            $cartProduct['productInfo']['attrInfo']['product_id'] = isset($cartInfo['cart_info']['productInfo']['attrInfo']['product_id']) ? $cartInfo['cart_info']['productInfo']['attrInfo']['product_id'] : '';
+            $cartProduct['productInfo']['attrInfo']['suk'] = isset($cartInfo['cart_info']['productInfo']['attrInfo']['suk']) ? $cartInfo['cart_info']['productInfo']['attrInfo']['suk'] : '';
+            $cartProduct['productInfo']['attrInfo']['price'] = isset($cartInfo['cart_info']['productInfo']['attrInfo']['price']) ? $cartInfo['cart_info']['productInfo']['attrInfo']['price'] : '';
+            $cartProduct['productInfo']['attrInfo']['image'] = isset($cartInfo['cart_info']['productInfo']['attrInfo']['image']) ? $cartInfo['cart_info']['productInfo']['attrInfo']['image'] : '';
+        }
+        $cartProduct['product_id'] = isset($cartInfo['cart_info']['product_id']) ? $cartInfo['cart_info']['product_id'] : 0;
+        $cartProduct['combination_id'] = isset($cartInfo['cart_info']['combination_id']) ? $cartInfo['cart_info']['combination_id'] : 0;
+        $cartProduct['seckill_id'] = isset($cartInfo['cart_info']['seckill_id']) ? $cartInfo['cart_info']['seckill_id'] : 0;
+        $cartProduct['bargain_id'] = isset($cartInfo['cart_info']['bargain_id']) ? $cartInfo['cart_info']['bargain_id'] : 0;
+        $cartProduct['order_id'] = StoreOrder::where('id', $cartInfo['oid'])->value('order_id');
+        return app('json')->successful($cartProduct);
+    }
+
+    /**
+     * 首页获取未支付订单
+     */
+    public function get_noPay(Request $request)
+    {
+        return app('json')->successful(StoreOrder::getUserOrderSearchList($request->uid(), 0, 0, 0, ''));
+    }
+>>>>>>> 386b37d33e5ba817cba00df29efaefbd692e4dd1
 }

+ 7 - 0
app/api/controller/phpcrypto.php

@@ -20,8 +20,11 @@ function hex2string($hex){
 	return $string;
 }
 */
+<<<<<<< HEAD
 
  
+=======
+>>>>>>> 386b37d33e5ba817cba00df29efaefbd692e4dd1
 if(!extension_loaded('phpcrypto')) {
     dl('phpcrypto.so');
 }
@@ -38,7 +41,11 @@ echo "\n";
 function test_php_crypto_init(){
     $php_func = 'php_crypto_init';
     echo "--------$php_func--------\n";
+<<<<<<< HEAD
     $path = "/www/wwwroot/hgd.liuniu946.com/public/opt/php/libcryptAPIsm_lnx64.so";//国密动态库路径
+=======
+    $path = "/opt/php/libcryptAPIsm_lnx64.so";//国密动态库路径
+>>>>>>> 386b37d33e5ba817cba00df29efaefbd692e4dd1
     $recode = $php_func($path);
     echo "recode:$recode \n";//如果非零,则加载失败
 }

+ 622 - 0
app/api/controller/user/UserController.php

@@ -1,3 +1,4 @@
+<<<<<<< HEAD
 <?php
 
 namespace app\api\controller\user;
@@ -617,4 +618,625 @@ class UserController
         $puid = $request->post('puid/d', 0);
         return app('json')->success(User::setSpread($puid, $request->uid()));
     }
+=======
+<?php
+
+namespace app\api\controller\user;
+
+use app\http\validates\user\AddressValidate;
+use app\models\system\SystemCity;
+use app\models\user\UserVisit;
+use think\db\exception\DataNotFoundException;
+use think\db\exception\DbException;
+use think\db\exception\ModelNotFoundException;
+use think\exception\ValidateException;
+use app\Request;
+use app\models\user\UserLevel;
+use app\models\user\UserSign;
+use app\models\store\StoreBargain;
+use app\models\store\StoreCombination;
+use app\models\store\StoreCouponUser;
+use app\models\store\StoreOrder;
+use app\models\store\StoreProductRelation;
+use app\models\store\StoreSeckill;
+use app\models\user\User;
+use app\models\user\UserAddress;
+use app\models\user\UserBill;
+use app\models\user\UserExtract;
+use app\models\user\UserNotice;
+use crmeb\services\GroupDataService;
+use crmeb\services\UtilService;
+
+/**
+ * 用户类
+ * Class UserController
+ * @package app\api\controller\store
+ */
+class UserController
+{
+
+    /**
+     * 获取用户信息
+     * @param Request $request
+     * @return mixed
+     */
+    public function userInfo(Request $request)
+    {
+        $info = $request->user()->toArray();
+        $broken_time = intval(sys_config('extract_time'));
+        $search_time = time() - 86400 * $broken_time;
+        //返佣 +
+        $brokerage_commission = UserBill::where(['uid' => $info['uid'], 'category' => 'now_money', 'type' => 'brokerage'])
+            ->where('add_time', '>', $search_time)
+            ->where('pm', 1)
+            ->sum('number');
+        //退款退的佣金 -
+        $refund_commission = UserBill::where(['uid' => $info['uid'], 'category' => 'now_money', 'type' => 'brokerage'])
+            ->where('add_time', '>', $search_time)
+            ->where('pm', 0)
+            ->sum('number');
+        $info['broken_commission'] = bcsub($brokerage_commission, $refund_commission, 2);
+        if ($info['broken_commission'] < 0)
+            $info['broken_commission'] = 0;
+        $info['commissionCount'] = bcsub($info['brokerage_price'], $info['broken_commission'], 2);
+        if ($info['commissionCount'] < 0)
+            $info['commissionCount'] = 0;
+        $uids = User::where('spread_uid', $request->uid())->column('uid');
+        $info['pay_price'] = StoreOrder::where('uid', 'in', $uids)
+            ->where('paid', 1)
+            ->where('is_participate', 0)
+            ->sum('pay_price');
+
+        return app('json')->success($info);
+    }
+
+    /**
+     * 用户资金统计
+     * @param Request $request
+     * @return mixed
+     * @throws \think\Exception
+     * @throws DataNotFoundException
+     * @throws ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+    public function balance(Request $request)
+    {
+        $uid = $request->uid();
+        $user['now_money'] = User::getUserInfo($uid, 'now_money')['now_money'];//当前总资金
+        $user['recharge'] = UserBill::getRecharge($uid);//累计充值
+        $user['orderStatusSum'] = StoreOrder::getOrderStatusSum($uid);//累计消费
+        return app('json')->successful($user);
+    }
+
+    /**
+     * 个人中心
+     * @param Request $request
+     * @return mixed
+     */
+    public function user(Request $request)
+    {
+        $user = $request->user();
+        $user = $user->toArray();
+        $user['couponCount'] = StoreCouponUser::getUserValidCouponCount($user['uid']);
+        $user['like'] = StoreProductRelation::getUserIdCollect($user['uid']);
+        $user['orderStatusNum'] = StoreOrder::getOrderData($user['uid']);
+        $user['notice'] = UserNotice::getNotice($user['uid']);
+        $user['brokerage'] = UserBill::getBrokerage($user['uid']);//获取总佣金
+        $user['recharge'] = UserBill::getRecharge($user['uid']);//累计充值
+        $user['orderStatusSum'] = StoreOrder::getOrderStatusSum($user['uid']);//累计消费
+        $user['extractTotalPrice'] = UserExtract::userExtractTotalPrice($user['uid']);//累计提现
+        $user['extractPrice'] = $user['brokerage_price'];//可提现
+        $user['statu'] = (int)sys_config('store_brokerage_statu');
+        $broken_time = intval(sys_config('extract_time'));
+        $search_time = time() - 86400 * $broken_time;
+        if (!$user['is_promoter'] && $user['statu'] == 2) {
+            $price = StoreOrder::where(['paid' => 1, 'refund_status' => 0, 'uid' => $user['uid']])->sum('pay_price');
+            $status = is_brokerage_statu($price);
+            if ($status) {
+                User::where('uid', $user['uid'])->update(['is_promoter' => 1]);
+                $user['is_promoter'] = 1;
+            } else {
+                $storeBrokeragePrice = sys_config('store_brokerage_price', 0);
+                $user['promoter_price'] = bcsub($storeBrokeragePrice, $price, 2);
+            }
+        }
+        //可提现佣金
+        //返佣 +
+        $brokerage_commission = UserBill::where(['uid' => $user['uid'], 'category' => 'now_money', 'type' => 'brokerage'])
+            ->where('add_time', '>', $search_time)
+            ->where('pm', 1)
+            ->sum('number');
+        //退款退的佣金 -
+        $refund_commission = UserBill::where(['uid' => $user['uid'], 'category' => 'now_money', 'type' => 'brokerage'])
+            ->where('add_time', '>', $search_time)
+            ->where('pm', 0)
+            ->sum('number');
+        $user['broken_commission'] = bcsub($brokerage_commission, $refund_commission, 2);
+        if ($user['broken_commission'] < 0)
+            $user['broken_commission'] = 0;
+        $user['commissionCount'] = bcsub($user['brokerage_price'], $user['broken_commission'], 2);
+        if ($user['commissionCount'] < 0)
+            $user['commissionCount'] = 0;
+        if (!sys_config('vip_open'))
+            $user['vip'] = false;
+        else {
+            $vipId = UserLevel::getUserLevel($user['uid']);
+            $user['vip'] = $vipId !== false ? true : false;
+            if ($user['vip']) {
+                $user['vip_id'] = $vipId;
+                $user['vip_icon'] = UserLevel::getUserLevelInfo($vipId, 'icon');
+                $user['vip_name'] = UserLevel::getUserLevelInfo($vipId, 'name');
+            }
+        }
+        $user['yesterDay'] = UserBill::yesterdayCommissionSum($user['uid']);
+        $user['recharge_switch'] = (int)sys_config('recharge_switch');//充值开关
+        $user['adminid'] = (boolean)\app\models\store\StoreService::orderServiceStatus($user['uid']);
+        if ($user['phone'] && $user['user_type'] != 'h5') {
+            $user['switchUserInfo'][] = $request->user();
+            if ($h5UserInfo = User::where('account', $user['phone'])->where('user_type', 'h5')->find()) {
+                $user['switchUserInfo'][] = $h5UserInfo;
+            }
+        } else if ($user['phone'] && $user['user_type'] == 'h5') {
+            if ($wechatUserInfo = User::where('phone', $user['phone'])->where('user_type', '<>', 'h5')->find()) {
+                $user['switchUserInfo'][] = $wechatUserInfo;
+            }
+            $user['switchUserInfo'][] = $request->user();
+        } else if (!$user['phone']) {
+            $user['switchUserInfo'][] = $request->user();
+        }
+
+        return app('json')->successful($user);
+    }
+
+    /**
+     * 地址 获取单个
+     * @param Request $request
+     * @param $id
+     * @return mixed
+     * @throws DataNotFoundException
+     * @throws ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+    public function address(Request $request, $id)
+    {
+        $addressInfo = [];
+        if ($id && is_numeric($id) && UserAddress::be(['is_del' => 0, 'id' => $id, 'uid' => $request->uid()])) {
+            $addressInfo = UserAddress::find($id)->toArray();
+        }
+        return app('json')->successful($addressInfo);
+    }
+
+    /**
+     * 地址列表
+     * @param Request $request
+     * @param $page
+     * @param $limit
+     * @return mixed
+     */
+    public function address_list(Request $request)
+    {
+        list($page, $limit) = UtilService::getMore([['page', 0], ['limit', 20]], $request, true);
+        $list = UserAddress::getUserValidAddressList($request->uid(), $page, $limit, 'id,real_name,phone,province,city,district,detail,is_default');
+        return app('json')->successful($list);
+    }
+
+    /**
+     * 设置默认地址
+     *
+     * @param Request $request
+     * @return mixed
+     */
+    public function address_default_set(Request $request)
+    {
+        list($id) = UtilService::getMore([['id', 0]], $request, true);
+        if (!$id || !is_numeric($id)) return app('json')->fail('参数错误!');
+        if (!UserAddress::be(['is_del' => 0, 'id' => $id, 'uid' => $request->uid()]))
+            return app('json')->fail('地址不存在!');
+        $res = UserAddress::setDefaultAddress($id, $request->uid());
+        if (!$res)
+            return app('json')->fail('地址不存在!');
+        else
+            return app('json')->successful();
+    }
+
+    /**
+     * 获取默认地址
+     * @param Request $request
+     * @return mixed
+     */
+    public function address_default(Request $request)
+    {
+        $defaultAddress = UserAddress::getUserDefaultAddress($request->uid(), 'id,real_name,phone,province,city,district,detail,is_default');
+        if ($defaultAddress) {
+            $defaultAddress = $defaultAddress->toArray();
+            return app('json')->successful('ok', $defaultAddress);
+        }
+        return app('json')->successful('empty', []);
+    }
+
+    /**
+     * 修改 添加地址
+     * @param Request $request
+     * @return mixed
+     */
+    public function address_edit(Request $request)
+    {
+        $addressInfo = UtilService::postMore([
+            ['address', []],
+            ['is_default', false],
+            ['real_name', ''],
+            ['post_code', ''],
+            ['phone', ''],
+            ['detail', ''],
+            ['id', 0],
+            ['type', 0]
+        ], $request);
+        if (!isset($addressInfo['address']['province'])) return app('json')->fail('收货地址格式错误!');
+        if (!isset($addressInfo['address']['city'])) return app('json')->fail('收货地址格式错误!');
+        if (!isset($addressInfo['address']['district'])) return app('json')->fail('收货地址格式错误!');
+        if (!isset($addressInfo['address']['city_id']) && $addressInfo['type'] == 0) {
+            return app('json')->fail('收货地址格式错误!请重新选择!');
+        } else if ($addressInfo['type'] == 1) {
+            $city = $addressInfo['address']['city'];
+            $cityId = SystemCity::where('name', $city)->where('parent_id', '<>', 0)->value('city_id');
+            if ($cityId) {
+                $addressInfo['address']['city_id'] = $cityId;
+            } else {
+                if (!($cityId = SystemCity::where('parent_id', '<>', 0)->where('name', 'like', "%$city%")->value('city_id'))) {
+                    return app('json')->fail('收货地址格式错误!修改后请重新导入!');
+                }
+                $addressInfo['address']['city_id'] = $cityId;
+            }
+        }
+
+        $addressInfo['province'] = $addressInfo['address']['province'];
+        $addressInfo['city'] = $addressInfo['address']['city'];
+        $addressInfo['city_id'] = $addressInfo['address']['city_id'] ?? 0;
+        $addressInfo['district'] = $addressInfo['address']['district'];
+        $addressInfo['is_default'] = (int)$addressInfo['is_default'] == true ? 1 : 0;
+        $addressInfo['uid'] = $request->uid();
+        unset($addressInfo['address'], $addressInfo['type']);
+        try {
+            validate(AddressValidate::class)->check($addressInfo);
+        } catch (ValidateException $e) {
+            return app('json')->fail($e->getError());
+        }
+        if ($addressInfo['id'] && UserAddress::be(['id' => $addressInfo['id'], 'uid' => $request->uid(), 'is_del' => 0])) {
+            $id = $addressInfo['id'];
+            unset($addressInfo['id']);
+            if (UserAddress::edit($addressInfo, $id, 'id')) {
+                if ($addressInfo['is_default'])
+                    UserAddress::setDefaultAddress($id, $request->uid());
+                return app('json')->successful();
+            } else
+                return app('json')->fail('编辑收货地址失败!');
+        } else {
+            $addressInfo['add_time'] = time();
+            if ($address = UserAddress::create($addressInfo)) {
+                if ($addressInfo['is_default']) {
+                    UserAddress::setDefaultAddress($address->id, $request->uid());
+                }
+                return app('json')->successful(['id' => $address->id]);
+            } else {
+                return app('json')->fail('添加收货地址失败!');
+            }
+        }
+    }
+
+    /**
+     * 删除地址
+     *
+     * @param Request $request
+     * @return mixed
+     */
+    public function address_del(Request $request)
+    {
+        list($id) = UtilService::postMore([['id', 0]], $request, true);
+        if (!$id || !is_numeric($id)) return app('json')->fail('参数错误!');
+        if (!UserAddress::be(['is_del' => 0, 'id' => $id, 'uid' => $request->uid()]))
+            return app('json')->fail('地址不存在!');
+        if (UserAddress::edit(['is_del' => '1'], $id, 'id'))
+            return app('json')->successful();
+        else
+            return app('json')->fail('删除地址失败!');
+    }
+
+
+    /**
+     * 获取收藏产品
+     *
+     * @param Request $request
+     * @return mixed
+     */
+    public function collect_user(Request $request)
+    {
+        list($page, $limit) = UtilService::getMore([
+            ['page', 0],
+            ['limit', 0]
+        ], $request, true);
+        if (!(int)$limit) return app('json')->successful([]);
+        $productRelationList = StoreProductRelation::getUserCollectProduct($request->uid(), (int)$page, (int)$limit);
+        return app('json')->successful($productRelationList);
+    }
+
+    /**
+     * 添加收藏
+     * @param Request $request
+     * @param $id
+     * @param $category
+     * @return mixed
+     */
+    public function collect_add(Request $request)
+    {
+        list($id, $category) = UtilService::postMore([['id', 0], ['category', 'product']], $request, true);
+        if (!$id || !is_numeric($id)) return app('json')->fail('参数错误');
+        $res = StoreProductRelation::productRelation($id, $request->uid(), 'collect', $category);
+        if (!$res) return app('json')->fail(StoreProductRelation::getErrorInfo());
+        else return app('json')->successful();
+    }
+
+    /**
+     * 取消收藏
+     *
+     * @param Request $request
+     * @return mixed
+     */
+    public function collect_del(Request $request)
+    {
+        list($id, $category) = UtilService::postMore([['id', 0], ['category', 'product']], $request, true);
+        if (!$id || !is_numeric($id)) return app('json')->fail('参数错误');
+        $res = StoreProductRelation::unProductRelation($id, $request->uid(), 'collect', $category);
+        if (!$res) return app('json')->fail(StoreProductRelation::getErrorInfo());
+        else return app('json')->successful();
+    }
+
+    /**
+     * 批量收藏
+     * @param Request $request
+     * @return mixed
+     */
+    public function collect_all(Request $request)
+    {
+        $collectInfo = UtilService::postMore([
+            ['id', []],
+            ['category', 'product'],
+        ], $request);
+        if (!count($collectInfo['id'])) return app('json')->fail('参数错误');
+        $productIdS = $collectInfo['id'];
+        $res = StoreProductRelation::productRelationAll($productIdS, $request->uid(), 'collect', $collectInfo['category']);
+        if (!$res) return app('json')->fail(StoreProductRelation::getErrorInfo());
+        else return app('json')->successful('收藏成功');
+    }
+
+    /**
+     * 添加点赞
+     *
+     * @param Request $request
+     * @return mixed
+     */
+//    public function like_add(Request $request)
+//    {
+//        list($id, $category) = UtilService::postMore([['id',0], ['category','product']], $request, true);
+//        if(!$id || !is_numeric($id))  return app('json')->fail('参数错误');
+//        $res = StoreProductRelation::productRelation($id,$request->uid(),'like',$category);
+//        if(!$res) return  app('json')->fail(StoreProductRelation::getErrorInfo());
+//        else return app('json')->successful();
+//    }
+
+    /**
+     * 取消点赞
+     *
+     * @param Request $request
+     * @return mixed
+     */
+//    public function like_del(Request $request)
+//    {
+//        list($id, $category) = UtilService::postMore([['id',0], ['category','product']], $request, true);
+//        if(!$id || !is_numeric($id)) return app('json')->fail('参数错误');
+//        $res = StoreProductRelation::unProductRelation($id, $request->uid(),'like',$category);
+//        if(!$res) return app('json')->fail(StoreProductRelation::getErrorInfo());
+//        else return app('json')->successful();
+//    }
+
+    /**
+     * 签到 配置
+     * @return mixed
+     * @throws DataNotFoundException
+     * @throws ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+    public function sign_config()
+    {
+        $signConfig = sys_data('sign_day_num') ?? [];
+        return app('json')->successful($signConfig);
+    }
+
+    /**
+     * 签到 列表
+     * @param Request $request
+     * @param $page
+     * @param $limit
+     * @return mixed
+     */
+    public function sign_list(Request $request)
+    {
+        list($page, $limit) = UtilService::getMore([
+            ['page', 0],
+            ['limit', 0]
+        ], $request, true);
+        if (!$limit) return app('json')->successful([]);
+        $signList = UserSign::getSignList($request->uid(), (int)$page, (int)$limit);
+        if ($signList) $signList = $signList->toArray();
+        return app('json')->successful($signList);
+    }
+
+    /**
+     * 签到
+     * @param Request $request
+     * @return mixed
+     */
+    public function sign_integral(Request $request)
+    {
+        $signed = UserSign::getIsSign($request->uid());
+        if ($signed) return app('json')->fail('已签到');
+        if (false !== ($integral = UserSign::sign($request->uid())))
+            return app('json')->successful('签到获得' . floatval($integral) . '积分', ['integral' => $integral]);
+        return app('json')->fail(UserSign::getErrorInfo('签到失败'));
+    }
+
+    /**
+     * 签到用户信息
+     * @param Request $request
+     * @return mixed
+     */
+    public function sign_user(Request $request)
+    {
+        list($sign, $integral, $all) = UtilService::postMore([
+            ['sign', 0],
+            ['integral', 0],
+            ['all', 0],
+        ], $request, true);
+        $user = $request->user();
+        //是否统计签到
+        if ($sign || $all) {
+            $user['sum_sgin_day'] = UserSign::getSignSumDay($user['uid']);
+            $user['is_day_sgin'] = UserSign::getIsSign($user['uid']);
+            $user['is_YesterDay_sgin'] = UserSign::getIsSign($user['uid'], 'yesterday');
+            if (!$user['is_day_sgin'] && !$user['is_YesterDay_sgin']) {
+                $user['sign_num'] = 0;
+            }
+        }
+        //是否统计积分使用情况
+        if ($integral || $all) {
+            $user['sum_integral'] = (int)UserBill::getRecordCount($user['uid'], 'integral', 'sign,system_add,gain');
+            $user['deduction_integral'] = (int)UserBill::getRecordCount($user['uid'], 'integral', 'deduction', '', true) ?? 0;
+            $user['today_integral'] = (int)UserBill::getRecordCount($user['uid'], 'integral', 'sign,system_add,gain', 'today');
+        }
+        unset($user['pwd']);
+        if (!$user['is_promoter']) {
+            $user['is_promoter'] = (int)sys_config('store_brokerage_statu') == 2 ? true : false;
+        }
+        return app('json')->successful($user->hidden(['account', 'real_name', 'birthday', 'card_id', 'mark', 'partner_id', 'group_id', 'add_time', 'add_ip', 'phone', 'last_time', 'last_ip', 'spread_uid', 'spread_time', 'user_type', 'status', 'level', 'clean_time', 'addres'])->toArray());
+    }
+
+    /**
+     * 签到列表(年月)
+     *
+     * @param Request $request
+     * @return mixed
+     */
+    public function sign_month(Request $request)
+    {
+        list($page, $limit) = UtilService::getMore([
+            ['page', 0],
+            ['limit', 0]
+        ], $request, true);
+        if (!$limit) return app('json')->successful([]);
+        $userSignList = UserSign::getSignMonthList($request->uid(), (int)$page, (int)$limit);
+        return app('json')->successful($userSignList);
+    }
+
+    /**
+     * 获取活动状态
+     * @return mixed
+     */
+    public function activity()
+    {
+        $data['is_bargin'] = StoreBargain::validBargain() ? true : false;
+        $data['is_pink'] = StoreCombination::getPinkIsOpen() ? true : false;
+        $data['is_seckill'] = StoreSeckill::getSeckillCount() ? true : false;
+        return app('json')->successful($data);
+    }
+
+    /**
+     * 用户修改信息
+     * @param Request $request
+     * @return mixed
+     */
+    public function edit(Request $request)
+    {
+        list($avatar, $nickname) = UtilService::postMore([
+            ['avatar', ''],
+            ['nickname', ''],
+        ], $request, true);
+        if (User::editUser($avatar, $nickname, $request->uid())) return app('json')->successful('修改成功');
+        return app('json')->fail('修改失败');
+    }
+
+    /**
+     * 推广人排行
+     * @param Request $request
+     * @return mixed
+     * @throws DataNotFoundException
+     * @throws ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+    public function rank(Request $request)
+    {
+        $data = UtilService::getMore([
+            ['page', ''],
+            ['limit', ''],
+            ['type', '']
+        ], $request);
+        $users = User::getRankList($data);
+        return app('json')->success($users);
+    }
+
+    /**
+     * 佣金排行
+     * @param Request $request
+     * @return mixed
+     */
+    public function brokerage_rank(Request $request)
+    {
+        $data = UtilService::getMore([
+            ['page', ''],
+            ['limit'],
+            ['type']
+        ], $request);
+        return app('json')->success([
+            'rank' => User::brokerageRank($data),
+            'position' => User::currentUserRank($data['type'], $request->user()['brokerage_price'])
+        ]);
+
+    }
+
+    /**
+     * 添加访问记录
+     * @param Request $request
+     * @return mixed
+     */
+    public function set_visit(Request $request)
+    {
+        $data = UtilService::postMore([
+            ['url', ''],
+            ['stay_time', 0]
+        ], $request);
+        if ($data['url'] == '') return app('json')->fail('未获取页面路径');
+        $data['uid'] = $request->uid();
+        $data['ip'] = $request->ip();
+        $data['add_time'] = time();
+        $res = UserVisit::insert($data);
+        if ($res) {
+            return app('json')->success('添加访问记录成功');
+        } else {
+            return app('json')->fail('添加访问记录失败');
+        }
+    }
+
+
+    /**
+     * 静默绑定推广人
+     * @param Request $request
+     * @return mixed
+     * @throws DataNotFoundException
+     * @throws DbException
+     * @throws ModelNotFoundException
+     */
+    public function spread(Request $request)
+    {
+        $puid = $request->post('puid/d', 0);
+        return app('json')->success(User::setSpread($puid, $request->uid()));
+    }
+>>>>>>> 386b37d33e5ba817cba00df29efaefbd692e4dd1
 }

+ 128 - 0
app/api/controller/user/UserPartakeController.php

@@ -1,3 +1,4 @@
+<<<<<<< HEAD
 <?php
 
 namespace app\api\controller\user;
@@ -123,4 +124,131 @@ class UserPartakeController
     }
 
 
+=======
+<?php
+
+namespace app\api\controller\user;
+
+use app\admin\model\order\StoreOrder;
+use app\models\system\SystemGroupData;
+use app\models\user\Out;
+use app\models\user\User;
+use app\models\user\UserPartake;
+use app\Request;
+use crmeb\services\GroupDataService;
+use crmeb\services\SystemConfigService;
+use crmeb\services\UtilService;
+use think\facade\Db;
+
+class UserPartakeController
+{
+    /**
+     * 出局奖励列表
+     * @return void
+     */
+    public function out_list(Request $request)
+    {
+        [$page, $limit] = UtilService::getMore([['page', 1], ['limit', 10]], $request, true);
+        $list = Out::where('status', 1)->where($page, $limit)->order('id DESC')->select()->toArray();
+        return app('json')->success($list);
+    }
+
+    /**
+     * 出局奖励列表
+     * @return void
+     */
+    public function out_detail($id, Request $request)
+    {
+        $list = Out::where('status', 1)->where('id', $id)->order('id DESC')->find();
+        $partake = UserPartake::where('uid', $request->uid())->where('status', 0)->find();
+        $list['partake'] = $partake;
+        $list = $list ? $list->toArray() : [];
+        return app('json')->success($list);
+    }
+
+    /**
+     * 参加
+     * @return void
+     */
+    public function participate_in(Request $request)
+    {
+        $data = UtilService::postMore([
+            'out_id'
+        ]);
+        Db::startTrans();
+        $user = User::where('uid', $request->uid())->find();
+        if ($user['level'] < 2) return app('json')->fail('等级为团队合伙人才能参与');
+
+        $out = Out::where('id', $data['out_id'])->find();
+        if (empty($out)) return app('json')->fail('参与项目不存在');
+        if ($out['status'] == 0) return app('json')->fail('参与项目已关闭');
+
+        $partake = UserPartake::where('uid', $request->uid())->where('status', 0)->find();
+        if ($partake) return app('json')->fail('当前已有参与中项目,无法参加');
+
+        $res = UserPartake::create([
+            'uid' => $request->uid(),
+            'out_id' => $data['out_id'],
+        ]);
+        if ($res) {
+            Db::commit();
+            return app('json')->success('参与成功');
+        } else {
+            Db::rollback();
+            return app('json')->fail('参与失败');
+        }
+
+    }
+
+
+    /**
+     * 参与记录
+     * @param Request $request
+     * @return mixed
+     * @throws \think\db\exception\DataNotFoundException
+     * @throws \think\db\exception\DbException
+     * @throws \think\db\exception\ModelNotFoundException
+     */
+    public function partake(Request $request)
+    {
+        $where = UtilService::getMore([
+            ['page', 1],
+            ['limit', 20],
+        ]);
+
+        $data = UserPartake::alias('a')
+            ->field('a.*,c.name,c.number')
+            ->order('a.id DESC')
+            ->leftJoin('out c', 'c.id = a.out_id')
+            ->where('uid', $request->uid())
+            ->page($where['page'], $where['limit'])
+            ->select();
+        $data = count($data) ? $data->toArray() : [];
+        foreach ($data as &$item) {
+            if ($item['money'] == 0) {
+                $item['money'] = User::where('uid', $item['uid'])->find()['pay_price'];
+            }
+        }
+        return app('json')->success($data);
+
+    }
+
+    public function user_push_list(Request $request)
+    {
+
+        $where = UtilService::getMore([
+            ['page', 1],
+            ['limit', 20],
+            ['uid'],
+            ['spread_uid']
+
+        ]);
+        $where['spread_uid'] = $request->uid();
+
+        $data = StoreOrder::list($where);
+        return app('json')->success($data);
+    }
+
+
+>>>>>>> 386b37d33e5ba817cba00df29efaefbd692e4dd1
 }

+ 2249 - 0
app/models/store/StoreOrder.php

@@ -1,3 +1,4 @@
+<<<<<<< HEAD
 <?php
 /**
  *
@@ -2244,4 +2245,2252 @@ class StoreOrder extends BaseModel
         return compact('list', 'count');
     }
 
+=======
+<?php
+/**
+ *
+ * @author: xaboy<365615158@qq.com>
+ * @day: 2017/12/20
+ */
+
+namespace app\models\store;
+
+use app\admin\model\system\ShippingTemplatesFree;
+use app\admin\model\system\ShippingTemplatesRegion;
+use crmeb\basic\BaseModel;
+use think\db\exception\DataNotFoundException;
+use think\db\exception\DbException;
+use think\db\exception\ModelNotFoundException;
+use think\facade\Cache;
+use crmeb\traits\ModelTrait;
+use think\facade\Log;
+use app\models\system\SystemStore;
+use app\models\routine\RoutineTemplate;
+use app\models\user\{Out, ProxyAddress, User, UserAddress, UserBill, UserLevel, UserPartake, UserSpread, WechatUser};
+use crmeb\services\{
+    SystemConfigService, WechatTemplateService, workerman\ChannelService
+};
+use crmeb\repositories\{
+    GoodsRepository, PaymentRepositories, OrderRepository, ShortLetterRepositories, UserRepository
+};
+use app\admin\model\system\ShippingTemplates;
+
+/**
+ * TODO 订单Model
+ * Class StoreOrder
+ * @package app\models\store
+ */
+class StoreOrder extends BaseModel
+{
+    /**
+     * 数据表主键
+     * @var string
+     */
+    protected $pk = 'id';
+
+    /**
+     * 模型名称
+     * @var string
+     */
+    protected $name = 'store_order';
+
+    use ModelTrait;
+
+    protected $insert = ['add_time'];
+
+    protected static $payType = ['weixin' => '微信支付', 'yue' => '余额支付', 'offline' => '线下支付', 'ali' => '支付宝支付'];
+
+    protected static $deliveryType = ['send' => '商家配送', 'express' => '快递配送'];
+
+    protected function setAddTimeAttr()
+    {
+        return time();
+    }
+
+    protected function setCartIdAttr($value)
+    {
+        return is_array($value) ? json_encode($value) : $value;
+    }
+
+    protected function getCartIdAttr($value)
+    {
+        return json_decode($value, true);
+    }
+
+    /**获取订单组信息
+     * @param $cartInfo
+     * @return array
+     */
+    public static function getOrderPriceGroup($cartInfo, $addr)
+    {
+        $storeFreePostage = floatval(sys_config('store_free_postage')) ?: 0;//满额包邮
+        $totalPrice = self::getOrderSumPrice($cartInfo, 'truePrice');//获取订单总金额
+        $totalIntegral = self::getOrderSumPrice($cartInfo, 'integral');//获取订单总积分
+        $costPrice = self::getOrderSumPrice($cartInfo, 'costPrice');//获取订单成本价
+        $vipPrice = self::getOrderSumPrice($cartInfo, 'vip_truePrice');//获取订单会员优惠金额
+        //如果满额包邮等于0
+        if (!$storeFreePostage) {
+            $storePostage = 0;
+        } else {
+            if ($addr) {
+                //按照运费模板计算每个运费模板下商品的件数/重量/体积以及总金额 按照首重倒序排列
+                $temp_num = [];
+                foreach ($cartInfo as $cart) {
+                    $temp = ShippingTemplates::get($cart['productInfo']['temp_id']);
+                    if (!$temp) $temp = ShippingTemplates::get(1);
+                    if ($temp->getData('type') == 1) {
+                        $num = $cart['cart_num'];
+                    } elseif ($temp->getData('type') == 2) {
+                        $num = $cart['cart_num'] * $cart['productInfo']['attrInfo']['weight'];
+                    } else {
+                        $num = $cart['cart_num'] * $cart['productInfo']['attrInfo']['volume'];
+                    }
+                    $region = ShippingTemplatesRegion::where('temp_id', $cart['productInfo']['temp_id'])->where('city_id', $addr['city_id'])->find();
+                    if (!$region) $region = ShippingTemplatesRegion::where('temp_id', $cart['productInfo']['temp_id'])->where('city_id', 0)->find();
+                    if (!$region) $region = ShippingTemplatesRegion::where('temp_id', 1)->where('city_id', 0)->find();
+                    if (!$region) {
+                        return self::setErrorInfo('运费模板不存在');
+                    }
+                    if (!isset($temp_num[$cart['productInfo']['temp_id']])) {
+                        $temp_num[$cart['productInfo']['temp_id']]['number'] = $num;
+                        $temp_num[$cart['productInfo']['temp_id']]['price'] = bcmul($cart['cart_num'], $cart['truePrice'], 2);
+                        $temp_num[$cart['productInfo']['temp_id']]['first'] = $region['first'];
+                        $temp_num[$cart['productInfo']['temp_id']]['first_price'] = $region['first_price'];
+                        $temp_num[$cart['productInfo']['temp_id']]['continue'] = $region['continue'];
+                        $temp_num[$cart['productInfo']['temp_id']]['continue_price'] = $region['continue_price'];
+                        $temp_num[$cart['productInfo']['temp_id']]['temp_id'] = $cart['productInfo']['temp_id'];
+                        $temp_num[$cart['productInfo']['temp_id']]['city_id'] = $addr['city_id'];
+                    } else {
+                        $temp_num[$cart['productInfo']['temp_id']]['number'] += $num;
+                        $temp_num[$cart['productInfo']['temp_id']]['price'] += bcmul($cart['cart_num'], $cart['truePrice'], 2);
+                    }
+                }
+                array_multisort(array_column($temp_num, 'first_price'), SORT_DESC, $temp_num);
+                $type = $storePostage = 0;
+                foreach ($temp_num as $k => $v) {
+                    if (ShippingTemplatesFree::where('temp_id', $v['temp_id'])->where('city_id', $v['city_id'])->where('number', '<=', $v['number'])->where('price', '<=', $v['price'])->find()) {
+                        unset($temp_num[$k]);
+                    }
+                }
+                foreach ($temp_num as $v) {
+                    if ($type == 0) {
+                        if ($v['number'] <= $v['first']) {
+                            $storePostage = bcadd($storePostage, $v['first_price'], 2);
+                        } else {
+                            if ($v['continue'] <= 0) {
+                                $storePostage = $storePostage;
+                            } else {
+                                $storePostage = bcadd(bcadd($storePostage, $v['first_price'], 2), bcmul(ceil(bcdiv(bcsub($v['number'], $v['first']), $v['continue'] ?? 0, 2)), $v['continue_price']), 2);
+                            }
+                        }
+                        $type = 1;
+                    } else {
+                        if ($v['continue'] <= 0) {
+                            $storePostage = $storePostage;
+                        } else {
+                            $storePostage = bcadd($storePostage, bcmul(ceil(bcdiv($v['number'], $v['continue'] ?? 0, 2)), $v['continue_price']), 2);
+                        }
+                    }
+                }
+            } else {
+                $storePostage = 0;
+            }
+            if ($storeFreePostage <= $totalPrice) $storePostage = 0;//如果总价大于等于满额包邮 邮费等于0
+        }
+        return compact('storePostage', 'storeFreePostage', 'totalPrice', 'costPrice', 'vipPrice', 'totalIntegral');
+    }
+
+
+    /**获取某个字段总金额
+     * @param $cartInfo
+     * @param $key 键名
+     * @return int|string
+     */
+    public static function getOrderSumPrice($cartInfo, $key = 'truePrice')
+    {
+        $SumPrice = 0;
+        foreach ($cartInfo as $cart) {
+            $SumPrice = bcadd($SumPrice, bcmul($cart['cart_num'], $cart[$key], 2), 2);
+        }
+        return $SumPrice;
+    }
+
+
+    /**
+     * 拼团
+     * @param $cartInfo
+     * @return array
+     */
+    public static function getCombinationOrderPriceGroup($cartInfo)
+    {
+        $storePostage = floatval(sys_config('store_postage')) ?: 0;
+        $storeFreePostage = floatval(sys_config('store_free_postage')) ?: 0;
+        $totalPrice = self::getCombinationOrderTotalPrice($cartInfo);
+        $costPrice = self::getCombinationOrderTotalPrice($cartInfo);
+        if (!$storeFreePostage) {
+            $storePostage = 0;
+        } else {
+            foreach ($cartInfo as $cart) {
+                if (!StoreCombination::where('id', $cart['combination_id'])->value('is_postage'))
+                    $storePostage = bcadd($storePostage, StoreCombination::where('id', $cart['combination_id'])->value('postage'), 2);
+            }
+            if ($storeFreePostage <= $totalPrice) $storePostage = 0;
+        }
+        return compact('storePostage', 'storeFreePostage', 'totalPrice', 'costPrice');
+    }
+
+    /**
+     * 拼团价格
+     * @param $cartInfo
+     * @return float
+     */
+    public static function getCombinationOrderTotalPrice($cartInfo)
+    {
+        $totalPrice = 0;
+        foreach ($cartInfo as $cart) {
+            if ($cart['combination_id']) {
+                $totalPrice = bcadd($totalPrice, bcmul($cart['cart_num'], StoreCombination::where('id', $cart['combination_id'])->value('price'), 2), 2);
+            }
+        }
+        return (float)$totalPrice;
+    }
+
+    /**
+     * 缓存订单信息
+     * @param $uid
+     * @param $cartInfo
+     * @param $priceGroup
+     * @param array $other
+     * @param int $cacheTime
+     * @return string
+     * @throws \Psr\SimpleCache\InvalidArgumentException
+     */
+    public static function cacheOrderInfo($uid, $cartInfo, $priceGroup, $other = [], $cacheTime = 600)
+    {
+        do {
+            $key = md5(time() . rand(100000, 999999));
+        } while (Cache::has('user_order_' . $uid . $key));
+        Cache::set('user_order_' . $uid . $key, compact('cartInfo', 'priceGroup', 'other'), $cacheTime);
+        return $key;
+    }
+
+    /**
+     * 获取订单缓存信息
+     * @param $uid
+     * @param $key
+     * @return mixed|null
+     * @throws \Psr\SimpleCache\InvalidArgumentException
+     */
+    public static function getCacheOrderInfo($uid, $key)
+    {
+        $cacheName = 'user_order_' . $uid . $key;
+        if (!Cache::has($cacheName)) return null;
+        return Cache::get($cacheName);
+    }
+
+    /**
+     * 删除订单缓存
+     * @param $uid
+     * @param $key
+     */
+    public static function clearCacheOrderInfo($uid, $key)
+    {
+        Cache::delete('user_order_' . $uid . $key);
+    }
+
+    /**
+     * 生成订单
+     * @param $uid
+     * @param $key
+     * @param $addressId
+     * @param $payType
+     * @param bool $useIntegral
+     * @param int $couponId
+     * @param string $mark
+     * @param int $combinationId
+     * @param int $pinkId
+     * @param int $seckill_id
+     * @param int $bargain_id
+     * @param bool $test
+     * @param int $isChannel
+     * @param int $shipping_type
+     * @param string $real_name
+     * @param string $phone
+     * @return StoreOrder|bool|\think\Model
+     * @throws \think\Exception
+     * @throws DataNotFoundException
+     * @throws ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+
+    public static function cacheKeyCreateOrder($uid, $key, $addressId, $payType, $useIntegral = false, $couponId = 0, $mark = '', $combinationId = 0, $pinkId = 0, $seckill_id = 0, $bargain_id = 0, $test = false, $isChannel = 0, $shipping_type = 1, $real_name = '', $phone = '', $storeId = 0)
+    {
+        self::beginTrans();
+        try {
+            $shipping_type = (int)$shipping_type;
+            $offlinePayStatus = (int)sys_config('offline_pay_status') ?? (int)2;
+            if ($offlinePayStatus == 2) unset(self::$payType['offline']);
+            if (!array_key_exists($payType, self::$payType)) return self::setErrorInfo('选择支付方式有误!', true);
+            if (self::be(['unique' => $key, 'uid' => $uid])) return self::setErrorInfo('请勿重复提交订单', true);
+            $userInfo = User::getUserInfo($uid);
+            if (!$userInfo) return self::setErrorInfo('用户不存在!', true);
+            $cartGroup = self::getCacheOrderInfo($uid, $key);
+            if (!$cartGroup) return self::setErrorInfo('订单已过期,请刷新当前页面!', true);
+            $cartInfo = $cartGroup['cartInfo'];
+            $priceGroup = $cartGroup['priceGroup'];
+            $other = $cartGroup['other'];
+            $payPrice = (float)$priceGroup['totalPrice'];
+            $payIntegral = (float)$priceGroup['totalIntegral'];
+            $addr = UserAddress::where('uid', $uid)->where('id', $addressId)->find();
+            if ($payType == 'offline' && sys_config('offline_postage') == 1) {
+                $payPostage = 0;
+            } else {
+                $payPostage = self::getOrderPriceGroup($cartInfo, $addr)['storePostage'];
+            }
+            if ($shipping_type === 1) {
+                if (!$test && !$addressId) return self::setErrorInfo('请选择收货地址!', true);
+                if (!$test && (!UserAddress::be(['uid' => $uid, 'id' => $addressId, 'is_del' => 0]) || !($addressInfo = UserAddress::find($addressId))))
+                    return self::setErrorInfo('地址选择有误!', true);
+            } else {
+                if ((!$real_name || !$phone) && !$test) return self::setErrorInfo('请填写姓名和电话', true);
+                $addressInfo['real_name'] = $real_name;
+                $addressInfo['phone'] = $phone;
+                $addressInfo['province'] = '';
+                $addressInfo['city'] = '';
+                $addressInfo['district'] = '';
+                $addressInfo['detail'] = '';
+            }
+
+            $cartIds = [];
+            $totalNum = 0;
+            $gainIntegral = 0;
+            foreach ($cartInfo as $cart) {
+                $cartIds[] = $cart['id'];
+                $totalNum += $cart['cart_num'];
+                if (!$seckill_id) $seckill_id = $cart['seckill_id'];
+                if (!$bargain_id) $bargain_id = $cart['bargain_id'];
+                if (!$combinationId) $combinationId = $cart['combination_id'];
+                $cartInfoGainIntegral = isset($cart['productInfo']['give_integral']) ? bcmul($cart['cart_num'], $cart['productInfo']['give_integral'], 2) : 0;
+                $gainIntegral = bcadd($gainIntegral, $cartInfoGainIntegral, 2);
+            }
+            $deduction = $seckill_id || $bargain_id || $combinationId;
+            if ($deduction) {
+                $couponId = 0;
+                $useIntegral = false;
+                if (!$test) {
+                    unset(self::$payType['offline']);
+                    if (!array_key_exists($payType, self::$payType)) return self::setErrorInfo('营销产品不能使用线下支付!', true);
+                }
+            }
+            //使用优惠劵
+            $res1 = true;
+            if ($couponId) {
+                $couponInfo = StoreCouponUser::validAddressWhere()->where('id', $couponId)->where('uid', $uid)->find();
+                if (!$couponInfo) return self::setErrorInfo('选择的优惠劵无效!', true);
+                $coupons = StoreCouponUser::getUsableCouponList($uid, ['valid' => $cartInfo], $payPrice);
+                $flag = false;
+                foreach ($coupons as $coupon) {
+                    if ($coupon['id'] == $couponId) {
+                        $flag = true;
+                        continue;
+                    }
+                }
+                if (!$flag)
+                    return self::setErrorInfo('不满足优惠劵的使用条件!', true);
+                $payPrice = (float)bcsub($payPrice, $couponInfo['coupon_price'], 2);
+                $res1 = StoreCouponUser::useCoupon($couponId);
+                $couponPrice = $couponInfo['coupon_price'];
+            } else {
+                $couponId = 0;
+                $couponPrice = 0;
+            }
+            if (!$res1) return self::setErrorInfo('使用优惠劵失败!', true);
+
+            //$shipping_type = 1 快递发货 $shipping_type = 2 门店自提
+            $store_self_mention = sys_config('store_self_mention') ?? 0;
+            if (!$store_self_mention) $shipping_type = 1;
+            if ($shipping_type === 1) {
+                //是否包邮
+                if ((isset($other['offlinePostage']) && $other['offlinePostage'] && $payType == 'offline')) $payPostage = 0;
+                $payPrice = (float)bcadd($payPrice, $payPostage, 2);
+            } else if ($shipping_type === 2) {
+                //门店自提没有邮费支付
+                $priceGroup['storePostage'] = 0;
+                $payPostage = 0;
+                if (!$storeId && !$test) {
+                    return self::setErrorInfo('请选择门店', true);
+                }
+            }
+
+            //积分抵扣
+            $res2 = true;
+            $SurplusIntegral = $userInfo['integral'];
+            if ($payIntegral > 0) {
+                if ($userInfo['integral'] < $payIntegral) {
+                    return self::setErrorInfo('积分不足', true);
+                } else {
+                    $res2 = false !== User::bcDec($userInfo['uid'], 'integral', $payIntegral, 'uid');
+                }
+                $SurplusIntegral = bcsub($userInfo['integral'], $payIntegral, 2);
+                $res2 = $res2 && false != UserBill::expend('积分商品', $uid, 'integral', 'integral_product', $payIntegral, $key, $SurplusIntegral, '购买积分商品使用' . $payIntegral . '积分');
+            }
+
+            //积分抵扣
+            if ($useIntegral && $SurplusIntegral > 0) {
+                $deductionPrice = (float)bcmul($SurplusIntegral, $other['integralRatio'], 2);
+                if ($deductionPrice < $payPrice) {
+                    $payPrice = bcsub($payPrice, $deductionPrice, 2);
+                    $usedIntegral = $SurplusIntegral;
+                    $SurplusIntegral = 0;
+                    $res2 = false !== User::edit(['integral' => 0], $userInfo['uid'], 'uid');
+                } else {
+                    $deductionPrice = $payPrice;
+                    $usedIntegral = (float)bcdiv($payPrice, $other['integralRatio'], 2);
+                    $SurplusIntegral = bcsub($SurplusIntegral, $usedIntegral, 2);
+                    $res2 = false !== User::bcDec($userInfo['uid'], 'integral', $usedIntegral, 'uid');
+                    $payPrice = 0;
+                }
+                $res2 = $res2 && false != UserBill::expend('积分抵扣', $uid, 'integral', 'deduction', $usedIntegral, $key, $SurplusIntegral, '购买商品使用' . floatval($usedIntegral) . '积分抵扣' . floatval($deductionPrice) . '元');
+            } else {
+                $deductionPrice = 0;
+                $usedIntegral = 0;
+            }
+            if (!$res2) return self::setErrorInfo('使用积分抵扣失败!', true);
+            if ($payPrice <= 0) $payPrice = 0;
+            if ($test) {
+                self::rollbackTrans();
+                return [
+                    'total_price' => $priceGroup['totalPrice'],
+                    'pay_price' => $payPrice,
+                    'pay_postage' => $payPostage,
+                    'coupon_price' => $couponPrice,
+                    'deduction_price' => $deductionPrice,
+                    'totalIntegral' => $payIntegral,
+                    'SurplusIntegral' => $SurplusIntegral,
+                ];
+            }
+            $orderInfo = [
+                'uid' => $uid,
+                'order_id' => $test ? 0 : self::getNewOrderId(),
+                'real_name' => $addressInfo['real_name'],
+                'user_phone' => $addressInfo['phone'],
+                'user_address' => $addressInfo['province'] . ' ' . $addressInfo['city'] . ' ' . $addressInfo['district'] . ' ' . $addressInfo['detail'],
+                'cart_id' => $cartIds,
+                'total_num' => $totalNum,
+                'total_price' => $priceGroup['totalPrice'],
+                'total_postage' => $priceGroup['storePostage'],
+                'coupon_id' => $couponId,
+                'coupon_price' => $couponPrice,
+                'pay_price' => $payPrice,
+                'pay_postage' => $payPostage,
+                'deduction_price' => $deductionPrice,
+                'paid' => 0,
+                'pay_type' => $payType,
+                'use_integral' => $usedIntegral + $payIntegral,
+                'gain_integral' => $gainIntegral,
+                'mark' => htmlspecialchars($mark),
+                'combination_id' => $combinationId,
+                'pink_id' => $pinkId,
+                'seckill_id' => $seckill_id,
+                'bargain_id' => $bargain_id,
+                'cost' => $priceGroup['costPrice'],
+                'is_channel' => $isChannel,
+                'add_time' => time(),
+                'unique' => $key,
+                'shipping_type' => $shipping_type,
+            ];
+            if ($shipping_type === 2) {
+                $orderInfo['verify_code'] = self::getStoreCode();
+                $orderInfo['store_id'] = SystemStore::getStoreDispose($storeId, 'id');
+                if (!$orderInfo['store_id']) return self::setErrorInfo('暂无门店无法选择门店自提!', true);
+            }
+            $order = self::create($orderInfo);
+            if (!$order) return self::setErrorInfo('订单生成失败!', true);
+            $res5 = true;
+            foreach ($cartInfo as $cart) {
+                //减库存加销量
+                if ($combinationId) $res5 = $res5 && StoreCombination::decCombinationStock($cart['cart_num'], $combinationId, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
+                else if ($seckill_id) $res5 = $res5 && StoreSeckill::decSeckillStock($cart['cart_num'], $seckill_id, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
+                else if ($bargain_id) $res5 = $res5 && StoreBargain::decBargainStock($cart['cart_num'], $bargain_id, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
+                else $res5 = $res5 && StoreProduct::decProductStock($cart['cart_num'], $cart['productInfo']['id'], isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
+            }
+            //保存购物车商品信息
+            $res4 = false !== StoreOrderCartInfo::setCartInfo($order['id'], $cartInfo);
+            //购物车状态修改
+            $res6 = false !== StoreCart::where('id', 'IN', $cartIds)->update(['is_pay' => 1]);
+            if (!$res4 || !$res5 || !$res6) return self::setErrorInfo('订单生成失败!', true);
+            //自动设置默认地址
+            UserRepository::storeProductOrderCreateEbApi($order, compact('cartInfo', 'addressId'));
+            self::clearCacheOrderInfo($uid, $key);
+            self::commitTrans();
+            StoreOrderStatus::status($order['id'], 'cache_key_create_order', '订单生成');
+            return $order;
+        } catch (\PDOException $e) {
+            self::rollbackTrans();
+            return self::setErrorInfo('生成订单时SQL执行错误错误原因:' . $e->getMessage());
+        } catch (\Exception $e) {
+            self::rollbackTrans();
+            return self::setErrorInfo('生成订单时系统错误错误原因:' . $e->getMessage());
+        }
+    }
+
+
+    /**
+     * 回退积分
+     * @param $order 订单信息
+     * @return bool
+     */
+    public static function RegressionIntegral($order)
+    {
+        if ($order['paid'] || $order['status'] == -2 || $order['is_del']) return true;
+        if ($order['use_integral'] <= 0) return true;
+        if ((int)$order['status'] != -2 && (int)$order['refund_status'] != 2 && $order['back_integral'] >= $order['use_integral']) return true;
+        $res = User::bcInc($order['uid'], 'integral', $order['use_integral']);
+        if (!$res) return self::setErrorInfo('回退积分增加失败');
+        UserBill::income('积分回退', $order['uid'], 'integral', 'deduction', $order['use_integral'], $order['unique'], User::where('uid', $order['uid'])->value('integral'), '购买商品失败,回退积分' . floatval($order['use_integral']));
+        return false !== self::where('order_id', $order['order_id'])->update(['back_integral' => $order['use_integral']]);
+    }
+
+
+    /**
+     * 回退库存和销量
+     * @param $order 订单信息
+     * @return bool
+     * @throws DataNotFoundException
+     * @throws ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+    public static function RegressionStock($order)
+    {
+        if ($order['paid'] || $order['status'] == -2 || $order['is_del']) return true;
+        $combinationId = $order['combination_id'];
+        $seckill_id = $order['seckill_id'];
+        $bargain_id = $order['bargain_id'];
+        $res5 = true;
+        $cartInfo = StoreOrderCartInfo::where('cart_id', 'in', $order['cart_id'])->select();
+        foreach ($cartInfo as $cart) {
+            //增库存减销量
+            if ($combinationId) $res5 = $res5 && StoreCombination::incCombinationStock($cart['cart_info']['cart_num'], $combinationId);
+            else if ($seckill_id) $res5 = $res5 && StoreSeckill::incSeckillStock($cart['cart_info']['cart_num'], $seckill_id);
+            else if ($bargain_id) $res5 = $res5 && StoreBargain::incBargainStock($cart['cart_info']['cart_num'], $bargain_id);
+            else $res5 = $res5 && StoreProduct::incProductStock($cart['cart_info']['cart_num'], $cart['cart_info']['productInfo']['id'], isset($cart['cart_info']['productInfo']['attrInfo']) ? $cart['cart_info']['productInfo']['attrInfo']['unique'] : '');
+        }
+        return $res5;
+    }
+
+    /**
+     * 回退优惠卷
+     * @param $order 订单信息
+     * @return bool
+     */
+    public static function RegressionCoupon($order)
+    {
+        if ($order['paid'] || $order['status'] == -2 || $order['is_del']) return true;
+        $res = true;
+        if ($order['coupon_id'] && StoreCouponUser::be(['id' => $order['coupon_id'], 'uid' => $order['uid'], 'status' => 1])) {
+            $res = $res && false !== StoreCouponUser::where('id', $order['coupon_id'])->where('uid', $order['uid'])->update(['status' => 0, 'use_time' => 0]);
+        }
+        return $res;
+    }
+
+    /**
+     * 取消订单
+     * @param string order_id 订单id
+     * @param $uid
+     * @return bool
+     * @throws DataNotFoundException
+     * @throws ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+    public static function cancelOrder($order_id, $uid)
+    {
+        $order = self::where('order_id', $order_id)->where('uid', $uid)->find();
+        if (!$order) return self::setErrorInfo('没有查到此订单');
+        self::beginTrans();
+        try {
+            $res = self::RegressionIntegral($order) && self::RegressionStock($order) && self::RegressionCoupon($order);
+            $order->is_del = 1;
+            if ($res && $order->save()) {
+                self::commitTrans();
+                return true;
+            } else
+                return false;
+        } catch (\Exception $e) {
+            self::rollbackTrans();
+            return self::setErrorInfo(['line' => $e->getLine(), 'message' => $e->getMessage()]);
+        }
+    }
+
+    /**
+     * 生成订单唯一id
+     * @param $uid 用户uid
+     * @return string
+     */
+    public static function getNewOrderId()
+    {
+        do {
+            list($msec, $sec) = explode(' ', microtime());
+            $msectime = number_format((floatval($msec) + floatval($sec)) * 1000, 0, '', '');
+            $orderId = 'wx' . $msectime . mt_rand(10000, 99999);
+        } while (self::be(['order_id' => $orderId]));// $orderId = 'wx' . $msectime . mt_rand(10000, 99999);
+        return $orderId;
+    }
+
+    /**
+     * 修改订单号
+     * @param $orderId
+     * @return string
+     */
+    public static function changeOrderId($orderId)
+    {
+        $ymd = substr($orderId, 2, 8);
+        $key = substr($orderId, 16);
+        return 'wx' . $ymd . date('His') . $key;
+    }
+
+    /**
+     * 查找购物车里的所有产品标题
+     * @param $cartId 购物车id
+     * @return bool|string
+     */
+    public static function getProductTitle($cartId)
+    {
+        $title = '';
+        try {
+            $orderCart = StoreOrderCartInfo::where('cart_id', 'in', $cartId)->field('cart_info')->select();
+            foreach ($orderCart as $item) {
+                if (isset($item['cart_info']['productInfo']['store_name'])) {
+                    $title .= $item['cart_info']['productInfo']['store_name'] . '|';
+                }
+            }
+            unset($item);
+            if (!$title) {
+                $productIds = StoreCart::where('id', 'in', $cartId)->column('product_id');
+                $productlist = ($productlist = StoreProduct::getProductField($productIds, 'store_name')) ? $productlist->toArray() : [];
+                foreach ($productlist as $item) {
+                    if (isset($item['store_name'])) $title .= $item['store_name'] . '|';
+                }
+            }
+            if ($title) $title = substr($title, 0, strlen($title) - 1);
+            unset($item);
+        } catch (\Exception $e) {
+        }
+        return $title;
+    }
+
+    /**
+     * 获取门店自提唯一核销码
+     * @return bool|string
+     */
+    public static function getStoreCode()
+    {
+        list($msec, $sec) = explode(' ', microtime());
+        $num = bcadd(time(), mt_rand(10, 999999), 0) . '' . substr($msec, 2, 3);//生成随机数
+        if (strlen($num) < 12)
+            $num = str_pad((string)$num, 12, 0, STR_PAD_RIGHT);
+        else
+            $num = substr($num, 0, 12);
+        if (self::be(['verify_code' => $num])) return self::getStoreCode();
+        return $num;
+    }
+
+    /**
+     * 余额支付
+     * @param $order_id
+     * @param $uid
+     * @param string $formId
+     * @return bool
+     * @throws \think\Exception
+     * @throws DataNotFoundException
+     * @throws ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+    public static function yuePay($order_id, $uid, $formId = '')
+    {
+        $orderInfo = self::where('uid', $uid)->where('order_id', $order_id)->where('is_del', 0)->find();
+        if (!$orderInfo) return self::setErrorInfo('订单不存在!');
+        if ($orderInfo['paid']) return self::setErrorInfo('该订单已支付!');
+//        if($orderInfo['pay_type'] != 'yue') return self::setErrorInfo('该订单不能使用余额支付!');
+        $userInfo = User::getUserInfo($uid);
+        if ($userInfo['now_money'] < $orderInfo['pay_price'])
+            return self::setErrorInfo(['status' => 'pay_deficiency', 'msg' => '余额不足' . floatval($orderInfo['pay_price'])]);
+        self::beginTrans();
+
+        $res1 = false !== User::bcDec($uid, 'now_money', $orderInfo['pay_price'], 'uid');
+        $res2 = UserBill::expend('购买商品', $uid, 'now_money', 'pay_product', $orderInfo['pay_price'], $orderInfo['id'], $userInfo['now_money'], '余额支付' . floatval($orderInfo['pay_price']) . '元购买商品');
+        $res3 = self::paySuccess($order_id, 'yue', $formId);//余额支付成功
+        try {
+            PaymentRepositories::yuePayProduct($userInfo, $orderInfo);
+        } catch (\Exception $e) {
+            self::rollbackTrans();
+            return self::setErrorInfo($e->getMessage());
+        }
+        $res = $res1 && $res2 && $res3;
+        self::checkTrans($res);
+        return $res;
+    }
+
+    /**
+     * 微信支付 为 0元时
+     * @param $order_id
+     * @param $uid
+     * @param string $formId
+     * @return bool
+     * @throws \think\Exception
+     * @throws DataNotFoundException
+     * @throws ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+    public static function jsPayPrice($order_id, $uid, $formId = '')
+    {
+        $orderInfo = self::where('uid', $uid)->where('order_id', $order_id)->where('is_del', 0)->find();
+        if (!$orderInfo) return self::setErrorInfo('订单不存在!');
+        if ($orderInfo['paid']) return self::setErrorInfo('该订单已支付!');
+        $userInfo = User::getUserInfo($uid);
+        self::beginTrans();
+        $res1 = UserBill::expend('购买商品', $uid, 'now_money', 'pay_product', $orderInfo['pay_price'], $orderInfo['id'], $userInfo['now_money'], '微信支付' . floatval($orderInfo['pay_price']) . '元购买商品');
+        $res2 = self::paySuccess($order_id, 'weixin', $formId);//微信支付为0时
+        $res = $res1 && $res2;
+        self::checkTrans($res);
+        return $res;
+    }
+
+
+    /**
+     * 用户申请退款
+     * @param $uni
+     * @param $uid
+     * @param string $refundReasonWap
+     * @return bool
+     */
+    public static function orderApplyRefund($uni, $uid, $refundReasonWap = '', $refundReasonWapExplain = '', $refundReasonWapImg = [])
+    {
+        $order = self::getUserOrderDetail($uid, $uni);
+        if (!$order) return self::setErrorInfo('支付订单不存在!');
+        if ($order['refund_status'] == 2) return self::setErrorInfo('订单已退款!');
+        if ($order['refund_status'] == 1) return self::setErrorInfo('正在申请退款中!');
+        if ($order['status'] == 1) return self::setErrorInfo('订单当前无法退款!');
+        self::beginTrans();
+        $res1 = false !== StoreOrderStatus::status($order['id'], 'apply_refund', '用户申请退款,原因:' . $refundReasonWap);
+        $res2 = false !== self::edit(['refund_status' => 1, 'refund_reason_time' => time(), 'refund_reason_wap' => $refundReasonWap, 'refund_reason_wap_explain' => $refundReasonWapExplain, 'refund_reason_wap_img' => json_encode($refundReasonWapImg)], $order['id'], 'id');
+        $res = $res1 && $res2;
+        self::checkTrans($res);
+        if (!$res)
+            return self::setErrorInfo('申请退款失败!');
+        else {
+            try {
+                if (in_array($order['is_channel'], [0, 2])) {
+                    //公众号发送模板消息通知客服
+                    WechatTemplateService::sendAdminNoticeTemplate([
+                        'first' => "亲,有个订单申请退款 \n订单号:{$order['order_id']}",
+                        'keyword1' => '退款申请',
+                        'keyword2' => '已支付',
+                        'keyword3' => date('Y/m/d H:i', time()),
+                        'remark' => '请及时处理'
+                    ]);
+                }
+                if (in_array($order['is_channel'], [1, 2])) {
+                    //小程序 发送模板消息
+                    RoutineTemplate::sendOrderRefundStatus($order, $refundReasonWap);
+                }
+                //通知后台消息提醒
+                ChannelService::instance()->send('NEW_REFUND_ORDER', ['order_id' => $order['order_id']]);
+            } catch (\Exception $e) {
+            }
+            //发送短信
+            event('ShortMssageSend', [$order['order_id'], 'AdminRefund']);
+            return true;
+        }
+    }
+
+    /**
+     * //TODO 支付成功后
+     * @param $orderId
+     * @param string $paytype
+     * @param string $formId
+     * @return bool
+     * @throws DataNotFoundException
+     * @throws DbException
+     * @throws ModelNotFoundException
+     */
+    public static function paySuccess($orderId, $paytype = 'weixin', $formId = '')
+    {
+        $order = self::where('order_id', $orderId)->find();
+        $resPink = true;
+        $res1 = self::where('order_id', $orderId)->update(['paid' => 1, 'pay_type' => $paytype, 'pay_time' => time(), 'is_del' => 0, 'is_system_del' => 0, 'mark' => '']);//订单改为支付
+        if ($order->combination_id && $res1 && !$order->refund_status) $resPink = StorePink::createPink($order);//创建拼团
+        $oid = self::where('order_id', $orderId)->value('id');
+        StoreOrderStatus::status($oid, 'pay_success', '用户付款成功');
+        $now_money = User::where('uid', $order['uid'])->value('now_money');
+        UserBill::expend('购买商品', $order['uid'], 'now_money', 'pay_money', $order['pay_price'], $order['id'], $now_money, '支付' . floatval($order['pay_price']) . '元购买商品');
+        //支付成功后
+        event('OrderPaySuccess', [$order, $formId]);
+        self::push($order);
+        $res = $res1 && $resPink && UserSpread::setSpreadSure($order['uid']) && User::backOrderBrokerage($order);
+        return false !== $res;
+    }
+
+
+    /**
+     * 直推奖励
+     * @param $order
+     * @return void
+     */
+    public static function push($order)
+    {
+        $user = User::where('uid', $order['uid'])->find();
+        if ($user['spread_uid']){
+            $spread = User::where('uid', $user['spread_uid'])->where('level', 2)->find();
+            if ($spread){
+                //直推上级是团队
+                $group_purchase = sys_config('group_purchase');
+                $jl = round($order['pay_price'] * ($group_purchase/100), 2);
+                UserBill::income('佣金', $spread['uid'], 'now_money', 'brokerage', $jl, '', $spread['brokerage_price']+$jl, '直推佣金奖励');
+                User::where('uid', $spread['uid'])->inc('brokerage_price', $jl)->update();
+
+            }
+        }
+    }
+
+    /*
+     * 线下支付消息通知
+     * 待完善
+     *
+     * */
+    public static function createOrderTemplate($order)
+    {
+
+        //$goodsName = StoreOrderCartInfo::getProductNameList($order['id']);
+//        RoutineTemplateService::sendTemplate(WechatUser::getOpenId($order['uid']),RoutineTemplateService::ORDER_CREATE, [
+//            'first'=>'亲,您购买的商品已支付成功',
+//            'keyword1'=>date('Y/m/d H:i',$order['add_time']),
+//            'keyword2'=>implode(',',$goodsName),
+//            'keyword3'=>$order['order_id'],
+//            'remark'=>'点击查看订单详情'
+//        ],Url::build('/wap/My/order',['uni'=>$order['order_id']],true,true));
+//        RoutineTemplateService::sendAdminNoticeTemplate([
+//            'first'=>"亲,您有一个新订单 \n订单号:{$order['order_id']}",
+//            'keyword1'=>'新订单',
+//            'keyword2'=>'线下支付',
+//            'keyword3'=>date('Y/m/d H:i',time()),
+//            'remark'=>'请及时处理'
+//        ]);
+    }
+
+    /**
+     * 获取订单详情
+     * @param $uid
+     * @param $key
+     * @return array|\think\Model|null
+     * @throws DataNotFoundException
+     * @throws ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+    public static function getUserOrderDetail($uid, $key)
+    {
+        return self::where('order_id|unique', $key)->where('uid', $uid)->where('is_del', 0)->find();
+    }
+
+
+    /**
+     * TODO 订单发货
+     * @param array $postageData 发货信息
+     * @param string $oid orderID
+     */
+    public static function orderPostageAfter($postageData, $oid)
+    {
+        $order = self::where('id', $oid)->find();
+        if ($postageData['delivery_type'] == 'send') {//送货
+            RoutineTemplate::sendOrderPostage($order);
+        } else if ($postageData['delivery_type'] == 'express') {//发货
+            RoutineTemplate::sendOrderPostage($order, 1);
+        }
+    }
+
+    /** 收货后发送模版消息
+     * @param $order
+     */
+    public static function orderTakeAfter($order)
+    {
+        $title = self::getProductTitle($order['cart_id']);
+        if ($order['is_channel'] == 1) {//小程序
+            RoutineTemplate::sendOrderTakeOver($order, $title);
+        } else {
+            $openid = WechatUser::where('uid', $order['uid'])->value('openid');
+            \crmeb\services\WechatTemplateService::sendTemplate($openid, \crmeb\services\WechatTemplateService::ORDER_TAKE_SUCCESS, [
+                'first' => '亲,您的订单已收货',
+                'keyword1' => $order['order_id'],
+                'keyword2' => '已收货',
+                'keyword3' => date('Y-m-d H:i:s', time()),
+                'keyword4' => $title,
+                'remark' => '感谢您的光临!'
+            ]);
+        }
+    }
+
+    /**
+     * 删除订单
+     * @param $uni
+     * @param $uid
+     * @return bool
+     */
+    public static function removeOrder($uni, $uid)
+    {
+        $order = self::getUserOrderDetail($uid, $uni);
+        if (!$order) return self::setErrorInfo('订单不存在!');
+        $order = self::tidyOrder($order);
+        if ($order['_status']['_type'] != 0 && $order['_status']['_type'] != -2 && $order['_status']['_type'] != 4)
+            return self::setErrorInfo('该订单无法删除!');
+        if (false !== self::edit(['is_del' => 1], $order['id'], 'id') && false !== StoreOrderStatus::status($order['id'], 'remove_order', '删除订单')) {
+            //未支付和已退款的状态下才可以退积分退库存退优惠券
+            if ($order['_status']['_type'] == 0 || $order['_status']['_type'] == -2) {
+                event('StoreOrderRegressionAllAfter', [$order]);
+            }
+            event('UserOrderRemoved', $uni);
+            return true;
+        } else
+            return self::setErrorInfo('订单删除失败!');
+    }
+
+
+    /**
+     * //TODO 用户确认收货
+     * @param $uni
+     * @param $uid
+     */
+    public static function takeOrder($uni, $uid)
+    {
+        $order = self::getUserOrderDetail($uid, $uni);
+        if (!$order) return self::setErrorInfo('订单不存在!');
+        $order = self::tidyOrder($order);
+        if ($order['_status']['_type'] != 2) return self::setErrorInfo('订单状态错误!');
+        self::beginTrans();
+        if (false !== self::edit(['status' => 2], $order['id'], 'id') &&
+            false !== StoreOrderStatus::status($order['id'], 'user_take_delivery', '用户已收货')) {
+            try {
+                OrderRepository::storeProductOrderUserTakeDelivery($order, $uid);
+                UserBill::where('uid', $order['uid'])->where('link_id', $order['id'])->where('type', 'pay_money')->update(['take' => 1]);
+            } catch (\Exception $e) {
+                self::rollbackTrans();
+                return self::setErrorInfo($e->getMessage());
+            }
+
+            self::cumulative($order);
+            self::team($order);
+            self::proxy($order);
+
+            self::commitTrans();
+            UserLevel::setLevelComplete($uid);
+            event('UserLevelAfter', [User::get($uni)]);
+            event('UserOrderTake', $uni);
+            //短信通知
+            event('ShortMssageSend', [$order['order_id'], ['Receiving', 'AdminConfirmTakeOver']]);
+            return true;
+        } else {
+            self::rollbackTrans();
+            return false;
+        }
+    }
+
+    /**
+     * 参与累计金额
+     * @param $order
+     * @return void
+     */
+    public static function cumulative($order)
+    {
+        User::where('uid', $order['uid'])->inc('pay_price', $order['pay_price'])->update();
+        $user = User::where('uid', $order['uid'])->find();
+        $partake = UserPartake::where('uid', $order['uid'])->where('status', 0)->find();
+        if ($partake){
+            $out = Out::where('id', $partake['out_id'])->find();
+            if ($user['pay_price'] >= $out['number']){
+                $user['pay_price'] -= $out['number'];
+                $user['use_price'] += $out['number'];
+                $user->save();
+                $partake['status'] = 1;
+                $partake['money'] = $out['number'];
+                $partake->save();
+            }
+        }
+    }
+
+    /**
+     * 发放团队奖励
+     * @param $order
+     * @return void
+     */
+    public static function team($order)
+    {
+        $user = User::where('uid', $order['uid'])->find();
+        $uids = getParents($user['spread_uid'],User::select());
+        if ($uids){
+            $v1 = 0;//团队
+            $v2 = 0;//联创
+            $city = sys_config('city')/100;//城市比列
+            $lianchuang = sys_config('lianchuang')/100;//联创比列
+            foreach ($uids as $item)
+            {
+                $spread = User::where('uid', $item)->find();
+                if ($spread['level'] == 3){
+                    if ($v1 == 0){
+                        $jl = $order['pay_price'] * $city;
+                        UserBill::income('佣金', $spread['uid'], 'now_money', 'brokerage', $jl, '', $spread['brokerage_price']+$jl, '下级消费'.$order['pay_price'].'城市合伙人团队佣金');
+                        User::where('uid', $spread['uid'])->inc('brokerage_price', $jl)->update();
+                        $v1++;
+                    }
+                }
+
+                if ($spread['level'] == 4){
+                    if ($v2 == 0){
+                        $jl = $order['pay_price'] * $lianchuang;
+                        UserBill::income('佣金', $spread['uid'], 'now_money', 'brokerage', $jl, '', $spread['brokerage_price']+$jl, '下级消费'.$order['pay_price'].'联创团队佣金');
+                        User::where('uid', $spread['uid'])->inc('brokerage_price', $jl)->update();
+                        $v2++;
+                    }
+                }
+            }
+        }
+    }
+
+
+    /**
+     * 发放落地奖励
+     * @param $order
+     * @param $uid
+     * @return void
+     */
+    public static function proxy($order)
+    {
+        $address = explode(' ', $order['user_address']);
+        $proxy = ProxyAddress::where(['province' => $address[0], 'city' => $address[1], 'district' => $address[2]])->select()->toArray();
+        foreach ($proxy as $item)
+        {
+            $user = User::where('uid', $item['uid'])->find();
+            if ($user['level'] == 3){
+                $to_ground = sys_config('to_ground');
+                $jl = $order['pay_price'] * ($to_ground/100);
+                UserBill::income('佣金', $user['uid'], 'now_money', 'brokerage', $jl, '', $user['brokerage_price']+$jl, '落地奖励佣金');
+                User::where('uid', $user['uid'])->inc('brokerage_price', $jl)->update();
+            }
+
+        }
+    }
+
+    /**
+     * 获取订单状态购物车等信息
+     * @param $order
+     * @param bool $detail 是否获取订单购物车详情
+     * @param bool $isPic 是否获取订单状态图片
+     * @return mixed
+     * @throws DataNotFoundException
+     * @throws ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+    public static function tidyOrder($order, $detail = false, $isPic = false)
+    {
+        if ($detail == true && isset($order['id'])) {
+            $cartInfo = StoreOrderCartInfo::where('oid', $order['id'])->column('cart_info', 'unique') ?: [];
+            $info = [];
+            foreach ($cartInfo as $k => $cart) {
+                $cart = json_decode($cart, true);
+                $cart['unique'] = $k;
+                //新增是否评价字段
+                $cart['is_reply'] = StoreProductReply::where('unique', $k)->count();
+                array_push($info, $cart);
+                unset($cart);
+            }
+            $order['cartInfo'] = $info;
+        }
+        $status = [];
+        if (!$order['paid'] && $order['pay_type'] == 'offline' && !$order['status'] >= 2) {
+            $status['_type'] = 9;
+            $status['_title'] = '线下付款';
+            $status['_msg'] = '商家处理中,请耐心等待';
+            $status['_class'] = 'nobuy';
+        } else if (!$order['paid']) {
+            $status['_type'] = 0;
+            $status['_title'] = '未支付';
+            //系统预设取消订单时间段
+            $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
+            //获取配置
+            $systemValue = SystemConfigService::more($keyValue);
+            //格式化数据
+            $systemValue = self::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
+            if ($order['pink_id'] || $order['combination_id']) {
+                $order_pink_time = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
+                $time = bcadd($order['add_time'], $order_pink_time * 3600, 0);
+                $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
+            } else if ($order['seckill_id']) {
+                $order_seckill_time = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
+                $time = bcadd($order['add_time'], $order_seckill_time * 3600, 0);
+                $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
+            } else if ($order['bargain_id']) {
+                $order_bargain_time = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
+                $time = bcadd($order['add_time'], $order_bargain_time * 3600, 0);
+                $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
+            } else {
+                $time = bcadd($order['add_time'], $systemValue['order_cancel_time'] * 3600, 0);
+                $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
+            }
+            $status['_class'] = 'nobuy';
+        } else if ($order['refund_status'] == 1) {
+            $status['_type'] = -1;
+            $status['_title'] = '申请退款中';
+            $status['_msg'] = '商家审核中,请耐心等待';
+            $status['_class'] = 'state-sqtk';
+        } else if ($order['refund_status'] == 2) {
+            $status['_type'] = -2;
+            $status['_title'] = '已退款';
+            $status['_msg'] = '已为您退款,感谢您的支持';
+            $status['_class'] = 'state-sqtk';
+        } else if (!$order['status']) {
+            if ($order['pink_id']) {
+                if (StorePink::where('id', $order['pink_id'])->where('status', 1)->count()) {
+                    $status['_type'] = 1;
+                    $status['_title'] = '拼团中';
+                    $status['_msg'] = '等待其他人参加拼团';
+                    $status['_class'] = 'state-nfh';
+                } else {
+                    $status['_type'] = 1;
+                    $status['_title'] = '未发货';
+                    $status['_msg'] = '商家未发货,请耐心等待';
+                    $status['_class'] = 'state-nfh';
+                }
+            } else {
+                if ($order['shipping_type'] === 1) {
+                    $status['_type'] = 1;
+                    $status['_title'] = '未发货';
+                    $status['_msg'] = '商家未发货,请耐心等待';
+                    $status['_class'] = 'state-nfh';
+                } else {
+                    $status['_type'] = 1;
+                    $status['_title'] = '待核销';
+                    $status['_msg'] = '待核销,请到核销点进行核销';
+                    $status['_class'] = 'state-nfh';
+                }
+            }
+        } else if ($order['status'] == 1) {
+            if ($order['delivery_type'] == 'send') {//TODO 送货
+                $status['_type'] = 2;
+                $status['_title'] = '待收货';
+                $status['_msg'] = date('m月d日H时i分', StoreOrderStatus::getTime($order['id'], 'delivery')) . '服务商已送货';
+                $status['_class'] = 'state-ysh';
+            } else {//TODO  发货
+                $status['_type'] = 2;
+                $status['_title'] = '待收货';
+                if ($order['delivery_type'] == 'fictitious')
+                    $_time = StoreOrderStatus::getTime($order['id'], 'delivery_fictitious');
+                else
+                    $_time = StoreOrderStatus::getTime($order['id'], 'delivery_goods');
+                $status['_msg'] = date('m月d日H时i分', $_time) . '服务商已发货';
+                $status['_class'] = 'state-ysh';
+            }
+        } else if ($order['status'] == 2) {
+            $status['_type'] = 3;
+            $status['_title'] = '待评价';
+            $status['_msg'] = '已收货,快去评价一下吧';
+            $status['_class'] = 'state-ypj';
+        } else if ($order['status'] == 3) {
+            $status['_type'] = 4;
+            $status['_title'] = '交易完成';
+            $status['_msg'] = '交易完成,感谢您的支持';
+            $status['_class'] = 'state-ytk';
+        }
+        if (isset($order['pay_type']))
+            $status['_payType'] = isset(self::$payType[$order['pay_type']]) ? self::$payType[$order['pay_type']] : '其他方式';
+        if (isset($order['delivery_type']))
+            $status['_deliveryType'] = isset(self::$deliveryType[$order['delivery_type']]) ? self::$deliveryType[$order['delivery_type']] : '其他方式';
+        $order['_status'] = $status;
+        $order['_pay_time'] = isset($order['pay_time']) && $order['pay_time'] != null ? date('Y-m-d H:i:s', $order['pay_time']) : date('Y-m-d H:i:s', $order['add_time']);
+        $order['_add_time'] = isset($order['add_time']) ? (strstr($order['add_time'], '-') === false ? date('Y-m-d H:i:s', $order['add_time']) : $order['add_time']) : '';
+        $order['status_pic'] = '';
+        //获取产品状态图片
+        if ($isPic) {
+            $order_details_images = sys_data('order_details_images') ?: [];
+            foreach ($order_details_images as $image) {
+                if (isset($image['order_status']) && $image['order_status'] == $order['_status']['_type']) {
+                    $order['status_pic'] = $image['pic'];
+                    break;
+                }
+            }
+        }
+        $order['offlinePayStatus'] = (int)sys_config('offline_pay_status') ?? (int)2;
+        return $order;
+    }
+
+    /**
+     * 设置订单查询状态
+     * @param $status
+     * @param int $uid
+     * @param null $model
+     * @return StoreOrder|null
+     */
+    public static function statusByWhere($status, $uid = 0, $model = null)
+    {
+//        $orderId = StorePink::where('uid',$uid)->where('status',1)->column('order_id','id');//获取正在拼团的订单编号
+        if ($model == null) $model = new self;
+        if ('' === $status)
+            return $model;
+        else if ($status == 0)//未支付
+            return $model->where('paid', 0)->where('status', 0)->where('refund_status', 0);
+        else if ($status == 1)//待发货
+            return $model->where('paid', 1)->where('status', 0)->where('refund_status', 0);
+        else if ($status == 2)//待收货
+            return $model->where('paid', 1)->where('status', 1)->where('refund_status', 0);
+        else if ($status == 3)//待评价
+            return $model->where('paid', 1)->where('status', 2)->where('refund_status', 0);
+        else if ($status == 4)//已完成
+            return $model->where('paid', 1)->where('status', 3)->where('refund_status', 0);
+        else if ($status == -1)//退款中
+            return $model->where('paid', 1)->where('refund_status', 1);
+        else if ($status == -2)//已退款
+            return $model->where('paid', 1)->where('refund_status', 2);
+        else if ($status == -3)//退款
+            return $model->where('paid', 1)->where('refund_status', 'IN', '1,2');
+//        else if($status == 11){
+//            return $model->where('order_id','IN',implode(',',$orderId));
+//        }
+        else
+            return $model;
+    }
+
+    /**
+     * 获取订单并分页
+     * @param $uid
+     * @param string $status
+     * @param int $page
+     * @param int $limit
+     * @return mixed
+     * @throws DataNotFoundException
+     * @throws ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+    public static function getUserOrderList($uid, $status = '', $page = 0, $limit = 8)
+    {
+        if ($page) $list = self::statusByWhere($status, $uid)->where('is_del', 0)->where('uid', $uid)
+            ->field('add_time,seckill_id,bargain_id,combination_id,id,order_id,pay_price,total_num,total_price,pay_postage,total_postage,paid,status,refund_status,pay_type,coupon_price,deduction_price,pink_id,delivery_type,is_del,shipping_type')
+            ->order('add_time DESC')->page((int)$page, (int)$limit)->select()->toArray();
+        else  $list = self::statusByWhere($status, $uid)->where('is_del', 0)->where('uid', $uid)
+            ->field('add_time,seckill_id,bargain_id,combination_id,id,order_id,pay_price,total_num,total_price,pay_postage,total_postage,paid,status,refund_status,pay_type,coupon_price,deduction_price,pink_id,delivery_type,is_del,shipping_type')
+            ->order('add_time DESC')->page((int)$page, (int)$limit)->select()->toArray();
+        foreach ($list as $k => $order) {
+            $list[$k] = self::tidyOrder($order, true);
+        }
+
+        return $list;
+    }
+
+    /**
+     * 获取推广人地下用户的订单金额
+     * @param string $uid
+     * @param string $status
+     * @return array
+     */
+    public static function getUserOrderCount($uid = '', $status = '')
+    {
+        $res = self::statusByWhere($status, $uid)->where('uid', 'IN', $uid)->column('pay_price');
+        return $res;
+    }
+
+    /**
+     * 搜索某个订单详细信息
+     * @param $uid
+     * @param $order_id
+     * @return bool|mixed
+     * @throws DataNotFoundException
+     * @throws ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+    public static function searchUserOrder($uid, $order_id)
+    {
+        $order = self::where('uid', $uid)->where('order_id', $order_id)->where('is_del', 0)->field('seckill_id,bargain_id,combination_id,id,order_id,pay_price,total_num,total_price,pay_postage,total_postage,paid,status,refund_status,pay_type,coupon_price,deduction_price,delivery_type,shipping_type')
+            ->order('add_time DESC')->find();
+        if (!$order)
+            return false;
+        else
+            return self::tidyOrder($order->toArray(), true);
+
+    }
+
+    /**
+     * 订单评价信息记录
+     * @param $oid
+     * @return StoreOrderStatus|\think\Model
+     * @throws \Exception
+     */
+    public static function orderOver($oid)
+    {
+        $res = self::edit(['status' => '3'], $oid, 'id');
+        if (!$res) exception('评价后置操作失败!');
+        return StoreOrderStatus::status($oid, 'check_order_over', '用户评价');
+    }
+
+    /**
+     * 设置订单产品评价完毕事件
+     * @param $oid
+     * @return StoreOrderStatus|\think\Model
+     * @throws \Exception
+     */
+    public static function checkOrderOver($oid)
+    {
+        $uniqueList = StoreOrderCartInfo::where('oid', $oid)->column('unique', 'unique');
+        //订单产品全部评价完成
+        if (StoreProductReply::where('unique', 'IN', $uniqueList)->where('oid', $oid)->count() == count($uniqueList)) {
+            event('StoreProductOrderOver', [$oid]);
+            return self::orderOver($oid);
+        }
+    }
+
+
+    public static function getOrderStatusNum($uid)
+    {
+        $noBuy = (int)self::where('uid', $uid)->where('paid', 0)->where('is_del', 0)->where('pay_type', '<>', 'offline')->count();
+        $noPostageNoPink = (int)self::where('o.uid', $uid)->alias('o')->where('o.paid', 1)->where('o.pink_id', 0)->where('o.is_del', 0)->where('o.status', 0)->where('o.pay_type', '<>', 'offline')->count();
+        $noPostageYesPink = (int)self::where('o.uid', $uid)->alias('o')->join('StorePink p', 'o.pink_id = p.id')->where('p.status', 2)->where('o.paid', 1)->where('o.is_del', 0)->where('o.status', 0)->where('o.pay_type', '<>', 'offline')->count();
+        $noPostage = (int)bcadd($noPostageNoPink, $noPostageYesPink, 0);
+        $noTake = (int)self::where('uid', $uid)->where('paid', 1)->where('is_del', 0)->where('status', 1)->where('pay_type', '<>', 'offline')->count();
+        $noReply = (int)self::where('uid', $uid)->where('paid', 1)->where('is_del', 0)->where('status', 2)->count();
+        $noPink = (int)self::where('o.uid', $uid)->alias('o')->join('StorePink p', 'o.pink_id = p.id')->where('p.status', 1)->where('o.paid', 1)->where('o.is_del', 0)->where('o.status', 0)->where('o.pay_type', '<>', 'offline')->count();
+        $noRefund = (int)self::where('uid', $uid)->where('paid', 1)->where('is_del', 0)->where('refund_status', 'IN', '1,2')->count();
+        return compact('noBuy', 'noPostage', 'noTake', 'noReply', 'noPink', 'noRefund');
+    }
+
+    /**
+     * 购买商品赠送积分
+     * @param $order
+     * @return bool
+     * @throws \think\Exception
+     * @throws DataNotFoundException
+     * @throws ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+    public static function gainUserIntegral($order)
+    {
+        if ($order['gain_integral'] > 0) {
+            $userInfo = User::getUserInfo($order['uid']);
+            BaseModel::beginTrans();
+            $res1 = false != User::where('uid', $userInfo['uid'])->update(['integral' => bcadd($userInfo['integral'], $order['gain_integral'], 2)]);
+            $res2 = false != UserBill::income('购买商品赠送积分', $order['uid'], 'integral', 'gain', $order['gain_integral'], $order['id'], $userInfo['integral'], '购买商品赠送' . floatval($order['gain_integral']) . '积分');
+            $res = $res1 && $res2;
+            BaseModel::checkTrans($res);
+            return $res;
+        }
+        return true;
+    }
+
+    /**
+     * 获取当前订单中有没有拼团存在
+     * @param $pid
+     * @return int|string
+     */
+    public static function getIsOrderPink($pid = 0, $uid = 0)
+    {
+        return self::where('uid', $uid)->where('pink_id', $pid)->where('refund_status', 0)->where('is_del', 0)->count();
+    }
+
+    /**
+     * 获取order_id
+     * @param $pid
+     * @return mixed
+     */
+    public static function getStoreIdPink($pid = 0, $uid = 0)
+    {
+        return self::where('uid', $uid)->where('pink_id', $pid)->where('is_del', 0)->value('order_id');
+    }
+
+    /**
+     * 删除当前用户拼团未支付的订单
+     */
+    public static function delCombination()
+    {
+        self::where('combination', '>', 0)->where('paid', 0)->where('uid', User::getActiveUid())->delete();
+    }
+
+    public static function getUserPrice($uid = 0)
+    {
+        if (!$uid) return 0;
+        $price = self::where('paid', 1)->where('uid', $uid)->where('status', 2)->where('refund_status', 0)->column('pay_price', 'id');
+        $count = 0;
+        if ($price) {
+            foreach ($price as $v) {
+                $count = bcadd($count, $v, 2);
+            }
+        }
+        return $count;
+    }
+
+
+    /**
+     * 个人中心获取个人订单列表和订单搜索
+     * @param int $uid 用户uid
+     * @param int | string 查找订单类型
+     * @param int $first 分页
+     * @param int 每页显示多少条
+     * @param string $search 订单号
+     * @return array
+     * */
+    public static function getUserOrderSearchList($uid, $type, $page, $limit, $search)
+    {
+        if ($search) {
+            $order = self::searchUserOrder($uid, $search) ?: [];
+            $list = $order == false ? [] : [$order];
+        } else {
+            $list = self::getUserOrderList($uid, $type, $page, $limit);
+        }
+        foreach ($list as $k => $order) {
+            $list[$k] = self::tidyOrder($order, true);
+            if ($list[$k]['_status']['_type'] == 3) {
+                foreach ($order['cartInfo'] ?: [] as $key => $product) {
+                    $list[$k]['cartInfo'][$key]['is_reply'] = StoreProductReply::isReply($product['unique'], 'product');
+                    $list[$k]['cartInfo'][$key]['add_time'] = isset($product['add_time']) ? date('Y-m-d H:i', $product['add_time']) : '时间错误';
+                }
+            }
+        }
+        return $list;
+    }
+
+    /**
+     * 获取用户下级的订单
+     * @param int $xuid 下级用户用户uid
+     * @param int $uid 用户uid
+     * @param int $type 订单类型
+     * @param int $first 截取行数
+     * @param int $limit 展示条数
+     * @return array
+     * */
+    public static function getSubordinateOrderlist($xUid, $uid, $type, $first, $limit)
+    {
+        $list = [];
+        if (!$xUid) {
+            $arr = User::getOneSpreadUid($uid);
+            foreach ($arr as $v) $list = StoreOrder::getUserOrderList($v, $type, $first, $limit);
+        } else $list = self::getUserOrderList($xUid, $type, $first, $limit);
+        foreach ($list as $k => $order) {
+            $list[$k] = self::tidyOrder($order, true);
+            if ($list[$k]['_status']['_type'] == 3) {
+                foreach ($order['cartInfo'] ?: [] as $key => $product) {
+                    $list[$k]['cartInfo'][$key]['is_reply'] = StoreProductReply::isReply($product['unique'], 'product');
+                }
+            }
+        }
+        return $list;
+    }
+
+    /**
+     * 获取 今日 昨日 本月 订单金额
+     * @return mixed
+     */
+    public static function getOrderTimeData()
+    {
+        $to_day = strtotime(date('Y-m-d'));//今日
+        $pre_day = strtotime(date('Y-m-d', strtotime('-1 day')));//昨日
+        $now_month = strtotime(date('Y-m'));//本月
+        //今日成交额
+//        $data['todayPrice'] = (float)number_format(self::where('is_del', 0)->where('pay_time', '>=', $to_day)->where('paid', 1)->where('refund_status', 0)->value('sum(pay_price)'), 2) ?? 0;
+        $data['todayPrice'] = number_format(self::where('is_del', 0)->where('pay_time', '>=', $to_day)->where('paid', 1)->where('refund_status', 0)->value('sum(pay_price)'), 2) ?? 0;
+        //今日订单数
+        $data['todayCount'] = self::where('is_del', 0)->where('pay_time', '>=', $to_day)->where('paid', 1)->where('refund_status', 0)->count();
+        //昨日成交额
+        $data['proPrice'] = number_format(self::where('is_del', 0)->where('pay_time', '<', $to_day)->where('pay_time', '>=', $pre_day)->where('paid', 1)->where('refund_status', 0)->value('sum(pay_price)'), 2) ?? 0;
+        //昨日订单数
+        $data['proCount'] = self::where('is_del', 0)->where('pay_time', '<', $to_day)->where('pay_time', '>=', $pre_day)->where('paid', 1)->where('refund_status', 0)->count();
+        //本月成交额
+        $data['monthPrice'] = number_format(self::where('is_del', 0)->where('pay_time', '>=', $now_month)->where('paid', 1)->where('refund_status', 0)->value('sum(pay_price)'), 2) ?? 0;
+        //本月订单数
+        $data['monthCount'] = self::where('is_del', 0)->where('pay_time', '>=', $now_month)->where('paid', 1)->where('refund_status', 0)->count();
+        return $data;
+    }
+
+    /**
+     * 获取某个用户的订单统计数据
+     * @param $uid
+     * @return mixed
+     */
+    public static function getOrderData($uid)
+    {
+        //订单支付没有退款 数量
+        $data['order_count'] = self::where('is_del', 0)->where('paid', 1)->where('uid', $uid)->where('refund_status', 0)->count();
+        //订单支付没有退款 支付总金额
+        $data['sum_price'] = self::where('is_del', 0)->where('paid', 1)->where('uid', $uid)->where('refund_status', 0)->sum('pay_price');
+        //订单待支付 数量
+        $data['unpaid_count'] = self::statusByWhere(0, $uid)->where('is_del', 0)->where('uid', $uid)->count();
+        //订单待发货 数量
+        $data['unshipped_count'] = self::statusByWhere(1, $uid)->where('is_del', 0)->where('uid', $uid)->count();
+        //订单待收货 数量
+        $data['received_count'] = self::statusByWhere(2, $uid)->where('is_del', 0)->where('uid', $uid)->count();
+        //订单待评价 数量
+        $data['evaluated_count'] = self::statusByWhere(3, $uid)->where('is_del', 0)->where('uid', $uid)->count();
+        //订单已完成 数量
+        $data['complete_count'] = self::statusByWhere(4, $uid)->where('is_del', 0)->where('uid', $uid)->count();
+        //订单退款
+        $data['refund_count'] = self::statusByWhere(-1, $uid)->where('is_del', 0)->where('uid', $uid)->count();
+        return $data;
+    }
+
+
+    /**
+     * 获取订单统计数据
+     * @param $uid
+     * @return mixed
+     */
+    public static function getOrderDataAdmin()
+    {
+        //订单支付没有退款 数量
+        $data['order_count'] = self::where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->count();
+        //订单支付没有退款 支付总金额
+        $data['sum_price'] = self::where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->sum('pay_price');
+        //订单待支付 数量
+        $data['unpaid_count'] = self::statusByWhere(0, 0)->where('is_del', 0)->count();
+        //订单待发货 数量
+        $data['unshipped_count'] = self::statusByWhere(1, 0)->where('is_del', 0)->count();
+        //订单待收货 数量
+        $data['received_count'] = self::statusByWhere(2, 0)->where('is_del', 0)->count();
+        //订单待评价 数量
+        $data['evaluated_count'] = self::statusByWhere(3, 0)->where('is_del', 0)->count();
+        //订单已完成 数量
+        $data['complete_count'] = self::statusByWhere(4, 0)->where('is_del', 0)->count();
+        //订单退款 数量
+        $data['refund_count'] = self::statusByWhere(-3, 0)->where('is_del', 0)->count();
+        return $data;
+    }
+
+
+    /**
+     * 累计消费
+     * @param $uid
+     * @return float
+     */
+    public static function getOrderStatusSum($uid)
+    {
+        return self::where('uid', $uid)->where('is_del', 0)->where('paid', 1)->sum('pay_price');
+    }
+
+    public static function getPinkOrderId($id)
+    {
+        return self::where('id', $id)->value('order_id');
+    }
+
+    /**
+     * 未支付订单自动取消
+     * @param int $limit 分页截取条数
+     * @param string $prefid 缓存名称
+     * @param int $expire 缓存时间
+     * @return string|null
+     * @throws \Psr\SimpleCache\InvalidArgumentException
+     */
+    public static function orderUnpaidCancel()
+    {
+        //系统预设取消订单时间段
+        $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
+
+        //获取配置
+        $systemValue = SystemConfigService::more($keyValue);
+        //格式化数据
+        $systemValue = self::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
+        //检查是否有未支付的订单   未支付查询条件
+        $unPidCount = self::where('paid', 0)->where('pay_type', '<>', 'offline')->where('is_del', 0)->where('status', 0)->where('refund_status', 0)->count();
+        if (!$unPidCount) return null;
+        try {
+            $res = true;
+            // 未支付查询条件
+            $orderList = self::where('paid', 0)->where('pay_type', '<>', 'offline')->where('is_del', 0)->where('status', 0)->where('refund_status', 0)->field('add_time,pink_id,order_id,seckill_id,bargain_id,combination_id,status,cart_id,use_integral,refund_status,uid,unique,back_integral,coupon_id,paid,is_del')->select();
+            foreach ($orderList as $order) {
+                if ($order['seckill_id']) {
+                    //优先使用单独配置的过期时间
+                    $order_seckill_time = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
+                    $res = $res && self::RegressionAll($order_seckill_time, $order);
+                    unset($order_seckill_time);
+                } else if ($order['bargain_id']) {
+                    $order_bargain_time = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
+                    $res = $res && self::RegressionAll($order_bargain_time, $order);
+                    unset($order_bargain_time);
+                } else if ($order['pink_id'] || $order['combination_id']) {
+                    $order_pink_time = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
+                    $res = $res && self::RegressionAll($order_pink_time, $order);
+                    unset($order_pink_time);
+                } else {
+                    $res = $res && self::RegressionAll($systemValue['order_cancel_time'], $order);
+                }
+            }
+            if (!$res) throw new \Exception('更新错误');
+            unset($orderList, $res, $pages);
+            return null;
+        } catch (PDOException $e) {
+            Log::error('未支付自动取消时发生数据库查询错误,错误原因为:' . $e->getMessage());
+            throw new \Exception($e->getMessage());
+        } catch (\think\Exception $e) {
+            Log::error('未支付自动取消时发生系统错误,错误原因为:' . $e->getMessage());
+            throw new \Exception($e->getMessage());
+        }
+
+    }
+
+
+    /**
+     * 未支付订单超过预设时间回退所有,如果不设置未支付过期时间,将不取消订单
+     * @param $time 预设时间
+     * @param $order 订单详情
+     * @return bool
+     * @throws DataNotFoundException
+     * @throws ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+    protected static function RegressionAll($time, $order)
+    {
+        if ($time == 0) return true;
+        if (($order['add_time'] + bcmul($time, 3600, 0)) < time()) {
+            $res1 = self::RegressionStock($order);
+            $res2 = self::RegressionIntegral($order);
+            $res3 = self::RegressionCoupon($order);
+            $res = $res1 && $res2 && $res3;
+            if ($res) $res = false !== self::where('order_id', $order['order_id'])->update(['is_del' => 1, 'mark' => '订单未支付已超过系统预设时间']);
+            unset($res1, $res2, $res3);
+            return $res;
+        } else
+            return true;
+    }
+
+
+    /**
+     * 格式化数据
+     * @param array $array 原本数据键
+     * @param $value 需要格式化的数据
+     * @param int $default 默认值
+     * @return mixed
+     */
+    protected static function setValeTime(array $array, $value, $default = 0)
+    {
+        foreach ($array as $item) {
+            if (!isset($value[$item]))
+                $value[$item] = $default;
+            else if (is_string($value[$item]))
+                $value[$item] = (float)$value[$item];
+        }
+        return $value;
+    }
+
+    public static function getOrderTotalPrice($cartInfo)
+    {
+        $totalPrice = 0;
+        foreach ($cartInfo as $cart) {
+            $totalPrice = bcadd($totalPrice, bcmul($cart['cart_num'], $cart['truePrice'], 2), 2);
+        }
+        return $totalPrice;
+    }
+
+    public static function getOrderCostPrice($cartInfo)
+    {
+        $costPrice = 0;
+        foreach ($cartInfo as $cart) {
+            $costPrice = bcadd($costPrice, bcmul($cart['cart_num'], $cart['costPrice'], 2), 2);
+        }
+        return $costPrice;
+    }
+
+    public static function getCombinationOrderCostPrice($cartInfo)
+    {
+        $costPrice = 0;
+        foreach ($cartInfo as $cart) {
+            if ($cart['combination_id']) {
+                $costPrice = bcadd($costPrice, bcmul($cart['cart_num'], StoreCombination::where('id', $cart['combination_id'])->value('price'), 2), 2);
+            }
+        }
+        return (float)$costPrice;
+    }
+
+    public static function yueRefundAfter($order)
+    {
+
+    }
+
+    /**
+     * 获取余额支付的金额
+     * @param $uid
+     * @return float|int
+     */
+    public static function getOrderStatusYueSum($uid)
+    {
+        return self::where('uid', $uid)->where('is_del', 0)->where('is_del', 0)->where('pay_type', 'yue')->where('paid', 1)->sum('pay_price');
+    }
+
+    /**
+     * 砍价支付成功订单数量
+     * @param $bargain
+     * @return int
+     */
+    public static function getBargainPayCount($bargain)
+    {
+        return self::where('bargain_id', $bargain)->where(['paid' => 1, 'refund_status' => 0])->count();
+    }
+
+    /**
+     * 7天自动收货
+     * @return bool
+     */
+    public static function startTakeOrder()
+    {
+
+        //7天前时间戳
+        $systemDeliveryTime = SystemConfigService::get('system_delivery_time') ?? 0;
+        //0为取消自动收货功能
+        if ($systemDeliveryTime == 0) return true;
+        $sevenDay = strtotime(date('Y-m-d H:i:s', strtotime('-' . $systemDeliveryTime . ' day')));
+        $model = new self;
+        $model = $model->alias('o');
+        $model = $model->join('StoreOrderStatus s', 's.oid=o.id');
+        $model = $model->where('o.paid', 1);
+        $model = $model->where('s.change_type', 'delivery_goods');
+        $model = $model->where('s.change_time', '<', $sevenDay);
+        $model = $model->where('o.status', 1);
+        $model = $model->where('o.refund_status', 0);
+        $model = $model->where('o.is_del', 0);
+        $orderInfo = $model->column('id', 'id');
+        if (!count($orderInfo)) return true;
+        $res = true;
+        foreach ($orderInfo as $key => &$item) {
+            $order = self::get($item);
+            if ($order['status'] == 2) continue;
+            if ($order['paid'] == 1 && $order['status'] == 1) $data['status'] = 2;
+            else if ($order['pay_type'] == 'offline') $data['status'] = 2;
+            else continue;
+            if (!self::edit($data, $item, 'id')) continue;
+            try {
+                OrderRepository::storeProductOrderTakeDeliveryAdmin($order, $item);
+                $res = $res && true;
+            } catch (\Exception $e) {
+                $res = $res && false;
+            }
+            $res = $res && StoreOrderStatus::status($item, 'take_delivery', '已收货[自动收货]');
+        }
+
+        if (!$res) {
+            throw new \Exception('');
+        }
+
+    }
+
+    /**
+     * 获取订单信息
+     * @param $id
+     * @param string $field
+     * @return array|null|\think\Model
+     * @throws DataNotFoundException
+     * @throws ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+    public static function getOrderInfo($id, $field = 'order_id')
+    {
+        return self::where('id', $id)->field($field)->find();
+    }
+
+    /**
+     * 订单每月统计数据
+     * @param $page
+     * @param $limit
+     * @return array
+     */
+    public static function getOrderDataPriceCount($page, $limit, $start, $stop)
+    {
+        if (!$limit) return [];
+        $model = new self;
+        if ($start != '' && $stop != '') $model = $model->where('pay_time', '>', $start)->where('pay_time', '<=', $stop);
+        $model = $model->field('sum(pay_price) as price,count(id) as count,FROM_UNIXTIME(pay_time, \'%m-%d\') as time');
+        $model = $model->where('is_del', 0);
+        $model = $model->where('paid', 1);
+        $model = $model->where('refund_status', 0);
+        $model = $model->group("FROM_UNIXTIME(pay_time, '%Y-%m-%d')");
+        $model = $model->order('pay_time DESC');
+        if ($page) $model = $model->page($page, $limit);
+        return $model->select();
+    }
+
+    /**
+     * 前台订单管理订单列表获取
+     * @param $where
+     * @return mixed
+     */
+    public static function orderList($where)
+    {
+        $model = self::getOrderWhere($where, self::alias('a')->join('user r', 'r.uid=a.uid', 'LEFT'), 'a.', 'r')->field('a.id,a.order_id,a.add_time,a.status,a.total_num,a.total_price,a.total_postage,a.pay_price,a.pay_postage,a.paid,a.refund_status,a.remark,a.pay_type');
+        if ($where['order'] != '') {
+            $model = $model->order(self::setOrder($where['order']));
+        } else {
+            $model = $model->order('a.id desc');
+        }
+        $data = ($data = $model->page((int)$where['page'], (int)$where['limit'])->select()) && count($data) ? $data->toArray() : [];
+        return self::tidyAdminOrder($data);
+    }
+
+    /**
+     * 前台订单管理 订单信息设置
+     * @param $data
+     * @param bool $status
+     * @return mixed
+     * @throws DataNotFoundException
+     * @throws ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+    public static function tidyAdminOrder($data, $status = false)
+    {
+        foreach ($data as &$item) {
+            $_info = StoreOrderCartInfo::where('oid', $item['id'])->field('cart_info')->select()->toArray();
+            foreach ($_info as $k => $v) {
+                if (!is_array($v['cart_info']))
+                    $_info[$k]['cart_info'] = json_decode($v['cart_info'], true);
+            }
+            foreach ($_info as $k => $v) {
+                unset($_info[$k]['cart_info']['type'], $_info[$k]['cart_info']['product_id'], $_info[$k]['cart_info']['combination_id'], $_info[$k]['cart_info']['seckill_id'], $_info[$k]['cart_info']['bargain_id'], $_info[$k]['cart_info']['bargain_id'], $_info[$k]['cart_info']['truePrice'], $_info[$k]['cart_info']['vip_truePrice'], $_info[$k]['cart_info']['trueStock'], $_info[$k]['cart_info']['costPrice'], $_info[$k]['cart_info']['productInfo']['id'], $_info[$k]['cart_info']['productInfo']['vip_price'], $_info[$k]['cart_info']['productInfo']['postage'], $_info[$k]['cart_info']['productInfo']['give_integral'], $_info[$k]['cart_info']['productInfo']['sales'], $_info[$k]['cart_info']['productInfo']['stock'], $_info[$k]['cart_info']['productInfo']['unit_name'], $_info[$k]['cart_info']['productInfo']['is_postage'], $_info[$k]['cart_info']['productInfo']['slider_image'], $_info[$k]['cart_info']['productInfo']['cost'], $_info[$k]['cart_info']['productInfo']['mer_id'], $_info[$k]['cart_info']['productInfo']['cate_id'], $_info[$k]['cart_info']['productInfo']['is_show'], $_info[$k]['cart_info']['productInfo']['store_info'], $_info[$k]['cart_info']['productInfo']['is_del'], $_info[$k]['cart_info']['is_pay'], $_info[$k]['cart_info']['is_del'], $_info[$k]['cart_info']['is_new'], $_info[$k]['cart_info']['add_time'], $_info[$k]['cart_info']['id'], $_info[$k]['cart_info']['uid'], $_info[$k]['cart_info']['product_attr_unique']);
+                $_info[$k]['cart_info']['productInfo']['suk'] = '';
+                if (isset($v['cart_info']['productInfo']['attrInfo'])) {
+                    $_info[$k]['cart_info']['productInfo']['image'] = $_info[$k]['cart_info']['productInfo']['attrInfo']['image'];
+                    $_info[$k]['cart_info']['productInfo']['price'] = $_info[$k]['cart_info']['productInfo']['attrInfo']['price'];
+                    $_info[$k]['cart_info']['productInfo']['suk'] = $_info[$k]['cart_info']['productInfo']['attrInfo']['suk'];
+                    unset($_info[$k]['cart_info']['productInfo']['attrInfo']);
+                }
+                if (!isset($v['cart_info']['productInfo']['ot_price'])) {
+                    $_info[$k]['cart_info']['productInfo']['ot_price'] = $v['cart_info']['productInfo']['price'];
+                }
+            }
+            $item['_info'] = $_info;
+            $item['add_time'] = date('Y-m-d H:i:s', $item['add_time']);
+//            if($item['pink_id'] || $item['combination_id']){
+//                $pinkStatus = StorePink::where('order_id_key',$item['id'])->value('status');
+//                switch ($pinkStatus){
+//                    case 1:
+//                        $item['pink_name'] = '[拼团订单]正在进行中';
+//                        $item['color'] = '#f00';
+//                        break;
+//                    case 2:
+//                        $item['pink_name'] = '[拼团订单]已完成';
+//                        $item['color'] = '#00f';
+//                        break;
+//                    case 3:
+//                        $item['pink_name'] = '[拼团订单]未完成';
+//                        $item['color'] = '#f0f';
+//                        break;
+//                    default:
+//                        $item['pink_name'] = '[拼团订单]历史订单';
+//                        $item['color'] = '#457856';
+//                        break;
+//                }
+//            }elseif ($item['seckill_id']){
+//                $item['pink_name'] = '[秒杀订单]';
+//                $item['color'] = '#32c5e9';
+//            }elseif ($item['bargain_id']){
+//                $item['pink_name'] = '[砍价订单]';
+//                $item['color'] = '#12c5e9';
+//            }else{
+//                $item['pink_name'] = '[普通订单]';
+//                $item['color'] = '#895612';
+//            }
+//            if($item['paid']==1){
+//                switch ($item['pay_type']){
+//                    case 'weixin':
+//                        $item['pay_type_name']='微信支付';
+//                        break;
+//                    case 'yue':
+//                        $item['pay_type_name']='余额支付';
+//                        break;
+//                    case 'offline':
+//                        $item['pay_type_name']='线下支付';
+//                        break;
+//                    default:
+//                        $item['pay_type_name']='其他支付';
+//                        break;
+//                }
+//            }else{
+//                switch ($item['pay_type']){
+//                    default:
+//                        $item['pay_type_name']='未支付';
+//                        break;
+//                    case 'offline':
+//                        $item['pay_type_name']='线下支付';
+//                        $item['pay_type_info']=1;
+//                        break;
+//                }
+//            }
+
+            if ($status) {
+                $status = [];
+                if (!$item['paid'] && $item['pay_type'] == 'offline' && !$item['status'] >= 2) {
+                    $status['_type'] = 9;
+                    $status['_title'] = '线下付款';
+                    $status['_msg'] = '商家处理中,请耐心等待';
+                    $status['_class'] = 'nobuy';
+                } else if (!$item['paid']) {
+                    $status['_type'] = 0;
+                    $status['_title'] = '未支付';
+                    //系统预设取消订单时间段
+                    $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
+                    //获取配置
+                    $systemValue = SystemConfigService::more($keyValue);
+                    //格式化数据
+                    $systemValue = self::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
+                    if ($item['pink_id'] || $item['combination_id']) {
+                        $order_pink_time = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
+                        $time = bcadd($item['add_time'], $order_pink_time * 3600, 0);
+                        $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
+                    } else if ($item['seckill_id']) {
+                        $order_seckill_time = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
+                        $time = bcadd($item['add_time'], $order_seckill_time * 3600, 0);
+                        $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
+                    } else if ($item['bargain_id']) {
+                        $order_bargain_time = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
+                        $time = bcadd($item['add_time'], $order_bargain_time * 3600, 0);
+                        $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
+                    } else {
+                        $time = bcadd($item['add_time'], $systemValue['order_cancel_time'] * 3600, 0);
+                        $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
+                    }
+                    $status['_class'] = 'nobuy';
+                } else if ($item['refund_status'] == 1) {
+                    $status['_type'] = -1;
+                    $status['_title'] = '申请退款中';
+                    $status['_msg'] = '商家审核中,请耐心等待';
+                    $status['_class'] = 'state-sqtk';
+                } else if ($item['refund_status'] == 2) {
+                    $status['_type'] = -2;
+                    $status['_title'] = '已退款';
+                    $status['_msg'] = '已为您退款,感谢您的支持';
+                    $status['_class'] = 'state-sqtk';
+                } else if (!$item['status']) {
+                    if ($item['pink_id']) {
+                        if (StorePink::where('id', $item['pink_id'])->where('status', 1)->count()) {
+                            $status['_type'] = 11;
+                            $status['_title'] = '拼团中';
+                            $status['_msg'] = '等待其他人参加拼团';
+                            $status['_class'] = 'state-nfh';
+                        } else {
+                            $status['_type'] = 1;
+                            $status['_title'] = '未发货';
+                            $status['_msg'] = '商家未发货,请耐心等待';
+                            $status['_class'] = 'state-nfh';
+                        }
+                    } else {
+                        $status['_type'] = 1;
+                        $status['_title'] = '未发货';
+                        $status['_msg'] = '商家未发货,请耐心等待';
+                        $status['_class'] = 'state-nfh';
+                    }
+                } else if ($item['status'] == 1) {
+                    if ($item['delivery_type'] == 'send') {//TODO 送货
+                        $status['_type'] = 2;
+                        $status['_title'] = '待收货';
+                        $status['_msg'] = date('m月d日H时i分', StoreOrderStatus::getTime($item['id'], 'delivery')) . '服务商已送货';
+                        $status['_class'] = 'state-ysh';
+                    } else {//TODO  发货
+                        $status['_type'] = 2;
+                        $status['_title'] = '待收货';
+                        $status['_msg'] = date('m月d日H时i分', StoreOrderStatus::getTime($item['id'], 'delivery_goods')) . '服务商已发货';
+                        $status['_class'] = 'state-ysh';
+                    }
+                } else if ($item['status'] == 2) {
+                    $status['_type'] = 3;
+                    $status['_title'] = '待评价';
+                    $status['_msg'] = '已收货,快去评价一下吧';
+                    $status['_class'] = 'state-ypj';
+                } else if ($item['status'] == 3) {
+                    $status['_type'] = 4;
+                    $status['_title'] = '交易完成';
+                    $status['_msg'] = '交易完成,感谢您的支持';
+                    $status['_class'] = 'state-ytk';
+                }
+                if (isset($item['pay_type']))
+                    $status['_payType'] = isset(self::$payType[$item['pay_type']]) ? self::$payType[$item['pay_type']] : '其他方式';
+                if (isset($item['delivery_type']))
+                    $status['_deliveryType'] = isset(self::$deliveryType[$item['delivery_type']]) ? self::$deliveryType[$item['delivery_type']] : '其他方式';
+                $item['_status'] = $status;
+            } else {
+                if ($item['paid'] == 0 && $item['status'] == 0) {
+                    $item['status_name'] = '未支付';
+                } else if ($item['paid'] == 1 && $item['status'] == 0 && $item['refund_status'] == 0) {
+                    $item['status_name'] = '未发货';
+                } else if ($item['paid'] == 1 && $item['status'] == 1 && $item['refund_status'] == 0) {
+                    $item['status_name'] = '待收货';
+                } else if ($item['paid'] == 1 && $item['status'] == 2 && $item['refund_status'] == 0) {
+                    $item['status_name'] = '待评价';
+                } else if ($item['paid'] == 1 && $item['status'] == 3 && $item['refund_status'] == 0) {
+                    $item['status_name'] = '已完成';
+                }
+            }
+//            unset($item['refund_status']);
+//            else if($item['paid']==1 && $item['refund_status']==1){
+//                $item['status_name']=<<<HTML
+//<b style="color:#f124c7">申请退款</b><br/>
+//<span>退款原因:{$item['refund_reason_wap']}</span>
+//HTML;
+//            }else if($item['paid']==1 && $item['refund_status']==2){
+//                $item['status_name']='已退款';
+//            }
+//            if($item['paid']==0 && $item['status']==0 && $item['refund_status']==0){
+//                $item['_status']=1;
+//            }else if($item['paid']==1 && $item['status']==0 && $item['refund_status']==0){
+//                $item['_status']=2;
+//            }else if($item['paid']==1 && $item['refund_status']==1){
+//                $item['_status']=3;
+//            }else if($item['paid']==1 && $item['status']==1 && $item['refund_status']==0){
+//                $item['_status']=4;
+//            }else if($item['paid']==1 && $item['status']==2 && $item['refund_status']==0){
+//                $item['_status']=5;
+//            }else if($item['paid']==1 && $item['status']==3 && $item['refund_status']==0){
+//                $item['_status']=6;
+//            }else if($item['paid']==1 && $item['refund_status']==2){
+//                $item['_status']=7;
+//            }
+        }
+        return $data;
+    }
+
+    /**
+     * 处理where条件
+     * @param $where
+     * @param $model
+     * @param string $aler
+     * @param string $join
+     * @return StoreOrder|null
+     */
+    public static function getOrderWhere($where, $model, $aler = '', $join = '')
+    {
+        if (isset($where['status']) && $where['status'] != '') $model = self::statusWhere($where['status'], $model, $aler);
+        if (isset($where['is_del']) && $where['is_del'] != '' && $where['is_del'] != -1) $model = $model->where($aler . 'is_del', $where['is_del']);
+        if (isset($where['combination_id'])) {
+            if ($where['combination_id'] == '普通订单') {
+                $model = $model->where($aler . 'combination_id', 0)->where($aler . 'seckill_id', 0)->where($aler . 'bargain_id', 0);
+            }
+            if ($where['combination_id'] == '拼团订单') {
+                $model = $model->where($aler . 'combination_id', ">", 0)->where($aler . 'pink_id', ">", 0);
+            }
+            if ($where['combination_id'] == '秒杀订单') {
+                $model = $model->where($aler . 'seckill_id', ">", 0);
+            }
+            if ($where['combination_id'] == '砍价订单') {
+                $model = $model->where($aler . 'bargain_id', ">", 0);
+            }
+        }
+        if (isset($where['type'])) {
+            switch ($where['type']) {
+                case 1:
+                    $model = $model->where($aler . 'combination_id', 0)->where($aler . 'seckill_id', 0)->where($aler . 'bargain_id', 0);
+                    break;
+                case 2:
+                    $model = $model->where($aler . 'combination_id', ">", 0);
+                    break;
+                case 3:
+                    $model = $model->where($aler . 'seckill_id', ">", 0);
+                    break;
+                case 4:
+                    $model = $model->where($aler . 'bargain_id', ">", 0);
+                    break;
+            }
+        }
+
+        if (isset($where['real_name']) && $where['real_name'] != '')
+            $model = $model->where($aler . 'order_id|' . $aler . 'real_name|' . $aler . 'user_phone' . ($join ? '|' . $join . '.nickname|' . $join . '.uid' : ''), 'LIKE', "%$where[real_name]%");
+        if (isset($where['data']) && $where['data'] !== '')
+            $model = self::getModelTime($where, $model, $aler . 'add_time');
+        return $model;
+    }
+
+    /**
+     * 设置where条件
+     * @param $status
+     * @param null $model
+     * @param string $alert
+     * @return StoreOrder|null
+     */
+    public static function statusWhere($status, $model = null, $alert = '')
+    {
+        if ($model == null) $model = new self;
+        if ('' === $status)
+            return $model;
+        else if ($status == 0)//未支付
+            return $model->where($alert . 'paid', 0)->where($alert . 'status', 0)->where($alert . 'refund_status', 0);
+        else if ($status == 1)//已支付 未发货
+            return $model->where($alert . 'paid', 1)->where($alert . 'status', 0)->where($alert . 'refund_status', 0);
+        else if ($status == 2)//已支付  待收货
+            return $model->where($alert . 'paid', 1)->where($alert . 'status', 1)->where($alert . 'refund_status', 0);
+        else if ($status == 3)// 已支付  已收货  待评价
+            return $model->where($alert . 'paid', 1)->where($alert . 'status', 2)->where($alert . 'refund_status', 0);
+        else if ($status == 4)// 交易完成
+            return $model->where($alert . 'paid', 1)->where($alert . 'status', 3)->where($alert . 'refund_status', 0);
+        else if ($status == -1)//退款中
+            return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 1);
+        else if ($status == -2)//已退款
+            return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 2);
+        else if ($status == -3)//退款
+            return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 'in', '1,2');
+        else
+            return $model;
+    }
+
+    /**
+     * 订单详情 管理员
+     * @param $orderId
+     * @param string $field
+     * @return array|null|\think\Model
+     * @throws DataNotFoundException
+     * @throws ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+    public static function getAdminOrderDetail($orderId, $field = '*')
+    {
+        return self::where('order_id', $orderId)->field($field)->find();
+    }
+
+    /**
+     * 获取指定时间区间的支付金额 管理员
+     * @param $start
+     * @param $stop
+     * @return float
+     */
+    public static function getOrderTimeBusinessVolumePrice($start, $stop)
+    {
+        return self::where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->where('add_time', '>=', $start)->where('add_time', '<', $stop)->sum('pay_price');
+    }
+
+    /**
+     * 获取指定时间区间的支付订单数量 管理员
+     * @param $start
+     * @param $stop
+     * @return float
+     */
+    public static function getOrderTimeBusinessVolumeNumber($start, $stop)
+    {
+        return self::where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->where('add_time', '>=', $start)->where('add_time', '<', $stop)->count();
+    }
+
+    /**
+     * 获取当前时间到指定时间的支付金额 管理员
+     * @param $start 开始时间
+     * @param $stop  结束时间
+     * @return mixed
+     */
+    public static function chartTimePrice($start, $stop)
+    {
+        $model = new self;
+        $model = $model->field('sum(pay_price) as num,FROM_UNIXTIME(add_time, \'%Y-%m-%d\') as time');
+        $model = $model->where('is_del', 0);
+        $model = $model->where('paid', 1);
+        $model = $model->where('refund_status', 0);
+        $model = $model->where('add_time', '>=', $start);
+        $model = $model->where('add_time', '<', $stop);
+        $model = $model->group("FROM_UNIXTIME(add_time, '%Y-%m-%d')");
+        $model = $model->order('add_time ASC');
+        return $model->select();
+    }
+
+    /**
+     * 获取当前时间到指定时间的支付订单数 管理员
+     * @param $start 开始时间
+     * @param $stop  结束时间
+     * @return mixed
+     */
+    public static function chartTimeNumber($start, $stop)
+    {
+        $model = new self;
+        $model = $model->field('count(id) as num,FROM_UNIXTIME(add_time, \'%Y-%m-%d\') as time');
+        $model = $model->where('is_del', 0);
+        $model = $model->where('paid', 1);
+        $model = $model->where('refund_status', 0);
+        $model = $model->where('add_time', '>=', $start);
+        $model = $model->where('add_time', '<', $stop);
+        $model = $model->group("FROM_UNIXTIME(add_time, '%Y-%m-%d')");
+        $model = $model->order('add_time ASC');
+        return $model->select();
+    }
+
+    /**
+     * 修改支付方式为线下支付
+     * @param $orderId
+     * @return bool
+     */
+    public static function setOrderTypePayOffline($orderId)
+    {
+        return self::edit(['pay_type' => 'offline'], $orderId, 'order_id');
+    }
+
+    /**
+     * 线下付款
+     * @param $id
+     * @return $this
+     */
+    public static function updateOffline($id)
+    {
+        $count = self::where('id', $id)->count();
+        if (!$count) return self::setErrorInfo('订单不存在');
+        $count = self::where('id', $id)->where('paid', 0)->count();
+        if (!$count) return self::setErrorInfo('订单已支付');
+        $res = self::where('id', $id)->update(['paid' => 1, 'pay_time' => time()]);
+        return $res;
+    }
+
+    /**
+     * 向创建订单10分钟未付款的用户发送短信
+     */
+    public static function sendTen()
+    {
+        $list = self::where('paid', 0)->where('is_del', 0)->where('is_system_del', 0)->where('add_time', '>', time() - 900)->where('add_time', '<', time() - 600)->column('user_phone');
+        foreach ($list as $phone) {
+            ShortLetterRepositories::send(true, $phone, [], 'ORDER_PAY_FALSE');
+        }
+    }
+
+    public function productInfo()
+    {
+        return $this->hasMany(StoreProductReply::class, 'oid', 'id');
+    }
+
+    public static function setOrderProductReplyWhere($where)
+    {
+        $model = self::where('status', 3)->order('add_time desc')->whereIn('id', function ($query) {
+            $query->name('store_order')->alias('o')->join('store_product_reply a', 'a.oid = o.id')->group('o.id')->field('o.id')->select();
+        })->with('productInfo', function ($query) use ($where) {
+            $alias = '';
+            if (isset($where['title']) && $where['title'] != '')
+                $query->where("{$alias}comment", 'LIKE', "%$where[title]%");
+            if (isset($where['is_reply']) && $where['is_reply'] != '') {
+                if ($where['is_reply'] >= 0) {
+                    $query->where("{$alias}is_reply", $where['is_reply']);
+                } else {
+                    $query->where("{$alias}is_reply", '>', 0);
+                }
+            }
+            if (isset($where['producr_id']) && $where['producr_id'] != 0)
+                $query->where($alias . 'product_id', $where['producr_id']);
+            $query->where("{$alias}is_del", 0);
+        });
+        return $model;
+
+    }
+
+    public static function getOrderProductReplyList($where)
+    {
+        $list = self::setOrderProductReplyWhere($where)->page((int)$where['message_page'], (int)$where['limit'])->select();
+        $list = count($list) ? $list->toArray() : [];
+        foreach ($list as $key => $item) {
+            if (isset($item['productInfo']) && is_array($item['productInfo']) && count($item['productInfo'])) {
+                foreach ($item['productInfo'] as $k => $v) {
+                    if (!$v['nickname'] && $v['uid']) {
+                        $v['nickname'] = User::where('uid', $v['uid'])->value('nickname');
+                        $v['avatar'] = User::where('uid', $v['uid'])->value('avatar');
+                    }
+                    $v['image'] = '';
+                    $v['store_name'] = '';
+                    if ($v['product_id']) {
+                        $product = StoreProduct::where('id', $v['product_id'])->field(['image', 'store_name'])->find();
+                        if ($product) {
+                            $v['image'] = $product['image'];
+                            $v['store_name'] = $product['store_name'];
+                        }
+                    }
+                    $list[$key]['productInfo'][$k] = $v;
+                }
+            }
+        }
+        $count = self::setOrderProductReplyWhere($where)->count();
+        return compact('list', 'count');
+    }
+
+>>>>>>> 386b37d33e5ba817cba00df29efaefbd692e4dd1
 }

+ 52 - 0
app/models/user/UserPartake.php

@@ -1,3 +1,4 @@
+<<<<<<< HEAD
 <?php
 
 
@@ -47,4 +48,55 @@ class UserPartake extends Model
     }
 
 
+=======
+<?php
+
+
+namespace app\models\user;
+
+
+use app\admin\model\order\StoreOrder;
+use app\admin\model\user\User;
+use think\Model;
+
+class UserPartake extends Model
+{
+    protected $name = 'user_partake';
+
+
+    protected $autoWriteTimestamp = true;
+
+    /**
+     * 参与累计金额
+     * @param $order
+     * @return void
+     */
+    public static function cumulative()
+    {
+        $user = User::select();
+        foreach ($user as $item){
+            $partake = UserPartake::where('uid', $item['uid'])->where('status', 0)->find();
+            if ($partake){
+                $uids = User::where('spread_uid', $item['uid'])->column('uid');
+                $money = StoreOrder::where('uid', 'in', $uids)
+                    ->where('paid', 1)
+                    ->where('is_participate', 0)
+                    ->sum('pay_price');
+                $out = Out::where('id', $partake['out_id'])->find();
+                if ($money >= $out['number']){
+                    User::where('uid', $item['uid'])->dec('pay_price', $money)->update();
+                    User::where('uid', $item['uid'])->inc('use_price', $money)->update();
+                    $partake['status'] = 1;
+                    $partake['money'] = $money;
+                    $partake->save();
+                    StoreOrder::where('uid', 'in', $uids)->where('paid', 1)->where('is_participate', 0)->update(['is_participate' => 1]);
+                }
+            }
+        }
+
+
+    }
+
+
+>>>>>>> 386b37d33e5ba817cba00df29efaefbd692e4dd1
 }

+ 216 - 0
crmeb/repositories/OrderRepository.php

@@ -1,3 +1,4 @@
+<<<<<<< HEAD
 <?php
 
 namespace crmeb\repositories;
@@ -211,4 +212,219 @@ class OrderRepository
 
     }
 
+=======
+<?php
+
+namespace crmeb\repositories;
+
+use app\models\store\StoreOrder;
+use app\models\user\User;
+use app\models\user\WechatUser;
+use app\admin\model\order\StoreOrder as AdminStoreOrder;
+use crmeb\services\AlipayService;
+use crmeb\services\MiniProgramService;
+use crmeb\services\SystemConfigService;
+use crmeb\services\WechatService;
+
+/**
+ * Class OrderRepository
+ * @package crmeb\repositories
+ */
+class OrderRepository
+{
+
+    /**
+     * TODO 小程序JS支付
+     * @param $orderId
+     * @param string $field
+     * @return array|string
+     * @throws \think\db\exception\DataNotFoundException
+     * @throws \think\db\exception\ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+    public static function jsPay($orderId, $field = 'order_id')
+    {
+        if (is_string($orderId))
+            $orderInfo = StoreOrder::where($field, $orderId)->find();
+        else
+            $orderInfo = $orderId;
+        if (!$orderInfo || !isset($orderInfo['paid'])) exception('支付订单不存在!');
+        if ($orderInfo['paid']) exception('支付已支付!');
+        if ($orderInfo['pay_price'] <= 0) exception('该支付无需支付!');
+        $openid = WechatUser::getOpenId($orderInfo['uid']);
+        $bodyContent = StoreOrder::getProductTitle($orderInfo['cart_id']);
+        $site_name = sys_config('site_name');
+        if (!$bodyContent && !$site_name) exception('支付参数缺少:请前往后台设置->系统设置-> 填写 网站名称');
+        return MiniProgramService::jsPay($openid, $orderInfo['order_id'], $orderInfo['pay_price'], 'product', StoreOrder::getSubstrUTf8($site_name . ' - ' . $bodyContent, 30));
+    }
+
+    /**
+     * 微信公众号JS支付
+     * @param $orderId
+     * @param string $field
+     * @return array|string
+     * @throws \think\db\exception\DataNotFoundException
+     * @throws \think\db\exception\ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+    public static function wxPay($orderId, $field = 'order_id')
+    {
+        if (is_string($orderId))
+            $orderInfo = StoreOrder::where($field, $orderId)->find();
+        else
+            $orderInfo = $orderId;
+        if (!$orderInfo || !isset($orderInfo['paid'])) exception('支付订单不存在!');
+        if ($orderInfo['paid']) exception('支付已支付!');
+        if ($orderInfo['pay_price'] <= 0) exception('该支付无需支付!');
+        $openid = WechatUser::uidToOpenid($orderInfo['uid'], 'openid');
+        $bodyContent = StoreOrder::getProductTitle($orderInfo['cart_id']);
+        $site_name = sys_config('site_name');
+        if (!$bodyContent && !$site_name) exception('支付参数缺少:请前往后台设置->系统设置-> 填写 网站名称');
+        return WechatService::jsPay($openid, $orderInfo['order_id'], $orderInfo['pay_price'], 'product', StoreOrder::getSubstrUTf8($site_name . ' - ' . $bodyContent, 30));
+    }
+
+    /**
+     * 微信h5支付
+     * @param $orderId
+     * @param string $field
+     * @return array|string
+     * @throws \think\db\exception\DataNotFoundException
+     * @throws \think\db\exception\ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+    public static function h5Pay($orderId, $field = 'order_id')
+    {
+        if (is_string($orderId))
+            $orderInfo = StoreOrder::where($field, $orderId)->find();
+        else
+            $orderInfo = $orderId;
+        if (!$orderInfo || !isset($orderInfo['paid'])) exception('支付订单不存在!');
+        if ($orderInfo['paid']) exception('支付已支付!');
+        if ($orderInfo['pay_price'] <= 0) exception('该支付无需支付!');
+        $bodyContent = StoreOrder::getProductTitle($orderInfo['cart_id']);
+        $site_name = sys_config('site_name');
+        if (!$bodyContent && !$site_name) exception('支付参数缺少:请前往后台设置->系统设置-> 填写 网站名称');
+        return WechatService::paymentPrepare(null, $orderInfo['order_id'], $orderInfo['pay_price'], 'product', StoreOrder::getSubstrUTf8($site_name . ' - ' . $bodyContent, 30), '', 'MWEB');
+    }
+
+    public static function aliPay($orderId, $field = 'order_id')
+    {
+        if (is_string($orderId))
+            $orderInfo = StoreOrder::where($field, $orderId)->where('is_del', 0)->find();
+        else
+            $orderInfo = $orderId;
+        if (!$orderInfo || !isset($orderInfo['paid'])) exception('支付订单不存在!');
+        if ($orderInfo['paid']) exception('支付已支付!');
+        if ($orderInfo['pay_price'] <= 0) exception('该支付无需支付!');
+        $bodyContent = StoreOrder::getProductTitle($orderInfo['cart_id']);
+        $site_name = sys_config('site_name');
+        if (!$site_name || !$bodyContent) exception('支付参数缺少:请前往后台设置->系统设置-> 填写 网站名称');
+        $alipay = SystemConfigService::more(['alipay_app_id', 'alipay_pub_key', 'alipay_private_key', 'alipay_key']);
+        $notifyUrl = sys_config('site_url') . '/api/alipay/notify';
+        $aliPay = new AlipayService();
+        $aliPay->setAppid($alipay['alipay_app_id']);
+        $aliPay->setNotifyUrl($notifyUrl);
+        $aliPay->setRsaPrivateKey($alipay['alipay_private_key']);
+        $aliPay->setTotalFee($orderInfo['pay_price']);
+        $aliPay->setOutTradeNo($orderInfo['order_id']);
+        $aliPay->setOrderName(StoreOrder::getSubstrUTf8($site_name . ' - ' . $bodyContent, 30));
+        $aliPay->setPassbackParams(['attach' => 'product']);
+        $orderStr = $aliPay->getOrderStr();
+        return $orderStr;
+    }
+
+    /**
+     * 用户确认收货
+     * @param $order
+     * @param $uid
+     * @throws \think\Exception
+     * @throws \think\db\exception\DataNotFoundException
+     * @throws \think\db\exception\ModelNotFoundException
+     * @throws \think\exception\DbException
+     * @throws \think\db\exception\DbException
+     * @throws \Exception
+     */
+    public static function storeProductOrderUserTakeDelivery($order, $uid)
+    {
+        $res1 = StoreOrder::gainUserIntegral($order);
+//        $res2 = User::backOrderBrokerage($order);
+        $res2 = User::sendBackOrderBrokerage($order);
+        StoreOrder::orderTakeAfter($order);
+        //满赠优惠券
+        WechatUser::userTakeOrderGiveCoupon($uid, $order['total_price']);
+        if (!($res1 && $res2)) exception('收货失败!');
+    }
+
+    /**
+     * 修改状态 为已收货  admin模块
+     * @param $order
+     * @throws \Exception
+     */
+    public static function storeProductOrderTakeDeliveryAdmin($order)
+    {
+
+        $res1 = AdminStoreOrder::gainUserIntegral($order);
+//        $res2 = User::backOrderBrokerage($order);
+        $res2 = User::sendBackOrderBrokerage($order);
+        AdminStoreOrder::orderTakeAfter($order);
+        if (!($res1 && $res2)) exception('收货失败!');
+    }
+
+    /**
+     * 修改状态 为已收货  定时任务使用
+     * @param $order
+     * @throws \Exception
+     */
+    public static function storeProductOrderTakeDeliveryTimer($order)
+    {
+
+        $res1 = AdminStoreOrder::gainUserIntegral($order, false);
+        $res2 = User::sendBackOrderBrokerage($order);
+        AdminStoreOrder::orderTakeAfter($order);
+        if (!($res1 && $res2)) exception('收货失败!');
+    }
+
+
+    /**
+     * 修改状态为  已退款  admin模块
+     * @param $data
+     * @param $oid
+     * @return bool|mixed
+     * @throws \think\db\exception\DataNotFoundException
+     * @throws \think\db\exception\ModelNotFoundException
+     * @throws \think\exception\DbException
+     */
+    public static function storeProductOrderRefundY($data, $oid)
+    {
+        $order = AdminStoreOrder::where('id', $oid)->find();
+        if ($order['is_channel'] == 1)
+            return AdminStoreOrder::refundRoutineTemplate($oid); //TODO 小程序余额退款模板消息
+        else
+            return AdminStoreOrder::refundTemplate($data, $oid);//TODO 公众号余额退款模板消息
+    }
+
+
+    /**
+     * TODO  后台余额退款
+     * @param $product
+     * @param $refund_data
+     * @throws \Exception
+     */
+    public static function storeOrderYueRefund($product, $refund_data)
+    {
+        $res = AdminStoreOrder::integralBack($product['id']);
+        if (!$res) exception('退积分失败!');
+    }
+
+    /**
+     * 订单退积分
+     * @param $product $product 商品信息
+     * @param $back_integral $back_integral 退多少积分
+     */
+    public static function storeOrderIntegralBack($product, $back_integral)
+    {
+
+    }
+
+>>>>>>> 386b37d33e5ba817cba00df29efaefbd692e4dd1
 }

+ 92 - 0
crmeb/repositories/PaymentRepositories.php

@@ -1,3 +1,4 @@
+<<<<<<< HEAD
 <?php
 
 namespace crmeb\repositories;
@@ -87,4 +88,95 @@ class PaymentRepositories
             return false;
         }
     }
+=======
+<?php
+
+namespace crmeb\repositories;
+
+use app\models\store\StoreOrder;
+use app\models\user\UserRecharge;
+
+/**
+ * Class PaymentRepositories
+ * @package crmeb\repositories
+ */
+class PaymentRepositories
+{
+
+    /**
+     * 公众号下单成功之后
+     * @param $order
+     * @param $prepay_id
+     */
+    public static function wechatPaymentPrepare($order, $prepay_id)
+    {
+
+    }
+
+    /**
+     * 小程序下单成功之后
+     * @param $order
+     * @param $prepay_id
+     */
+    public static function wechatPaymentPrepareProgram($order, $prepay_id)
+    {
+
+    }
+
+    /**
+     * 使用余额支付订单时
+     * @param $userInfo
+     * @param $orderInfo
+     */
+    public static function yuePayProduct($userInfo, $orderInfo)
+    {
+
+
+    }
+
+    /**
+     * 订单支付成功之后
+     * @param string|null $order_id 订单id
+     * @return bool
+     */
+    public static function wechatProduct(string $order_id = null)
+    {
+        try {
+            if (StoreOrder::be(['order_id' => $order_id, 'paid' => 1])) return true;
+            return StoreOrder::paySuccess($order_id);
+        } catch (\Exception $e) {
+            return false;
+        }
+    }
+    /**
+     * 订单支付成功之后
+     * @param string|null $order_id 订单id
+     * @return bool
+     */
+    public static function aliProduct(string $order_id = null)
+    {
+        try {
+            if (StoreOrder::be(['order_id' => $order_id, 'paid' => 1])) return true;
+            return StoreOrder::paySuccess($order_id, 'ali');
+        } catch (\Exception $e) {
+            return false;
+        }
+    }
+
+
+    /**
+     * 充值成功后
+     * @param string|null $order_id 订单id
+     * @return bool
+     */
+    public static function wechatUserRecharge(string $order_id = null)
+    {
+        try {
+            if (UserRecharge::be(['order_id' => $order_id, 'paid' => 1])) return true;
+            return UserRecharge::rechargeSuccess($order_id);
+        } catch (\Exception $e) {
+            return false;
+        }
+    }
+>>>>>>> 386b37d33e5ba817cba00df29efaefbd692e4dd1
 }

+ 260 - 0
route/api/route.php

@@ -1,3 +1,4 @@
+<<<<<<< HEAD
 <?php
 
 use think\facade\Route;
@@ -255,4 +256,263 @@ Route::miss(function () {
         ]);
     else
         return \think\Response::create()->code(404);
+=======
+<?php
+
+use think\facade\Route;
+
+//账号密码登录
+Route::post('login', 'AuthController/login')->name('login')
+    ->middleware(\app\http\middleware\AllowOriginMiddleware::class);
+
+// 获取发短信的key
+Route::get('verify_code', 'AuthController/verifyCode')->name('verifyCode')
+    ->middleware(\app\http\middleware\AllowOriginMiddleware::class);
+
+//手机号登录
+Route::post('login/mobile', 'AuthController/mobile')->name('loginMobile')
+    ->middleware(\app\http\middleware\AllowOriginMiddleware::class);
+
+//图片验证码
+Route::get('sms_captcha', 'AuthController/captcha')->name('captcha')
+    ->middleware(\app\http\middleware\AllowOriginMiddleware::class);
+//验证码发送
+Route::post('register/verify', 'AuthController/verify')->name('registerVerify')
+    ->middleware(\app\http\middleware\AllowOriginMiddleware::class);
+//手机号注册
+Route::post('register', 'AuthController/register')->name('register')
+    ->middleware(\app\http\middleware\AllowOriginMiddleware::class);
+
+//手机号修改密码
+Route::post('register/reset', 'AuthController/reset')->name('registerReset')
+    ->middleware(\app\http\middleware\AllowOriginMiddleware::class);
+
+Route::any('wechat/serve', 'wechat.WechatController/serve');//公众号服务
+Route::any('wechat/notify', 'wechat.WechatController/notify');//公众号支付回调
+Route::any('routine/notify', 'wechat.AuthController/notify');//小程序支付回调
+Route::any('test', 'PublicController/test');//小程序支付回调
+Route::any('alipay/notify', 'AlipayController/notify');//支付支付回调
+
+Route::get('h5Key', 'AuthController/h5Key');//授权登录Key
+Route::get('h5Token/:key', 'AuthController/h5Token');//授权登录Token
+
+//管理员订单操作类
+Route::group(function () {
+    Route::get('admin/order/statistics', 'admin.StoreOrderController/statistics')->name('adminOrderStatistics');//订单数据统计
+    Route::get('admin/order/data', 'admin.StoreOrderController/data')->name('adminOrderData');//订单每月统计数据
+    Route::get('admin/order/list', 'admin.StoreOrderController/lst')->name('adminOrderList');//订单列表
+    Route::get('admin/order/detail/:orderId', 'admin.StoreOrderController/detail')->name('adminOrderDetail');//订单详情
+    Route::get('admin/order/delivery/gain/:orderId', 'admin.StoreOrderController/delivery_gain')->name('adminOrderDeliveryGain');//订单发货获取订单信息
+    Route::post('admin/order/delivery/keep', 'admin.StoreOrderController/delivery_keep')->name('adminOrderDeliveryKeep');//订单发货
+    Route::post('admin/order/price', 'admin.StoreOrderController/price')->name('adminOrderPrice');//订单改价
+    Route::post('admin/order/remark', 'admin.StoreOrderController/remark')->name('adminOrderRemark');//订单备注
+    Route::get('admin/order/time', 'admin.StoreOrderController/time')->name('adminOrderTime');//订单交易额时间统计
+    Route::post('admin/order/offline', 'admin.StoreOrderController/offline')->name('adminOrderOffline');//订单支付
+    Route::post('admin/order/refund', 'admin.StoreOrderController/refund')->name('adminOrderRefund');//订单退款
+    Route::post('order/order_verific', 'admin.StoreOrderController/order_verific')->name('order');//订单核销
+})->middleware(\app\http\middleware\AllowOriginMiddleware::class)->middleware(\app\http\middleware\AuthTokenMiddleware::class, true)->middleware(\app\http\middleware\CustomerMiddleware::class);
+
+//会员授权接口
+Route::group(function () {
+    Route::post('h5Auth/:key', 'AuthController/h5Auth');//小程序支付回调
+    Route::get('logout', 'AuthController/logout')->name('logout');// 退出登录
+    Route::post('switch_h5', 'AuthController/switch_h5')->name('switch_h5');// 切换账号
+    Route::post('binding', 'AuthController/binding_phone')->name('bindingPhone');// 绑定手机号
+    //产品类
+    Route::get('product/code/:id', 'store.StoreProductController/code')->name('productCode');//产品分享二维码 推广员
+    Route::post('product/poster', 'store.StoreProductController/poster')->name('productPost');//产品分享海报
+    //公共类
+    Route::post('upload/image', 'PublicController/upload_image')->name('uploadImage');//图片上传
+    //用户类 客服聊天记录
+    Route::get('user/service/list', 'user.StoreService/lst')->name('userServiceList');//客服列表
+    Route::get('user/service/record/:toUid', 'user.StoreService/record')->name('userServiceRecord');//客服聊天记录
+
+    //用户类  用户coupons/order
+    Route::get('user', 'user.UserController/user')->name('user');//个人中心
+    Route::post('user/spread', 'user.UserController/spread')->name('userSpread');//静默绑定授权
+    Route::post('user/edit', 'user.UserController/edit')->name('userEdit');//用户修改信息
+    Route::get('user/balance', 'user.UserController/balance')->name('userBalance');//用户资金统计
+    Route::get('userinfo', 'user.UserController/userinfo')->name('userinfo');// 用户信息
+    //用户类  地址
+    Route::get('address/detail/:id', 'user.UserController/address')->name('address');//获取单个地址
+    Route::get('address/list', 'user.UserController/address_list')->name('addressList');//地址列表
+    Route::post('address/default/set', 'user.UserController/address_default_set')->name('addressDefaultSet');//设置默认地址
+    Route::get('address/default', 'user.UserController/address_default')->name('addressDefault');//获取默认地址
+    Route::post('address/edit', 'user.UserController/address_edit')->name('addressEdit');//修改 添加 地址
+    Route::post('address/del', 'user.UserController/address_del')->name('addressDel');//删除地址
+    //用户类 收藏
+    Route::get('collect/user', 'user.UserController/collect_user')->name('collectUser');//收藏产品列表
+    Route::post('collect/add', 'user.UserController/collect_add')->name('collectAdd');//添加收藏
+    Route::post('collect/del', 'user.UserController/collect_del')->name('collectDel');//取消收藏
+    Route::post('collect/all', 'user.UserController/collect_all')->name('collectAll');//批量添加收藏
+
+    Route::get('brokerage_rank', 'user.UserController/brokerage_rank')->name('brokerageRank');//佣金排行
+    Route::get('rank', 'user.UserController/rank')->name('rank');//推广人排行
+    //用戶类 分享
+    Route::post('user/share', 'PublicController/user_share')->name('user_share');//记录用户分享
+    //用户类 点赞
+//    Route::post('like/add', 'user.UserController/like_add')->name('likeAdd');//添加点赞
+//    Route::post('like/del', 'user.UserController/like_del')->name('likeDel');//取消点赞
+    //用户类 签到
+    Route::get('sign/config', 'user.UserController/sign_config')->name('signConfig');//签到配置
+    Route::get('sign/list', 'user.UserController/sign_list')->name('signList');//签到列表
+    Route::get('sign/month', 'user.UserController/sign_month')->name('signIntegral');//签到列表(年月)
+    Route::post('sign/user', 'user.UserController/sign_user')->name('signUser');//签到用户信息
+    Route::post('sign/integral', 'user.UserController/sign_integral')->name('signIntegral');//签到
+    //优惠券类
+    Route::post('coupon/receive', 'store.StoreCouponsController/receive')->name('couponReceive'); //领取优惠券
+    Route::post('coupon/receive/batch', 'store.StoreCouponsController/receive_batch')->name('couponReceiveBatch'); //批量领取优惠券
+    Route::get('coupons/user/:types', 'store.StoreCouponsController/user')->name('couponsUser');//用户已领取优惠券
+    Route::get('coupons/order/:price/:cartId', 'store.StoreCouponsController/order')->name('couponsOrder');//优惠券 订单列表
+    //购物车类
+    Route::get('cart/list', 'store.StoreCartController/lst')->name('cartList'); //购物车列表
+    Route::post('cart/add', 'store.StoreCartController/add')->name('cartAdd'); //购物车添加
+    Route::post('cart/del', 'store.StoreCartController/del')->name('cartDel'); //购物车删除
+    Route::post('order/cancel', 'order.StoreOrderController/cancel')->name('orderCancel'); //订单取消
+    Route::post('cart/num', 'store.StoreCartController/num')->name('cartNum'); //购物车 修改产品数量
+    Route::get('cart/count', 'store.StoreCartController/count')->name('cartCount'); //购物车 获取数量
+    //订单类
+    Route::post('order/confirm', 'order.StoreOrderController/confirm')->name('orderConfirm'); //订单确认
+    Route::post('order/computed/:key', 'order.StoreOrderController/computedOrder')->name('computedOrder'); //计算订单金额
+    Route::post('order/create/:key', 'order.StoreOrderController/create')->name('orderCreate'); //订单创建
+    Route::get('order/data', 'order.StoreOrderController/data')->name('orderData'); //订单统计数据
+    Route::get('order/list', 'order.StoreOrderController/lst')->name('orderList'); //订单列表
+    Route::get('order/detail/:uni', 'order.StoreOrderController/detail')->name('orderDetail'); //订单详情
+    Route::get('order/refund/reason', 'order.StoreOrderController/refund_reason')->name('orderRefundReason'); //订单退款理由
+    Route::post('order/refund/verify', 'order.StoreOrderController/refund_verify')->name('orderRefundVerify'); //订单退款审核
+    Route::post('order/take', 'order.StoreOrderController/take')->name('orderTake'); //订单收货
+    Route::get('order/express/:uni', 'order.StoreOrderController/express')->name('orderExpress'); //订单查看物流
+    Route::post('order/del', 'order.StoreOrderController/del')->name('orderDel'); //订单删除
+    Route::post('order/again', 'order.StoreOrderController/again')->name('orderAgain'); //订单 再次下单
+    Route::post('order/pay', 'order.StoreOrderController/pay')->name('orderPay'); //订单支付
+    Route::post('order/product', 'order.StoreOrderController/product')->name('orderProduct'); //订单产品信息
+    Route::post('order/comment', 'order.StoreOrderController/comment')->name('orderComment'); //订单评价
+    //活动---砍价
+    Route::get('bargain/detail/:id', 'activity.StoreBargainController/detail')->name('bargainDetail');//砍价产品详情
+    Route::post('bargain/start', 'activity.StoreBargainController/start')->name('bargainStart');//砍价开启
+    Route::post('bargain/start/user', 'activity.StoreBargainController/start_user')->name('bargainStartUser');//砍价 开启砍价用户信息
+    Route::post('bargain/share', 'activity.StoreBargainController/share')->name('bargainShare');//砍价 观看/分享/参与次数
+    Route::post('bargain/help', 'activity.StoreBargainController/help')->name('bargainHelp');//砍价 帮助好友砍价
+    Route::post('bargain/help/price', 'activity.StoreBargainController/help_price')->name('bargainHelpPrice');//砍价 砍掉金额
+    Route::post('bargain/help/count', 'activity.StoreBargainController/help_count')->name('bargainHelpCount');//砍价 砍价帮总人数、剩余金额、进度条、已经砍掉的价格
+    Route::post('bargain/help/list', 'activity.StoreBargainController/help_list')->name('bargainHelpList');//砍价 砍价帮
+    Route::post('bargain/poster', 'activity.StoreBargainController/poster')->name('bargainPoster');//砍价海报
+    Route::get('bargain/user/list', 'activity.StoreBargainController/user_list')->name('bargainUserList');//砍价列表(已参与)
+    Route::post('bargain/user/cancel', 'activity.StoreBargainController/user_cancel')->name('bargainUserCancel');//砍价取消
+    //活动---拼团
+    Route::get('combination/pink/:id', 'activity.StoreCombinationController/pink')->name('combinationPink');//拼团开团
+    Route::post('combination/remove', 'activity.StoreCombinationController/remove')->name('combinationRemove');//拼团 取消开团
+    Route::post('combination/poster', 'activity.StoreCombinationController/poster')->name('combinationPoster');//拼团海报
+    //账单类
+    Route::get('commission', 'user.UserBillController/commission')->name('commission');//推广数据 昨天的佣金 累计提现金额 当前佣金
+    Route::post('spread/people', 'user.UserBillController/spread_people')->name('spreadPeople');//推荐用户
+    Route::post('spread/order', 'user.UserBillController/spread_order')->name('spreadOrder');//推广订单
+    Route::get('spread/commission/:type', 'user.UserBillController/spread_commission')->name('spreadCommission');//推广佣金明细
+    Route::get('spread/count/:type', 'user.UserBillController/spread_count')->name('spreadCount');//推广 佣金 3/提现 4 总和
+    Route::get('spread/banner', 'user.UserBillController/spread_banner')->name('spreadBanner');//推广分销二维码海报生成
+    Route::get('integral/list', 'user.UserBillController/integral_list')->name('integralList');//积分记录
+    //提现类
+    Route::get('extract/bank', 'user.UserExtractController/bank')->name('extractBank');//提现银行/提现最低金额
+    Route::post('extract/cash', 'user.UserExtractController/cash')->name('extractCash');//提现申请
+    //充值类
+    Route::post('recharge/routine', 'user.UserRechargeController/routine')->name('rechargeRoutine');//小程序充值
+    Route::post('recharge/wechat', 'user.UserRechargeController/wechat')->name('rechargeWechat');//公众号充值
+    Route::get('recharge/index', 'user.UserRechargeController/index')->name('rechargeQuota');//充值余额选择
+    //会员等级类
+    Route::get('menu/user', 'PublicController/menu_user')->name('menuUser');//个人中心菜单
+    Route::get('user/level/detection', 'user.UserLevelController/detection')->name('userLevelDetection');//检测用户是否可以成为会员
+    Route::get('user/level/grade', 'user.UserLevelController/grade')->name('userLevelGrade');//会员等级列表
+    Route::get('user/level/task/:id', 'user.UserLevelController/task')->name('userLevelTask');//获取等级任务
+    //首页获取未支付订单
+    Route::get('order/nopay', 'order.StoreOrderController/get_noPay')->name('getNoPay');//获取未支付订单
+
+    //出局奖励
+    Route::get('partake/out', 'user.UserPartakeController/out_list')->name('outList');//出局奖励列表
+    Route::get('partake/out/:id', 'user.UserPartakeController/out_detail')->name('outList');//出局奖励列表
+    Route::post('partake/participate_in', 'user.UserPartakeController/participate_in')->name('participate_in');//参与
+    Route::get('partake/partake', 'user.UserPartakeController/partake')->name('partake');//参与记录
+    Route::get('partake/user_push_list', 'user.UserPartakeController/user_push_list')->name('user_push_list');//下级消费记录
+})->middleware(\app\http\middleware\AllowOriginMiddleware::class)->middleware(\app\http\middleware\AuthTokenMiddleware::class, true);
+//未授权接口
+Route::group(function () {
+    //公共类
+    Route::get('index', 'PublicController/index')->name('index');//首页
+    Route::get('city_area', 'PublicController/cityArea')->name('city_area');
+    Route::get('search/keyword', 'PublicController/search')->name('searchKeyword');//热门搜索关键字获取
+    //产品分类类
+    Route::get('category', 'store.CategoryController/category')->name('category');
+    //产品类
+    Route::post('image_base64', 'PublicController/get_image_base64')->name('getImageBase64');// 获取图片base64
+    Route::get('product/detail/:id/[:type]', 'store.StoreProductController/detail')->name('detail');//产品详情
+    Route::get('groom/list/:type', 'store.StoreProductController/groom_list')->name('groomList');//获取首页推荐不同类型产品的轮播图和产品
+    Route::get('products', 'store.StoreProductController/lst')->name('products');//产品列表
+    Route::get('product/hot', 'store.StoreProductController/product_hot')->name('productHot');//为你推荐
+    Route::get('reply/list/:id', 'store.StoreProductController/reply_list')->name('replyList');//产品评价列表
+    Route::get('reply/config/:id', 'store.StoreProductController/reply_config')->name('replyConfig');//产品评价数量和好评度
+    //文章分类类
+    Route::get('article/category/list', 'publics.ArticleCategoryController/lst')->name('articleCategoryList');//文章分类列表
+    //文章类
+    Route::get('article/list/:cid', 'publics.ArticleController/lst')->name('articleList');//文章列表
+    Route::get('article/details/:id', 'publics.ArticleController/details')->name('articleDetails');//文章详情
+    Route::get('article/hot/list', 'publics.ArticleController/hot')->name('articleHotList');//文章 热门
+    Route::get('article/banner/list', 'publics.ArticleController/banner')->name('articleBannerList');//文章 banner
+    //活动---秒杀
+    Route::get('seckill/index', 'activity.StoreSeckillController/index')->name('seckillIndex');//秒杀产品时间区间
+    Route::get('seckill/list/:time', 'activity.StoreSeckillController/lst')->name('seckillList');//秒杀产品列表
+    Route::get('seckill/detail/:id/[:time]', 'activity.StoreSeckillController/detail')->name('seckillDetail');//秒杀产品详情
+    //活动---砍价
+    Route::get('bargain/config', 'activity.StoreBargainController/config')->name('bargainConfig');//砍价产品列表配置
+    Route::get('bargain/list', 'activity.StoreBargainController/lst')->name('bargainList');//砍价产品列表
+    //活动---拼团
+    Route::get('combination/list', 'activity.StoreCombinationController/lst')->name('combinationList');//拼团产品列表
+    Route::get('combination/detail/:id', 'activity.StoreCombinationController/detail')->name('combinationDetail');//拼团产品详情
+    //用户类
+    Route::get('user/activity', 'user.UserController/activity')->name('userActivity');//活动状态
+
+    //微信
+    Route::get('wechat/config', 'wechat.WechatController/config')->name('wechatConfig');//微信 sdk 配置
+    Route::get('wechat/auth', 'wechat.WechatController/auth')->name('wechatAuth');//微信授权
+
+    //小程序登陆
+    Route::post('wechat/mp_auth', 'wechat.AuthController/mp_auth')->name('mpAuth');//小程序登陆
+    Route::get('wechat/get_logo', 'wechat.AuthController/get_logo')->name('getLogo');//小程序登陆授权展示logo
+    Route::post('wechat/set_form_id', 'wechat.AuthController/set_form_id')->name('setFormId');//小程序登陆收集form id
+    Route::get('wechat/teml_ids', 'wechat.AuthController/teml_ids')->name('wechatTemlIds');//小程序订阅消息
+    Route::get('wechat/live', 'wechat.AuthController/live')->name('wechatLive');//小程序直播列表
+
+    //物流公司
+    Route::get('logistics', 'PublicController/logistics')->name('logistics');//物流公司列表
+
+    //分享配置
+    Route::get('share', 'PublicController/share')->name('share');//分享配置
+
+    //优惠券
+    Route::get('coupons', 'store.StoreCouponsController/lst')->name('couponsList'); //可领取优惠券列表
+
+    //短信购买异步通知
+    Route::post('sms/pay/notify', 'PublicController/sms_pay_notify')->name('smsPayNotify'); //短信购买异步通知
+
+    //获取关注微信公众号海报
+    Route::get('wechat/follow', 'wechat.WechatController/follow')->name('Follow');
+
+    //门店列表
+    Route::get('store_list', 'PublicController/store_list')->name('storeList');
+    //获取城市列表
+    Route::get('city_list', 'PublicController/city_list')->name('cityList');
+
+    Route::get('version', 'PublicController/version')->name('version'); // 版本更新
+
+})->middleware(\app\http\middleware\AllowOriginMiddleware::class)->middleware(\app\http\middleware\AuthTokenMiddleware::class, false);
+
+
+Route::miss(function () {
+    if (app()->request->isOptions())
+        return \think\Response::create('ok')->code(200)->header([
+            'Access-Control-Allow-Origin' => '*',
+            'Access-Control-Allow-Headers' => 'Authori-zation,Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With',
+            'Access-Control-Allow-Methods' => 'GET,POST,PATCH,PUT,DELETE,OPTIONS,DELETE',
+        ]);
+    else
+        return \think\Response::create()->code(404);
+>>>>>>> 386b37d33e5ba817cba00df29efaefbd692e4dd1
 });