<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Exception;

class Cooperation extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = Db::name('cooperation');
    }

    /**
     * 保存
     * @return void
     */
    public function save()
    {
        try {
            //验证参数
            $id = $this->request->param('id',0);
            $userId = $this->auth->id;
            $scene = !empty($id) ? 'edit' : 'add';
            $validate = validate('Cooperation');
            if(!$validate->check($this->request->param(),[],$scene)){
                throw new Exception($validate->getError());
            }
            $time = time();
            $data = [
                'name' => $this->request->param('name', ''),
                'mobile'  => $this->request->param('mobile', ''),
                'servicetype_id'  => $this->request->param('servicetype_id', 0),
            ];
            if (empty($id)) {
                $data['user_id'] = $userId;
                $data['createtime'] = $time;
                $res = $this->model->insertGetId($data);
            } else {
                $data['updatetime'] = $time;
                $where['id'] = $id;
                $where['user_id'] = $userId;
                $res = $this->model->where($where)->update($data);
            }
            if (!$res) {
                throw new Exception('操作失败');
            }
            $this->success('操作成功');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }
}