<?php
namespace app\common\model;

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

class StampDuty extends Model
{

    public function add(){
        $data = [
            'id' => input('id/d',0),
            'title' => input('title','','trim'),
            'content' => input('content','','trim'),
            'bl' => input('bl/f',0),
            'type' => input('type/d',0),
            'enable' => input('enable/d',1),
            'org_id' => input('orgId/d',0)
        ];
        $logdata = json_encode($data);

        $result = validate('StampDuty')->check($data,[],'');
        if(true !== $result){
            HelpHander::error(validate('StampDuty')->getError());
        }
        $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('操作失败');
        }

        if($id > 0){
            $content = '修改印花税目';
        }else{
            $content = '添加印花税目';
        }
        model('ActionLog')->add(4,$content,0,$logdata);

        return true;
    }

    public function info($id){
        $info = $this->where('id',$id)->where('del',0)->find();
        if(!$info){
            HelpHander::error('数据不存在');
        }
        return $info->toArray();
    }

    public function lists($page,$size,$title,$orgId){
        $enable = input('enable/d',-1);
        if($enable >= 0){
            $map[] = ['enable','=',$enable];
        }
        $map[] = ['del','=',0];
        $map[] = ['org_id','=',$orgId];
        if($title != ''){
            $map[] = ['title','like','%'.$title.'%'];
        }
        $lists = $this
            ->where($map)
            ->page($page,$size)
            ->order('id desc')
            ->select();
        $total = $this->where($map)->count();
        $data = [
            'total' => $total,
            'list' => $lists?$lists->toArray():[]
        ];
        return $data;
    }

    public function allLists($orgId){
        $map[] = ['org_id','=',$orgId];
        $map[] = ['del','=',0];
        $map[] = ['enable','=',1];
        $lists = $this
            ->where($map)
            ->field('id,title,bl,type')
            ->order('id asc')
            ->select();

        return $lists?$lists->toArray():[];
    }

    public function del($id){
        $ret = $this->where('id',$id)->setField('del',1);
        if(!$ret){
            HelpHander::error('删除失败');
        }

        $logdata = json_encode(['id' => $id]);
        model('ActionLog')->add(4,'删除印花税目',0,$logdata);
        return true;
    }

}