审查视图

application/api/controller/Common.php 27.6 KB
王智 authored
1 2 3 4 5 6 7
<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Area;
use app\common\model\Version;
王智 authored
8
use Qiniu\Auth;
王智 authored
9 10
use think\Config;
use think\Hook;
王智 authored
11
王智 authored
12 13
//use EasyWeChat\Factory;
use EasyWeChat\Foundation\Application;
王智 authored
14
use think\Db;
王智 authored
15
use app\common\model\Attachment;
王智 authored
16
use think\process\exception\Timeout;
王智 authored
17 18 19 20 21 22

/**
 * 公共接口
 */
class Common extends Api
{
王智 authored
23
    protected $noNeedLogin = ['*'];
王智 authored
24 25 26 27 28 29
    protected $noNeedRight = '*';

    /**
     * 加载初始化
     *
     * @param string $version 版本号
王智 authored
30 31
     * @param string $lng 经度
     * @param string $lat 纬度
王智 authored
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
     */
    public function init()
    {
        if ($version = $this->request->request('version')) {
            $lng = $this->request->request('lng');
            $lat = $this->request->request('lat');

            //配置信息
            $upload = Config::get('upload');
            //如果非服务端中转模式需要修改为中转
            if ($upload['storage'] != 'local' && isset($upload['uploadmode']) && $upload['uploadmode'] != 'server') {
                //临时修改上传模式为服务端中转
                set_addon_config($upload['storage'], ["uploadmode" => "server"], false);

                $upload = \app\common\model\Config::upload();
                // 上传信息配置后
                Hook::listen("upload_config_init", $upload);

                $upload = Config::set('upload', array_merge(Config::get('upload'), $upload));
            }

            $upload['cdnurl'] = $upload['cdnurl'] ? $upload['cdnurl'] : cdnurl('', true);
            $upload['uploadurl'] = preg_match("/^((?:[a-z]+:)?\/\/)(.*)/i", $upload['uploadurl']) ? $upload['uploadurl'] : url($upload['storage'] == 'local' ? '/api/common/upload' : $upload['uploadurl'], '', false, true);

            $content = [
王智 authored
57
                'citydata' => Area::getCityFromLngLat($lng, $lat),
王智 authored
58
                'versiondata' => Version::check($version),
王智 authored
59 60
                'uploaddata' => $upload,
                'coverdata' => Config::get("cover"),
王智 authored
61 62 63 64 65 66 67 68
            ];
            $this->success('', $content);
        } else {
            $this->error(__('Invalid parameters'));
        }
    }

