<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\User;
use app\admin\model\off\Line;
use think\Validate;
/**
 * 卖废品接口**
 */
class Sell extends Api
{
    protected  $noNeedLogin = [];
    protected $noNeedRight = '*';
    protected $user_id = '';//token存贮user_id
    public function _initialize()
    {
        parent::_initialize();
        $this->user_id = $this->auth->getUserId();
    }

    /**
     * @ApiTitle    (卖废品信息添加)
     * @ApiSummary  (卖废品信息添加)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/sell/addSell)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="fullname", type="string", required=true, description="姓名")
     * @ApiParams   (name="address", type="string", required=true, description="地址")
     * @ApiParams   (name="description", type="string", required=true, description="废品描述")
     * @ApiParams   (name="pre_date", type="string", required=true, description="预约日期")
     * @ApiParams   (name="pre_time", type="string", required=true, description="预约时间")
     * @ApiParams   (name="images", type="string", required=true, description="废品图片")
     * @ApiParams   (name="share_uid", type="string", required=false, description="分享人uid")
     * @ApiReturn ({
            "code": 1,
            "msg": "保存成功",
            "time": "1553827374",
            "data": null
            })
     */
    public function addSell(){
        if ($this->request->isPost()) {
            $sell_data = $this->request->post();
            //验证数据
            $rule = config('site.sell');
            $validate = new Validate($rule['rule'],$rule['msg']);
            if (!$validate->check($sell_data)) {
                $this->error($validate->getError());
            }
            //如果携带分享uid,则按照积分增加
            if(!empty($sell_data['share_uid'])){
                $score = config('site.share_sell');
                $user = new User();
                $user->where(['id'=>$sell_data['share_uid'],'status'=>'normal'])->setInc('score', $score);
                $offlineModel = new Line();
                $offlineModel->create(['uid'=>$sell_data['share_uid'],'s_score'=>$score,'off_uid'=>$this->user_id]);
            }
            $sell = new \app\admin\model\Sell();
            $data['uid'] = $this->user_id;
            $data['fullname'] = $sell_data['fullname'];
            $data['address'] = $sell_data['address'];
            $data['description'] = $sell_data['description'];
            $data['pre_date'] = $sell_data['pre_date'];
            $data['pre_time'] = $sell_data['pre_time'];
            $data['images'] = $sell_data['images'];
            $data = $sell::create($data);
            if($data){
                $this->success('保存成功');
            }else{
                $this->error('保存失败');
            }
        }else{
            $this->error('请求方式错误');
        }
    }
}