<?php
namespace app\common\model;

use app\hander\HelpHander;
use think\Db;
use think\Model;

class SalaryApply extends Model
{

    public function add(){
        $data = [
            'id' => input('id/d',0),
            'title' => input('title','','trim'),
            'type' => input('type/d',0),
            'sort' => input('sort/d',0),
            'cate' => input('cate/d',0),
            'sign' => input('sign/d',0),
            'userids' => input('userids','','trim')
        ];

        $result = validate('SalaryApply')->check($data,[],'');
        if(true !== $result){
            HelpHander::error(validate('SalaryApply')->getError());
        }
        $users = explode(',',$data['userids']);
        $arr = [];
        foreach ($users as $v){
            if($v){
                $arr[] = $v;
            }
        }
        $data['userids'] = implode(',',$arr);

        $id = $data['id'];
        unset($data['id']);
        if($id > 0){
            $ret = $this->allowField(true)->save($data,['id'=>$id]);
        }else{
            $ret = $this->allowField(true)->save($data);
        }
        if(!$ret){
            HelpHander::error('操作失败');
        }
        return true;
    }

    public function all($type){
        $map[] = ['type','=',$type];
        $lists = $this
            ->where($map)
            ->order('sort asc,id asc')
            ->select();
        $lists = $lists?$lists->toArray():[];
        foreach ($lists as $k=>$v){
            $uids = explode(',',$v['userids']);
            $users = Db::name('user_info')->where('user_id','in',$uids)->column('name');
            $lists[$k]['users'] = $users?implode(',',$users):'';
        }
        return $lists;
    }

    public function all2($type){
        $map[] = ['type','=',$type];
        $lists = $this
            ->where($map)
//            ->field('id,title,userids,sign')
            ->order('sort asc,id asc')
            ->select();
        $lists = $lists?$lists->toArray():[];
        return $lists;
    }

    public function del($id){
        $ret = Db::name('salary_apply')->delete($id);
        if(!$ret){
            HelpHander::error('删除失败');
        }
        return true;
    }

}