<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Area;
use app\common\model\Version;
use Qiniu\Auth;
use think\Config;
use think\Hook;
use EasyWeChat\Factory;
use think\Db;
use app\common\model\Attachment;
use think\process\exception\Timeout;

/**
 * 公共接口
 */
class Common extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';

    /**
     * 加载初始化
     *
     * @param string $version 版本号
     * @param string $lng 经度
     * @param string $lat 纬度
     */
    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 = [
                'citydata' => Area::getCityFromLngLat($lng, $lat),
                'versiondata' => Version::check($version),
                'uploaddata' => $upload,
                'coverdata' => Config::get("cover"),
            ];
            $this->success('', $content);
        } else {
            $this->error(__('Invalid parameters'));
        }
    }

    /**
     * 上传文件-七牛
     *
     * @ApiTitle    (上传文件-七牛)
     * @ApiSummary  (测试描述信息)
     * @ApiMethod   (POST)
     * @ApiParams   (name="file", type="file", required=true, description="用户名")
     */
    public function uploadQiniu()
    {
        $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;
            }
            $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,
                ]
            ];
            try {
                $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("上传失败");
            }

            $url = '/' . $object;

            //上传成功后将存储变更为qiniu
            $attachment->storage = 'qiniu';
            $attachment->save();
            $this->success("上传成功", $url);
        } else {
            $this->error('上传失败');
        }
        return;
    }


    /**
     * 公共接口
     * @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']);
    }


    /**
     * 公共接口
     * @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':'返回成功',
    "data": {
    "Stor": [
    {
    "id": 2,  //服务商ID
    "CompanyMain": "混凝土瞬间移动树" //服务商名
    }
    ],
    "Battery": [
    {
    "id": 1,  //电池类型id
    "title": "电池类型一"  //电池类型
    },
    {
    "id": 2,
    "title": "电池类型二"
    },
    {
    "id": 3,
    "title": "电池类型三"
    },
    {
    "id": 4,
    "title": "电池类型四"
    }
    ]
    }
    )
     */
    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'];
            }
        }
//        $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'];
//            }
//        }
//        $MoneyArr = Db::name('money_config')->find();
        $data = [
//            'UpMoney' => $MoneyArr['UpMoney'],
//            'MonthMoney' => $MoneyArr['MonthMoney'],
            'Stor' => $Seller,
            'Battery' => $Battery,
//            'Hours' => $Hours,
        ];
        $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")
     * @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()]);
            //拒绝签订协议 给予用户退款
            $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'];
            //配置
//            $config = [
////                'payment' => [
//                'app_id' => 'wx6a9080f20326f817',
//                'merchant_id' => '1603658973',
//                'key' => '8695A8185xyzKcdEVfreewayShenzhen',
//                'cert_path' => '/home/wwwroot/fast/book/addons/epay/certs/apiclient_cert.pem', // XXX: 绝对路径!!!!
//                'key_path' => '/home/wwwroot/fast/book/addons/epay/certs/apiclient_key.pem',      // XXX: 绝对路径!!!!
////                ],
//            ];
            $app = Factory::officialAccount($config);
            try {
                $result = $app->refund->byTransactionId($PayOrderInfo['WeChatOrder'], $PayOrderInfo['PayOrder'], $PayOrderInfo['money'] * 100, $TuiMoney * 100); // 总金额 100, 退款 80,操作员:商户号
                //更改订单状态为已退款
                Db::name('pay_order')->where('OrderSn', $OrderSn['OrderSn'])->where('PayOrder', $PayOrderInfo['PayOrder'])->update(['type' => 0]);
            } 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);
            }
            $res = Db::name('tuikuan')->where('OrderSn', $OrderInfo['OrderSn'])->where('seller_id', $IsSeller)->update(['status' => $params['status']]);
            if ($params['type'] == 1) {
                //拒绝签订协议 给予用户退款
                $OrderSn = Db::name('agreement')->where('id', $params['id'])->value('OrderSn');
                $PayOrderInfo = Db::name('pay_order')->where('OrderSn', $OrderSn)->where('type', 1)->find();
                $TuiMoney = $PayOrderInfo['UpMoney'] * $params['bili'] + $PayOrderInfo['Money'];
                //配置
                $config = [
                    'app_id' => 'wx6a9080f20326f817',
                    'payment' => [
                        'merchant_id' => '1603658973',
                        'key' => '8695A8185xyzKcdEVfreewayShenzhen',
                        'cert_path' => '/home/wwwroot/fast/book/addons/epay/certs/apiclient_cert.pem', // XXX: 绝对路径!!!!
                        'key_path' => '/home/wwwroot/fast/book/addons/epay/certs/apiclient_key.pem',      // XXX: 绝对路径!!!!
                    ],
                ];
                $app = Factory::officialAccount($config);
                try {
                    $result = $app->refund->byTransactionId($PayOrderInfo['WeChatOrder'], $PayOrderInfo['PayOrder'], $PayOrderInfo['money'] * 100, $TuiMoney * 100); // 总金额 100, 退款 80,操作员:商户号
                    //更改订单状态为已退款
                    Db::name('pay_order')->where('OrderSn', $OrderSn)->where('PayOrder', $PayOrderInfo['PayOrder'])->update(['type' => 0]);
                } 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="订单号")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功',
    )
     */
    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);
    }


    /**
     * 公共接口
     * @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);
    }


    //定时任务
    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;
                        }
                    }
                }
            }
        }
    }


    /**
     * 公共接口
     * @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':'返回成功',
    "data": {
    "Avatar": "http://kcd.qiniu.bronet.cn/uploads/20201031/FnCgZycGvvpzdFwpJyrZoSN7iqCX.jpg",
    "Title": "电池类型四",
    "Manufactor": "银河百荣"
    }
    )
     */
    public function BatteryCon()
    {
        $Code = input('battery_code');
        if (empty($Code) || $Code == '' || $Code == "" || $Code == null) {
            $this->error('请先链接蓝牙', 0);
            die;
        }
        $map['BatteryCode'] = ['LIKE', '%' . $Code . '%'];
        //用户电池分类ID
        $Id = Db::name('battery_code')->where($map)->find();
        if (empty($Id)) {
            $this->error('系统没有找到该电池分类', 0);
            die;
        }
        $data = [
            'Avatar' => cdnurl($Id['avatar']),
            'Title' => $Id['title'],
            'Manufactor' => $Id['manufactor']
        ];
        $this->success('成功', $data);
    }
}