    /**
王智 authored
69 70 71 72 73 74
     * 上传文件-七牛
     *
     * @ApiTitle    (上传文件-七牛)
     * @ApiSummary  (测试描述信息)
     * @ApiMethod   (POST)
     * @ApiParams   (name="file", type="file", required=true, description="用户名")
王智 authored
75
     */
王智 authored
76
    public function uploadQiniu()
王智 authored
77
    {
王智 authored
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
        $config = get_addon_config('qiniu');
        $file = $this->request->file('file');
        if (!$file || !$file->isValid()) {
            $this->error("请上传有效的文件");
        }
        $fileInfo = $file->getInfo();
        $filePath = $file->getRealPath() ?: $file->getPathname();
        preg_match('/(\d+)(\w+)/', $config['maxsize'], $matches);
        $type = strtolower($matches[2]);
        $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
        $size = (int)$config['maxsize'] * pow(1024000, isset($typeDict[$type]) ? $typeDict[$type] : 0);

        $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
        $suffix = $suffix ? $suffix : 'file';

        $md5 = md5_file($filePath);
        $search = ['$(year)', '$(mon)', '$(day)', '$(etag)', '$(ext)'];
        $replace = [date("Y"), date("m"), date("d"), $md5, '.' . $suffix];
        $object = ltrim(str_replace($search, $replace, $config['savekey']), '/');

        $mimetypeArr = explode(',', strtolower($config['mimetype']));
        $typeArr = explode('/', $fileInfo['type']);

        //检查文件大小
        if (!$file->checkSize($size)) {
            $this->error("起过最大可上传文件限制");
        }

        //验证文件后缀
        if ($config['mimetype'] !== '*' &&
            (
                !in_array($suffix, $mimetypeArr)
                || (stripos($typeArr[0] . '/', $config['mimetype']) !== false && (!in_array($fileInfo['type'], $mimetypeArr) && !in_array($typeArr[0] . '/*', $mimetypeArr)))
            )
        ) {
            $this->error(__('上传格式限制'));
        }

        $savekey = '/' . $object;

        $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
        $fileName = substr($savekey, strripos($savekey, '/') + 1);
        //先上传到本地
        $splInfo = $file->move(ROOT_PATH . '/public' . $uploadDir, $fileName);
        if ($splInfo) {
            $extparam = $this->request->post();
            $filePath = $splInfo->getRealPath() ?: $splInfo->getPathname();

            $sha1 = sha1_file($filePath);
            $imagewidth = $imageheight = 0;
            if (in_array($suffix, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf', 'pdf'])) {
                $imgInfo = getimagesize($splInfo->getPathname());
                $imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
                $imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;
王智 authored
132
            }
王智 authored
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
            $params = array(
                'admin_id' => session('admin.id'),
                'user_id' => $this->auth->id,
                'filesize' => $fileInfo['size'],
                'imagewidth' => $imagewidth,
                'imageheight' => $imageheight,
                'imagetype' => $suffix,
                'imageframes' => 0,
                'mimetype' => $fileInfo['type'],
                'url' => $uploadDir . $splInfo->getSaveName(),
                'uploadtime' => time(),
                'storage' => 'local',
                'sha1' => $sha1,
                'extparam' => json_encode($extparam),
            );
            $attachment = Attachment::create(array_filter($params), true);
            $policy = array(
                'saveKey' => ltrim($savekey, '/'),
            );
            $auth = new Auth($config['accessKey'], $config['secretKey']);
            $token = $auth->uploadToken($config['bucket'], null, $config['expire'], $policy);
            $multipart = [
                ['name' => 'token', 'contents' => $token],
                [
                    'name' => 'file',
                    'contents' => fopen($filePath, 'r'),
                    'filename' => $fileName,
                ]
            ];
王智 authored
162
            try {
王智 authored
163 164 165 166 167 168 169 170 171 172
                $client = new \GuzzleHttp\Client();
                $res = $client->request('POST', $config['uploadurl'], [
                    'multipart' => $multipart
                ]);
                $code = $res->getStatusCode();
                //成功不做任何操作
            } catch (\GuzzleHttp\Exception\ClientException $e) {
                $attachment->delete();
                unlink($filePath);
                $this->error("上传失败");
王智 authored
173 174
            }
王智 authored
175
            $url = '/' . $object;
王智 authored
176
王智 authored
177 178 179 180 181 182 183 184
            //上传成功后将存储变更为qiniu
            $attachment->storage = 'qiniu';
            $attachment->save();
            $this->success("上传成功", $url);
        } else {
            $this->error('上传失败');
        }
        return;
王智 authored
185
    }
王智 authored
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274


    /**
     * 公共接口
     * @ApiTitle    (用户协议)
     * @ApiSummary  (用户协议)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Common/UserContent)
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功',
    "data": "<p>审核协议</p>"
    )
     */
    public function UserContent()
    {
        $ContentArr = Db::name('user_content')->where('id', 1)->find();
        $this->success('成功', $ContentArr['content']);
    }


    /**
     * 公共接口
     * @ApiTitle    (审核协议)
     * @ApiSummary  (审核协议)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Common/StatusContent)
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功',
    "data": "<p>审核协议</p>"
    )
     */
    public function StatusContent()
    {
        $ContentArr = Db::name('status_content')->where('id', 1)->find();
        $this->success('成功', $ContentArr['content']);
    }


    /**
     * 公共接口
     * @ApiTitle    (入驻协议)
     * @ApiSummary  (入驻协议)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Common/InContent)
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功',
    "data": "<p>入驻协议</p>"
    )
     */
    public function InContent()
    {
        $ContentArr = Db::name('in_content')->where('id', 1)->find();
        $this->success('成功', $ContentArr['content']);
    }


    /**
     * 公共接口
     * @ApiTitle    (服务商申请状态)
     * @ApiSummary  (服务商申请状态)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Common/SellerStatusOther)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功',
    "data": 审核状态:0=待审核,1=审核通过,2=审核未通过,9=未申请过
    )
     */
    public function SellerStatusOther()
    {
        $UserId = $this->IsToken($this->request->header());
        $Arr = Db::name('seller')->where('user_id', $UserId)->find();
        if (empty($Arr)) {
            $Arr['Status'] = 9;
        }
        $this->success('成功', $Arr['Status']);
    }
王智 authored
275 276 277 278 279 280 281 282 283 284 285 286 287


    /**
     * 公共接口
     * @ApiTitle    (协议配置)
     * @ApiSummary  (协议配置)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Common/AgreementConfig)
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功',
王智 authored
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
    "data": {
    "Stor": [
    {
    "id": 2,  //服务商ID
    "CompanyMain": "混凝土瞬间移动树" //服务商名
    }
    ],
    "Battery": [
    {
    "id": 1,  //电池类型id
    "title": "电池类型一"  //电池类型
    },
    {
    "id": 2,
    "title": "电池类型二"
    },
    {
    "id": 3,
    "title": "电池类型三"
    },
    {
    "id": 4,
    "title": "电池类型四"
    }
    ]
    }
王智 authored
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
    )
     */
    public function AgreementConfig()
    {
        $SellerArr = Db::name('seller')->select();
        if (empty($SellerArr)) {
            $Seller = [];
        } else {
            foreach ($SellerArr as $k => $v) {
                $Seller[$k]['id'] = $v['id'];
                $Seller[$k]['CompanyMain'] = $v['CompanyMain'];
            }
        }
        $BatteryArr = Db::name('battery_code')->select();
        if (empty($BatteryArr)) {
            $Battery = [];
        } else {
            foreach ($BatteryArr as $k => $v) {
                $Battery[$k]['id'] = $v['id'];
                $Battery[$k]['title'] = $v['title'];
            }
        }
王智 authored
336 337 338 339 340 341 342 343 344
//        $HoursArr = Db::name('hours')->select();
//        if (empty($HoursArr)) {
//            $Hours = [];
//        } else {
//            foreach ($HoursArr as $k => $v) {
//                $Hours[$k]['id'] = $v['id'];
//                $Hours[$k]['number'] = $v['number'];
//            }
//        }
王智 authored
345 346 347 348 349 350
//        $MoneyArr = Db::name('money_config')->find();
        $data = [
//            'UpMoney' => $MoneyArr['UpMoney'],
//            'MonthMoney' => $MoneyArr['MonthMoney'],
            'Stor' => $Seller,
            'Battery' => $Battery,
王智 authored
351
//            'Hours' => $Hours,
王智 authored
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
        ];
        $this->success('成功', $data);
    }


    /**
     * 公共接口
     * @ApiTitle    (协议价格计算)
     * @ApiSummary  (协议价格计算)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Common/AgreementConfigMoney)
     * @ApiParams   (name="battery_id", type="string", required=true, description="电池类型ID")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功',
    )
     */
    public function AgreementConfigMoney()
    {
        $params = $this->request->param();
        $MoneyConfigArr = Db::name('money_config')->where('battery_id', $params['battery_id'])->find();
        $data = [
            'UpMoney' => $MoneyConfigArr['UpMoney'],
            'MonthMoney' => $MoneyConfigArr['MonthMoney'] * 3
        ];
        $this->success('成功', $data);
    }


    /**
     * 公共接口
     * @ApiTitle    (服务商协议操作)
     * @ApiSummary  (服务商协议操作)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Common/AgreementOperation)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
王智 authored
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
     * @ApiParams   (name="type", type="string", required=true, description="操作:1=同意,2=拒绝,3=修改租金,4=终止协议,5=删除协议")
     * @ApiParams   (name="id", type="string", required=true, description="协议ID")
     * @ApiParams   (name="money", type="int", required=true, description="修改后的金额")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功',
    )
     */
    public function AgreementOperation()
    {
        $UserId = $this->IsToken($this->request->header());
        $params = $this->request->param();
        $IsSeller = Db::name('agreement')
            ->alias('a')
            ->join('seller s', 's.id=a.seller_id')
            ->where('s.user_id', $UserId)
            ->where('a.id', $params['id'])
            ->find();
        if (empty($IsSeller)) {
            $this->error('参数错误', 0);
        }
        //同意签订协议
        if ($params['type'] == 1) {
            $res = Db::name('agreement')->where('id', $params['id'])->update(['status' => 1, 'updatetime' => time(), 'EXP_time' => time() + 86400 * 30]);
        }
        //拒绝签订协议
        if ($params['type'] == 2) {
            $res = Db::name('agreement')->where('id', $params['id'])->update(['status' => 4, 'updatetime' => time()]);
            //拒绝签订协议 给予用户退款
王智 authored
421
            $OrderSn = Db::name('agreement')->where('id', $params['id'])->find();
王智 authored
422
            $PayOrderInfo = Db::name('pay_order')->where('OrderSn', $OrderSn['OrderSn'])->where('type', 1)->find();
王智 authored
423 424
            $TuiMoney = $OrderSn['UpMoney'] + $OrderSn['Money'];
            //配置
王智 authored
425 426 427 428 429
            $config = [
                'app_id' => 'wx6a9080f20326f817',
                'payment' => [
                    'merchant_id' => '1603658973',
                    'key' => '8695A8185xyzKcdEVfreewayShenzhen',
王智 authored
430 431
                    'cert_path' => '/home/wwwroot/fast/kcd/addons/epay/certs/apiclient_cert.pem', // XXX: 绝对路径!!!!
                    'key_path' => '/home/wwwroot/fast/kcd/addons/epay/certs/apiclient_key.pem',      // XXX: 绝对路径!!!!
王智 authored
432 433
                ],
            ];
王智 authored
434 435
            $app = new Application($config);
            $payment = $app->payment;
王智 authored
436
            try {
王智 authored
437
                $result = $payment->refundByTransactionId($PayOrderInfo['WeChatOrder'], $PayOrderInfo['PayOrder'], $PayOrderInfo['money'] * 100, $TuiMoney * 100); // 总金额 100, 退款 80,操作员:商户号
王智 authored
438
                //更改订单状态为已退款
王智 authored
439
                Db::name('pay_order')->where('OrderSn', $OrderSn['OrderSn'])->where('PayOrder', $PayOrderInfo['PayOrder'])->update(['type' => 0]);
王智 authored
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
            } catch (Exception $e) {
                $e->getMessage();
            }
            if (!$result) {
                $this->error('退款失败', 0);
                die;
            }
        }
        //修改租金
        if ($params['type'] == 3) {
            $res = Db::name('agreement')->where('id', $params['id'])->update(['MonthMoney' => $params['money'], 'updatetime' => time()]);
        }
        //终止协议
        if ($params['type'] == 4) {
            $res = Db::name('agreement')->where('id', $params['id'])->update(['status' => 2, 'updatetime' => time()]);
        }
        //删除协议
        if ($params['type'] == 5) {
            $res = Db::name('agreement')->where('id', $params['id'])->delete();
        }
        $this->res($res);
    }


    /**
     * 公共接口
     * @ApiTitle    (押金退还操作)
     * @ApiSummary  (押金退还操作)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Common/TuikuanOperation)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="type", type="string", required=true, description="操作:1=通过,2=拒绝,3=删除记录")
     * @ApiParams   (name="id", type="string", required=true, description="协议ID")
     * @ApiParams   (name="bili", type="string", required=true, description="退款百分比/ 1为百分之100/0.1为百分之10")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功',
    )
     */
    public function TuikuanOperation()
    {
        $UserId = $this->IsToken($this->request->header());
        $params = $this->request->param();
        $IsSeller = Db::name('agreement')
            ->alias('a')
            ->join('seller s', 's.id=a.seller_id')
            ->where('s.user_id', $UserId)
            ->where('a.id', $params['id'])
            ->value('seller_id');
        if (empty($IsSeller)) {
            $this->error('参数错误', 0);
        }
        $OrderInfo = Db::name('agreement')->where('id', $params['id'])->find();
        if ($params['type'] == 3) {
            $res = Db::name('tuikuan')->where('OrderSn', $OrderInfo['OrderSn'])->where('seller_id', $IsSeller)->delete();
        } else {
            $IsUpdateAgreement = Db::name('agreement')->where('id', $params['id'])->update(['refind_status' => $params['type']]);
            if (!$IsUpdateAgreement) {
                $this->error('协议状态更改失败', 0);
            }
王智 authored
502
            $res = Db::name('tuikuan')->where('OrderSn', $OrderInfo['OrderSn'])->where('seller_id', $IsSeller)->update(['status' => $params['type']]);
王智 authored
503
            if ($params['type'] == 1) {
王智 authored
504 505 506
                $OrderSn = Db::name('agreement')->where('id', $params['id'])->find();
                $PayOrderInfo = Db::name('pay_order')->where('OrderSn', $OrderSn['OrderSn'])->where('type', 1)->find();
                $TuiMoney = $OrderSn['UpMoney'] + $OrderSn['Money'];
王智 authored
507 508 509 510 511 512
                //配置
                $config = [
                    'app_id' => 'wx6a9080f20326f817',
                    'payment' => [
                        'merchant_id' => '1603658973',
                        'key' => '8695A8185xyzKcdEVfreewayShenzhen',
王智 authored
513 514
                        'cert_path' => '/home/wwwroot/fast/kcd/addons/epay/certs/apiclient_cert.pem', // XXX: 绝对路径!!!!
                        'key_path' => '/home/wwwroot/fast/kcd/addons/epay/certs/apiclient_key.pem',      // XXX: 绝对路径!!!!
王智 authored
515 516
                    ],
                ];
王智 authored
517 518
                $app = new Application($config);
                $payment = $app->payment;
王智 authored
519
                try {
王智 authored
520
                    $result = $payment->refundByTransactionId($PayOrderInfo['WeChatOrder'], $PayOrderInfo['PayOrder'], $PayOrderInfo['money'] * 100, $TuiMoney * 100); // 总金额 100, 退款 80,操作员:商户号
王智 authored
521
                    //更改订单状态为已退款
王智 authored
522
                    Db::name('pay_order')->where('OrderSn', $OrderSn['OrderSn'])->where('PayOrder', $PayOrderInfo['PayOrder'])->update(['type' => 0]);
王智 authored
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
                } catch (Exception $e) {
                    $e->getMessage();
                }
                if (!$result) {
                    $this->error('退款失败', 0);
                    die;
                }
            }
        }
        $this->res($res);
    }


    /**
     * 公共接口
     * @ApiTitle    (删除订单)
     * @ApiSummary  (删除订单)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Common/DeleteOrder)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="OrderSn", type="string", required=true, description="订单号")
王智 authored
544 545 546 547 548 549 550
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功',
    )
     */
王智 authored
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
    public function DeleteOrder()
    {
        $UserId = $this->IsToken($this->request->header());
        $OrderSn = input('OrderSn');
        $Arr = Db::name('order')
            ->alias('o')
            ->join('stor s', 's.id=a.stor_id')
            ->where('s.user_id', $UserId)
            ->where('o.OrderSn', $OrderSn)
            ->find();
        if (empty($Arr)) {
            $this->error('参数错误', 0);
            die;
        }
        $res = Db::name('order')->where('OrderSn', $OrderSn)->delete();
        $this->res($res);
    }


    /**
     * 公共接口
     * @ApiTitle    (账户押金操作)
     * @ApiSummary  (账户押金操作)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Common/UpMoneyOperation)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="OrderSn", type="string", required=true, description="订单号")
     * @ApiParams   (name="type", type="int", required=true, description="操作:1=取消签约,2=删除,3=退还押金")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功',
    )
     */
    public function UpMoneyOperation()
    {
        $UserId = $this->IsToken($this->request->header());
        $params = $this->request->param();
        $OrderInfo = Db::name('agreement')->where('OrderSn', $params['OrderSn'])->where('user_id', $UserId)->find();
        if (empty($OrderInfo)) {
            $this->error('参数错误', 0);
        }
        if ($params['type'] == 1) {
            if ($OrderInfo['status'] != 0) {
                $this->error('不能取消签约', 0);
            }
            $res = Db::name('agreement')->where('id', $OrderInfo['id'])->where('user_id', $UserId)->update(['status' => 4]);
            $this->Tuikuan($params['OrderSn']);
        }
        if ($params['type'] == 2) {
            if ($OrderInfo['status'] == 2 || $OrderInfo['status'] == 4) {
                $res = Db::name('agreement')->where('id', $OrderInfo['id'])->where('user_id', $UserId)->delete();
            } else {
                $this->error('不能删除订单', 0);
                die;
            }
        }
        if ($params['type'] == 3) {
            $res = Db::name('agreement')->where('id', $OrderInfo['id'])->where('user_id', $UserId)->update(['status' => 2, 'refind_status' => 0]);
            $data = [
                'user_id' => $UserId,
                'OrderSn' => $params['OrderSn'],
                'status' => 0,
                'seller_id' => $OrderInfo['seller_id'],
                'createtime' => time(),
                'updatetime' => time()
            ];
            $IsSave = Db::name('tuikuan')->insert($data);
            if (!$IsSave) {
                $this->error('添加退款记录失败', 0);
                die;
            }
        }
        $this->res($res);
    }
王智 authored
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667


    /**
     * 公共接口
     * @ApiTitle    (订单操作)
     * @ApiSummary  (订单操作)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Common/OrderOperation)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="OrderSn", type="string", required=true, description="订单号")
     * @ApiParams   (name="type", type="string", required=true, description="操作:1=确认无误,3=电池故障")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功',
    )
     */
    public function OrderOperation()
    {
        $UserId = $this->IsToken($this->request->header());
        $params = $this->request->param();
        $Arr = Db::name('order')
            ->alias('o')
            ->where('o.OrderSn', $params['OrderSn'])
            ->join('stor s', 's.id=o.stor_id')
            ->where('s.user_id', $UserId)
            ->find();
        if (empty($Arr)) {
            $this->error('身份异常', 0);
            die;
        }
        $res = Db::name('order')->where('OrderSn', $params['OrderSn'])->update(
            [
                'status' => $params['type'],
                'yes_time' => time(),
                'ok_time' => time()
            ]
        );
        $this->res($res);
    }
王智 authored
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694


    //定时任务
    public function MonthMoney()
    {
        $Arr = Db::name('agreement')->select();
        if (!empty($Arr)) {
            foreach ($Arr as $k => $v) {
                if (time() > $v['EXP_time']) {
                    if ($v['Money'] > $v['MonthMoney']) {
                        //扣钱+时间
                        $res = Db::name('agreement')->where('id', $v['id'])->update(['Money' => $v['Money'] - $v['MonthMoney'], 'EXP_time' => $v['EXP_time'] + 86400 * 30]);
                        if (!$res) {
                            $this->error('失败id' . $v['id'], 0);
                            die;
                        }
                    } else {
                        $res = Db::name('agreement')->where('id', $v['id'])->update(['status' => 3]);
                        if (!$res) {
                            $this->error('失败id' . $v['id'], 0);
                            die;
                        }
                    }
                }
            }
        }
    }
王智 authored
695 696 697 698 699 700 701 702 703 704 705 706 707 708


    /**
     * 公共接口
     * @ApiTitle    (设备详情)
     * @ApiSummary  (设备详情)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/Common/BatteryCon)
     * @ApiParams   (name="battery_code", type="string", required=true, description="电池编号")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功',
王智 authored
709 710 711 712 713
    "data": {
    "Avatar": "http://kcd.qiniu.bronet.cn/uploads/20201031/FnCgZycGvvpzdFwpJyrZoSN7iqCX.jpg",
    "Title": "电池类型四",
    "Manufactor": "银河百荣"
    }
王智 authored
714 715 716 717 718 719 720 721 722 723 724
    )
     */
    public function BatteryCon()
    {
        $Code = input('battery_code');
        if (empty($Code) || $Code == '' || $Code == "" || $Code == null) {
            $this->error('请先链接蓝牙', 0);
            die;
        }
        $map['BatteryCode'] = ['LIKE', '%' . $Code . '%'];
        //用户电池分类ID
王智 authored
725
        $Id = Db::name('battery_code')->where($map)->find();
王智 authored
726 727 728 729 730 731 732 733 734 735 736
        if (empty($Id)) {
            $this->error('系统没有找到该电池分类', 0);
            die;
        }
        $data = [
            'Avatar' => cdnurl($Id['avatar']),
            'Title' => $Id['title'],
            'Manufactor' => $Id['manufactor']
        ];
        $this->success('成功', $data);
    }
王智 authored
737 738 739 740 741 742

    //定时任务
    public function delNoPay()
    {
        Db::name('agreement')->where('createtime', '>', time() - 60)->where('pay', 0)->delete();
    }
王智 authored
743
}