<?php

namespace app\api\controller;

use app\api\model\Tax;
use app\api\model\UserAddress;
use app\api\model\UserCoupon;
use app\common\controller\Api;
use EasyWeChat\Factory;
use fast\Http;
use GuzzleHttp\Client;
use think\Config;
use think\Db;
use think\Validate;

/**
 * 我的页面
 */
class User extends Api
{
    protected $noNeedLogin = ['third', 'joinUs', 'developLogin', 'notice'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     * @ApiReturn (
     *     data:{
     *      nickname 昵称
     *      avatar 头像
     *      pay 待支付
     *      wait_send 待发货
     *      wait_collect 待收货
     *      wait_comment 待评价
     *     }
     * )
     */
    public function index()
    {
        $data                 = [];
        $data['nickname']     = $this->auth->nickname;
        $data['avatar']       = cdnurl($this->auth->avatar, true);
        $data['mobile']       = $this->auth->mobile;
        $data['pay']          = Db::name('litestore_order')->where('user_id', $this->auth->id)->where('pay_status', '10')->count();
        $data['wait_send']    = Db::name('litestore_order')->where('user_id', $this->auth->id)->where('freight_status', '10')->count();
        $data['wait_collect'] = Db::name('litestore_order')->where('user_id', $this->auth->id)->where('receipt_status', '10')->count();
        $data['wait_comment'] = Db::name('litestore_order')->where('user_id', $this->auth->id)->where('receipt_status', '20')->count();
        $this->success('会员中心', ['welcome' => $data]);
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar 头像地址
     * @param string $mobile 联系方式
     * @param string $nickname 昵称
     */
    public function profile()
    {
        $user     = $this->auth->getUser();
        $mobile   = $this->request->post('mobile');
        $nickname = $this->request->post('nickname');
        $avatar   = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($mobile) {
            $user->mobile = $mobile;
        }
        if ($nickname) {
            $user->nickname = $nickname;
        }
        if ($avatar) {
            $user->avatar = $avatar;
        }
        $user->save();
        $this->success();
    }


    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $code Code码
     * @param string $nickname 微信昵称
     * @param string $avatar 微信头像
     * @param string $invite_id 邀请人id。默认传0
     */
    public function third()
    {
        $code      = $this->request->post('code');
        $nickname  = $this->request->post('nickname');
        $avatar    = $this->request->post('avatar');
        $invite_id = $this->request->post('invite_id');
        if (!$code || !$nickname || !$avatar) {
            $this->error('后台所需参数缺失请完善参数');
        }
        $param               = [];
        $param['js_code']    = $code;
        $param['grant_type'] = 'authorization_code';
        $param['secret']     = Config::get('site.secret');
        $param['appid']      = Config::get('site.appid');
        $wxapi               = Http::get('https://api.weixin.qq.com/sns/jscode2session', $param);//请求openid
        $wxapi               = json_decode($wxapi, true);
        if (isset($wxapi['errcode'])) {
            $this->error($wxapi['errmsg']);
        }
        $third  = new \app\api\model\Third();
        $userid = $third->where('openid', $wxapi['openid'])->value('user_id');
        if ($userid) {
            $this->auth->direct($userid, $invite_id);
            $third->isUpdate()->save(['session_key' => $wxapi['session_key']], ['user_id' => $userid]);
            $this->success('登录成功', ['token' => $this->auth->getToken(), 'user_type' => $this->auth->user_type]);
        } else {
            if ($invite_id > 0) {
                $userid = $this->auth->register($nickname, '', '', '', ['avatar' => $avatar, 'invite_user_id' => $invite_id, 'invite_time' => time()]);
            } else {
                $userid = $this->auth->register($nickname, '', '', '', ['avatar' => $avatar]);
            }
            if ($userid) {
                $third->isUpdate(false)->save(['openid' => $wxapi['openid'], 'user_id' => $userid, 'session_key' => $wxapi['session_key']]);
                // 注册送优惠券
                $coupon = Db::name('coupon')->where('id', 3)->find();
                $time   = time();
                if ($coupon['register_send_switch'] == '1' && $time >= $coupon['register_send_starttime'] && $time <= $coupon['register_send_endtime']) {
                    UserCoupon::create([
                        'user_id'    => $userid,
                        'coupon_id'  => $coupon['id'],
                        'name'       => $coupon['name'],
                        'price'      => $coupon['price'],
                        'full_price' => $coupon['full_price'],
                        'endtime'    => $time + $coupon['days'] * 86400,
                    ]);
                }
                $this->success('登录成功', ['token' => $this->auth->getToken(), 'user_type' => $this->auth->user_type]);
            } else {
                $this->error('注册失败');
            }
        }
    }

    /**
     * @ApiTitle    (用户授权获取手机号)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="iv", type="string", required=true, description="小程序iv")
     * @ApiParams   (name="encryptedData", type="string", required=true, description="小程序encryptedData")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功',
    "data": {
    "mobile": "13580006666", //没有区号的手机号
    }
    })
     */
    public function getPhoneNumber()
    {
        $param    = $this->request->param();
        $validate = new \think\Validate([
            'iv'            => 'require',
            'encryptedData' => 'require',
        ]);
        $validate->message([
            'iv.require'            => 'iv参数错误!',
            'encryptedData.require' => 'encryptData参数错误!',
        ]);
        if (!$validate->check($param)) {
            $this->error($validate->getError());
        }
        // 获取session_key
        $user  = $this->auth->getUser();
        $third = \app\api\model\Third::where('user_id', $user['id'])->field('session_key')->find();
        empty($third) && $this->error('请先登录');
        // 获取小程序配置
        $app = Factory::miniProgram([
            'app_id' => Config::get('site.appid'),
            'secret' => Config::get('site.secret'),
        ]);
        $res = $app->encryptor->decryptData($third['session_key'], $param['iv'], $param['encryptedData']);
        // 更新手机号
        $user->mobile = $res['purePhoneNumber'];
        $user->save();
        $this->success('授权成功', ['mobile' => $res['purePhoneNumber']]);
    }

    /**
     * @ApiTitle    (用户优惠券)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="type", type="integer", required=true, description="0未使用1已使用2已过期")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    "data": [
    {
    "id": 1,
    "user_id": 1,
    "coupon_id": 1,
    "name": "手动阀手动阀",
    "price": "1.00", 优惠券金额
    "full_price": "10.00", 满减金额
    "createtime": 111122244,
    "endtime": 1641869388,
    "status": "0",
    "endtime_text": "2022年01月11日到期"
    }
    ]
    })
     */
    public function userCoupon()
    {
        $model = new UserCoupon();

        // 更新已过期状态
        $model->where('status', '0')->where('user_id', $this->auth->id)->where('endtime', '<', time())->update(['status' => '2']);

        $type = $this->request->post('type');
        if (!in_array($type, [0, 1, 2])) $this->error('type参数不合法');
        $list = $model->where('status', $type)->where('user_id', $this->auth->id)->select();
        $this->success('用户优惠券列表', $list);
    }

    /**
     * @ApiTitle    (用户地址列表)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    "data": [
    {
    "id": 1,
    "user_id": 1,
    "username": "1", 收件人
    "address": "阿松大", 地址
    "address_detail": "阿松大", 详细地址
    "normal_status": "0", 0不默认1默认
    "lng": null, 经度
    "lat": null, 纬度
    "createtime": null,
    "mobile_hide": "135****9988" 电话号码
    "mobile": "13549059988" 电话号码
    }
    ]
    })
     */
    public function userAddressList()
    {
        $model = new UserAddress();
        $list  = $model->where('user_id', $this->auth->id)->order('normal_status', 'desc')->select();
        $this->success('用户地址列表', $list);
    }


    /**
     * @ApiTitle    (用户修改(删除)地址)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name=id, type=integer, required=true, description="地址id")
     * @ApiParams   (name=type, type=integer, required=true, description="1修改2删除")
     * @ApiParams   (name=username, type=string, required=false, description="收件人")
     * @ApiParams   (name=mobile, type=string, required=flase, description="手机号")
     * @ApiParams   (name=address, type=string, required=false, description="地址")
     * @ApiParams   (name=address_detail, type=string, required=false, description="详细地址")
     * @ApiParams   (name=normal, type=integer, required=false, description="默认状态 0不默认或1默认")
     * @ApiParams   (name=lat, type=float, required=false, description="纬度")
     * @ApiParams   (name=lng, type=float, required=false, description="经度")
     * @ApiReturn   ({
    'code':'1',
    'msg':'SUCCESS'
    "data":
    })
     */
    public function userAddressEdit()
    {
        $id             = $this->request->post('id');
        $type           = $this->request->post('type');
        $username       = $this->request->post('username');
        $mobile         = $this->request->post('mobile');
        $address        = $this->request->post('address');
        $address_detail = $this->request->post('address_detail');
        $normal         = $this->request->post('normal');
        $lat            = $this->request->post('lat');
        $lng            = $this->request->post('lng');
        $data           = [
            'type'   => $type,
            'mobile' => $mobile,
            'id'     => $id,
            'normal' => $normal,
            'lat'    => $lat,
            'lng'    => $lng,
        ];
        $rule           = [
            'type'   => 'require|in:1,2',
            'mobile' => 'regex:^1\d{10}$',
            'id'     => 'require|integer',
            'normal' => 'in:0,1',
            'lat'    => 'float',
            'lng'    => 'float',
        ];
        $msg            = [
            'type'   => 'type参数不合法',
            'mobile' => '电话号码格式不正确',
            'id'     => '地址id不合法',
            'normal' => '默认状态参数不合法',
            'lat'    => '纬度请为浮点数格式',
            'lng'    => '经度请为浮点数格式',
        ];
        $validate       = new \think\Validate();
        $validate->rule($rule);
        $validate->message($msg);
        if (!$validate->check($data)) $this->error($validate->getError());
        $model = new UserAddress();
        if ($type == 1) {
            $data = [
                'mobile'         => $mobile,
                'normal_status'  => $normal,
                'lat'            => $lat,
                'lng'            => $lng,
                'username'       => $username,
                'address'        => $address,
                'address_detail' => $address_detail,
            ];
            if ($normal == 1) $model->isUpdate()->save(['normal_status' => '0'], ['user_id' => $this->auth->id]);
            $model->isUpdate()->save($data, ['id' => $id]);
        } else {
            $model->where('id', $id)->delete();
        }
        $this->success('SUCCESS');
    }

    /**
     * @ApiTitle    (用户添加地址)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name=username, type=string, required=true, description="收件人")
     * @ApiParams   (name=mobile, type=string, required=true, description="手机号")
     * @ApiParams   (name=address, type=string, required=true, description="地址")
     * @ApiParams   (name=address_detail, type=string, required=true, description="详细地址")
     * @ApiParams   (name=normal, type=integer, required=true, description="默认状态 0不默认或1默认")
     * @ApiParams   (name=lat, type=float, required=true, description="纬度")
     * @ApiParams   (name=lng, type=float, required=true, description="经度")
     * @ApiReturn   ({
    'code':'1',
    'msg':'SUCCESS'
    "data":
    })
     */
    public function userAddressAdd()
    {
        $username       = $this->request->post('username');
        $mobile         = $this->request->post('mobile');
        $address        = $this->request->post('address');
        $address_detail = $this->request->post('address_detail');
        $normal         = $this->request->post('normal');
        $lat            = $this->request->post('lat');
        $lng            = $this->request->post('lng');
        $data           = [
            'mobile'   => $mobile,
            'username' => $username,
            'address'  => $address,
            'normal'   => $normal,
            'lat'      => $lat,
            'lng'      => $lng,
        ];
        $rule           = [
            'mobile'   => 'require|regex:^1\d{10}$',
            'username' => 'require',
            'address'  => 'require',
            'normal'   => 'require|in:0,1',
            'lat'      => 'require|float',
            'lng'      => 'require|float',
        ];
        $msg            = [
            'mobile'   => '请正确填写电话号码',
            'username' => '请填写收件人',
            'address'  => '请选择地址',
            'normal'   => '默认状态参数不合法',
            'lat'      => '请上传纬度且为浮点数格式',
            'lng'      => '请上传经度且为浮点数格式',
        ];
        $validate       = new \think\Validate();
        $validate->rule($rule);
        $validate->message($msg);
        if (!$validate->check($data)) $this->error($validate->getError());
        $model = new UserAddress();
        $data  = [
            'mobile'         => $mobile,
            'user_id'        => $this->auth->id,
            'normal_status'  => $normal,
            'lat'            => $lat,
            'lng'            => $lng,
            'username'       => $username,
            'address'        => $address,
            'address_detail' => $address_detail,
        ];
        if ($normal == 1) $model->isUpdate()->save(['normal_status' => '0'], ['user_id' => $this->auth->id]);
        $model->isUpdate(false)->save($data);

        $this->success('SUCCESS');
    }


    /**
     * @ApiTitle    (加入我们)
     * @ApiMethod   (POST)
     * @ApiParams   (name=work, type=string, required=true, description="从事行业")
     * @ApiParams   (name=years, type=string, required=true, description="从业时间")
     * @ApiParams   (name=username, type=string, required=true, description="姓名")
     * @ApiParams   (name=mobile, type=string, required=true, description="手机号")
     * @ApiParams   (name=money, type=string, required=true, description="预计可投入资金")
     * @ApiParams   (name=team, type=integer, required=true, description="团队拥有0没有1有")
     * @ApiParams   (name=city, type=string, required=true, description="意向城市")
     * @ApiParams   (name=content, type=string, required=true, description="自身优势")
     * @ApiReturn   ({
    'code':'1',
    'msg':'SUCCESS'
    "data":
    })
     */
    public function joinUs()
    {
        $work     = $this->request->post('work');
        $years    = $this->request->post('years');
        $username = $this->request->post('username');
        $mobile   = $this->request->post('mobile');
        $money    = $this->request->post('money');
        $team     = $this->request->post('team');
        $city     = $this->request->post('city');
        $content  = $this->request->post('content');
        $data     = [
            'work'     => $work,
            'mobile'   => $mobile,
            'username' => $username,
            'years'    => $years,
            'money'    => $money,
            'team'     => $team,
            'city'     => $city,
            'content'  => $content,
        ];
        $rule     = [
            'work'     => 'require',
            'mobile'   => 'require|regex:^1\d{10}$',
            'years'    => 'require',
            'username' => 'require',
            'money'    => 'require',
            'team'     => 'require|in:0,1',
            'city'     => 'require',
            'content'  => 'require|max:100',
        ];
        $msg      = [
            'work'     => '请填写从事行业',
            'mobile'   => '请正确填写电话号码',
            'years'    => '请填写从业时间',
            'username' => '请输入姓名',
            'money'    => '请输入可投入资金',
            'team'     => '请选择是否拥有团队',
            'city'     => '请填写意向城市',
            'content'  => '请填写描述控制在100字以内',
        ];
        $validate = new \think\Validate();
        $validate->rule($rule);
        $validate->message($msg);
        if (!$validate->check($data)) $this->error($validate->getError());

        // 禁止连点
        !empty(cache('joinus_' . $username)) && $this->error('操作频繁,请稍后再试');
        cache('joinus_' . $username, '123', 5);

        $data['createtime'] = time();
        Db::name('join_us')->insert($data);
        $this->success('SUCCESS');
    }


    /**
     * @ApiTitle    (帮助反馈列表)
     * @ApiMethod   (POST)
     * @ApiHeaders    (name=token, type=string, required=true, description="token")
     * @ApiParams   (name=page, type=integer, required=true, description="页数")
     * @ApiReturn   ({
    'code':'1',
    'msg':'SUCCESS'
    "data":
    "list": {
    "total": 1,
    "per_page": 15,
    "current_page": 1,
    "last_page": 1,
    "data": [
    {
    "id": 1,
    "title": "123", 标题
    "content": "啊实打实大苏打", 内容
    }
    ]
    },
    "rider_status": 0 申请骑手状态:0=无,1=申请中,2=成功,3=拒绝
    "mobile": 拨号电话号码
    })
     */
    public function helpsList()
    {
        $page = $this->request->post('page');
        if (!is_numeric($page)) $this->error('页数参数不合法');
        $list = Db::name('helps')
            ->order('id', 'desc')
            ->paginate(15, false, ['page' => $page]);
        $this->success('SUCCESS', ['list' => $list, 'rider_status' => $this->auth->rider, 'mobile' => Config::get('site.work_mobile')]);
    }

    /**
     * @ApiTitle    (意见反馈)
     * @ApiMethod   (POST)
     * @ApiHeaders    (name=token, type=string, required=true, description="token")
     * @ApiParams   (name=cotent, type=string, required=true, description="意见描述")
     * @ApiParams   (name=images, type=string, required=false, description="图片逗号隔开 不要域名")
     * @ApiParams   (name=mobile, type=string, required=true, description="联系方式")
     * @ApiReturn   ({
    'code':'1',
    'msg':'SUCCESS'
    "data":
    })
     */
    public function opinionAdd()
    {
        $cotent = $this->request->post('cotent');
        $images = $this->request->post('images');
        $mobile = $this->request->post('mobile');
        if (!$cotent) $this->error('请填写意见描述');
        if (mb_strlen($cotent) > 100) $this->error('请将意见描述控制在100字以内');
        if (!$mobile || !preg_match('/^1\d{10}$/', $mobile)) $this->error('请正确填写联系方式');
        $data = [
            'user_id'    => $this->auth->id,
            'cotent'     => $cotent,
            'images'     => $images,
            'mobile'     => $mobile,
            'createtime' => time(),
        ];
        Db::name('opinion')->insert($data);
        $this->success('SUCCESS');
    }

    /**
     * @ApiTitle    (申请成为骑手)
     * @ApiMethod   (POST)
     * @ApiHeaders    (name=token, type=string, required=true, description="token")
     * @ApiReturn   ({
    'code':'1',
    'msg':'SUCCESS'
    "data":
    })
     */
    public function riderApply()
    {
        if (in_array($this->auth->rider, [1, 2])) {
            $this->error('您已申请,不可重复申请');
        }
        $user        = $this->auth->getUser();
        $user->rider = '1';
        $user->save();
        $this->success('SUCCESS');
    }

    /**
     * @ApiTitle    (邀请有奖)
     * @ApiMethod   (POST)
     * @ApiHeaders    (name=token, type=string, required=true, description="token")
     * @ApiReturn   ({
    'code':'1',
    'msg':'邀请有奖'
    "data":
    "price": "10.00", 优惠价格
    "full_price": "100.00", 满减价格
    "endtime": "2022年04月10日", 到期时间
    "rule": "啊实打实大苏打", 规则
    "user_list": [
    {
    "user": {
    "nickname": "admin",
    "avatar_text": ""
    },
    "createtime_text": ""
    }
    ],
    "invite_id": 1, 邀请人id
    })
     */
    public function inviteReward()
    {
        $model               = new \app\api\model\User();
        $coupon              = Db::name('coupon')->where('id', 1)->field('price,full_price,endtime')->find();
        $coupon['endtime']   = date('Y年m月d日', $coupon['endtime']);
        $coupon['rule']      = Config::get('site.invite_rule');
        $coupon['user_list'] = $model
            ->where('invite_user_id', $this->auth->id)
            ->where('invite_status', '1')
            ->limit(3)
            ->select();
        foreach ($coupon['user_list'] as $key => $value) {
            $value->visible(['nickname']);
        }
        $coupon['invite_id'] = $this->auth->id;
        $this->success('邀请有奖', $coupon);
    }

    /**
     * @ApiTitle    (发票管理列表)
     * @ApiMethod   (POST)
     * @ApiHeaders    (name=token, type=string, required=true, description="token")
     * @ApiParams     (name=page, type=integer, required=true, description="页数")
     * @ApiReturn   ({
    'code':'1',
    'msg':'发票管理列表'
    "data":
    "total": 1, 总条数
    "per_page": 5, 每页数量
    "current_page": 1, 当前页
    "last_page": 1, 最后一页
    "data": [
    {
    "id": "1",
    "company_name": "asdsd", 公司名称
    "username": "asdsa", 个人名称
    "type": "1", 1个人发票2公司发票
    "price": 0, 发票价格
    "tax_time": 1654891234,
    "tax_time_text": "2022年01月12日" 开票时间
    }
    ]
    })
     */
    public function taxList()
    {
        $page  = $this->request->post('page', 1);
        $model = new Tax();
        $list  = $model
            ->where('user_id', $this->auth->id)
            ->where('del_status', 'normal')
            ->field('id,company_name,username,type,price,tax_time')
            ->order('id', 'desc')
            ->paginate(5, false, ['page' => $page]);
        $this->success('发票管理列表', $list);
    }


    /**
     * @ApiTitle    (申请发票)
     * @ApiSummary (个人信息和企业信息必填二选一)
     * @ApiMethod   (POST)
     * @ApiHeaders    (name=token, type=string, required=true, description="token")
     * @ApiParams     (name=type, type=integer, required=true, description="1个人2企业单位")
     * @ApiParams     (name=username, type=string, required=false, description="个人名称")
     * @ApiParams     (name=company_name, type=string, required=false, description="公司名称")
     * @ApiParams     (name=tax_number, type=string, required=false, description="纳税识别号")
     * @ApiParams     (name=company_address, type=string, required=false, description="公司地址")
     * @ApiParams     (name=company_mobile, type=string, required=false, description="公司电话")
     * @ApiParams     (name=bank, type=string, required=false, description="开户银行")
     * @ApiParams     (name=mobile, type=string, required=true, description="收票人电话号码")
     * @ApiParams     (name=eamil, type=string, required=true, description="电子邮箱")
     * @ApiParams     (name=order_no, type=string, required=true, description="订单编号")
     * @ApiReturn   ({
    'code':'1',
    'msg':'SUCCESS'
    "data":
    })
     */
    public function taxApply()
    {
        $type            = $this->request->post('type');
        $username        = $this->request->post('username');
        $company_name    = $this->request->post('company_name');
        $tax_number      = $this->request->post('tax_number');
        $company_address = $this->request->post('company_address');
        $company_mobile  = $this->request->post('company_mobile');
        $bank            = $this->request->post('bank');
        $mobile          = $this->request->post('mobile');
        $eamil           = $this->request->post('eamil');
        $order_no        = $this->request->post('order_no');
        //校验数据
        if (!in_array($type, [1, 2])) $this->error('type参数不合法');
        $data     = [
            'mobile'   => $mobile,
            'eamil'    => $eamil,
            'order_no' => $order_no,
        ];
        $rule     = [
            'mobile'   => 'regex:^1\d{10}$',
            'eamil'    => 'regex:^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$',
            'order_no' => 'require',
        ];
        $msg      = [
            'mobile'   => '收票人电话号码格式不正确',
            'eamil'    => '电子邮箱格式不正确',
            'order_no' => '请输入订单编号',
        ];
        $validate = new \think\Validate($rule, $msg);
        if (!$validate->check($data)) $this->error($validate->getError());
        if ($type == 2) {
            $data     = [
                'company_name'    => $company_name,
                'company_mobile'  => $company_mobile,
                'tax_number'      => $tax_number,
                'company_address' => $company_address,
                'bank'            => $bank,
            ];
            $rule     = [
                'company_name'    => 'require',
                'tax_number'      => 'require',
                'company_address' => 'require',
                'bank'            => 'require',
                'company_mobile'  => 'regex:^1\d{10}$',
            ];
            $msg      = [
                'company_mobile'  => '公司电话格式不正确',
                'company_name'    => '请填写公司名称',
                'tax_number'      => '请填写纳税人识别号',
                'company_address' => '请填写公司地址',
                'bank'            => '请填写开户银行',
            ];
            $validate = new \think\Validate($rule, $msg);
            if (!$validate->check($data)) $this->error($validate->getError());
        } else {
            $data     = [
                'username' => $username,
            ];
            $rule     = [
                'username' => 'require',
            ];
            $msg      = [
                'username' => '请填写个人/非企业单位名称',
            ];
            $validate = new \think\Validate($rule, $msg);
            if (!$validate->check($data)) $this->error($validate->getError());
        }
        //校验订单编号
        $orderModel = new \app\api\model\Order();
        $order      = $orderModel::get(['order_no' => $order_no]);
        if (!$order) $this->error('订单编号不存在');
        if ($order['user_id'] != $this->auth->id) $this->error('当前用户无权使用此订单编号');
        // 插入数据
        $data  = [
            'company_name'    => $company_name,
            'username'        => $username,
            'company_mobile'  => $company_mobile,
            'tax_number'      => $tax_number,
            'company_address' => $company_address,
            'bank'            => $bank,
            'mobile'          => $mobile,
            'email'           => $eamil,
            'order_no'        => $order_no,
            'type'            => $type,
            'order_id'        => $order['id'],
            'price'           => $order['total_price'],
            'user_id'         => $this->auth->id,
        ];
        $model = new Tax();
        $model->allowField(true)->isUpdate(false)->save($data);
        $this->success('SUCCESS');
    }


    /**
     * @ApiTitle    (发票删除)
     * @ApiMethod   (POST)
     * @ApiHeaders    (name=token, type=string, required=true, description="token")
     * @ApiParams     (name=ids, type=string, required=true, description="发票id逗号隔开")
     * @ApiReturn   ({
    'code':'1',
    'msg':'SUCCESS'
    "data":
    })
     */
    public function taxDelete()
    {
        $ids = $this->request->post('ids');
        //校验数据
        $ids = explode(',', $ids);
        foreach ($ids as $key => $value) {
            if (!is_numeric($value)) $this->error('ids参数不合法');
        }
        $model = new Tax();
        $model->isUpdate()->save(['del_status' => 'hidden'], ['id' => ['in', $ids]]);
        $this->success('SUCCESS');
    }

    /**
     * 开发登录
     * @ApiMethod (POST)
     * @param string $account 账号
     */
    public function developLogin()
    {
        $account = $this->request->param('account');
        if (!$account) {
            $this->error(__('Invalid parameters'));
        }
        $field = Validate::is($account, 'email') ? 'email' : (Validate::regex($account, '/^1\d{10}$/') ? 'mobile' : 'username');
        $user  = \app\common\model\User::get([$field => $account]);
        if (!$user) {
            $this->error('账号格式不正确');
        }
        $ret = $this->auth->direct($user->id);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 测试
     * @ApiInternal
     */
    public function notice()
    {
        $client   = new Client();
        $response = $client->request('POST', request()->domain() . ":2121/", [
            'form_params' => [
                'type'    => 'publish',
                'content' => '这个是推送的测试数据',
                'to'      => '',
            ],
        ]);
        halt($response->getBody()->getContents());
    }
}