<?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());
        }
    }

    /**
     * 详情
     * @return void
     */
    public function getInfo()
    {
        try {
            $userId = $this->auth->id;
            $c = 'cooperation';
            $s = 'servicetype';
            $field = $c.'.id,'.$c.'.name,mobile,servicetype_id,cooperation_status,'.$c.'.remark,'.$c.'.createtime,'.$s.'.title as `service_title`';
            $where[$c.'.user_id'] = $userId;
            $result = $this->model->alias($c)
                ->join($s,$s.'.id = '.$c.'.servicetype_id','LEFT')
                ->where($where)->field($field)->find();
            if (!empty($result)) {
                $statusArr = model('Cooperation')->getCooperationStatusList();
                $result['cooperation_status_text'] = isset($statusArr[$result['cooperation_status']]) ? $statusArr[$result['cooperation_status']] : '';
                $result = info_domain_image($result,['aptitude_images']);
            }

            $this->success('获取成功',$result);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }
}