<?php
namespace app\common\validate;

use think\Db;
use think\Validate;

class SalaryRecord extends Validate{

    protected $rule = [
        'type'  =>  'require|in:1,2,3,4,5,6,7,8,9',
        'month' => 'require|checkMonth',
        'users' => 'require|checkUser',
    ];

    protected $message = [
        'type.require' => '参数错误',
        'type.in' => '参数错误',
        'users.require' => '没有要发工资的人员',
    ];

    protected $scene = [
    ];

    protected  function checkUser($value,$rule,$data=[]){
        $users = json_decode($value,true);
        if(!is_array($users)){
            return '未选择用户';
        }

        if($data['type'] != 1 && $data['type'] != 2){
            return true;
        }

        foreach ($users as $k=>$v){
            $users[$k]['psmoney'] = (float)$v['psmoney'];
            $users[$k]['pwmoney'] = (float)$v['pwmoney'];
            $users[$k]['fixedPerformance'] = (float)$v['fixedPerformance'];
            $users[$k]['psmonth'] = (float)$v['psmonth'];
        }

        foreach ($users as $k=>$v){
//            foreach ($v as $key=>$val){
//                if(strpos($key,'subsidies') !== false && $val < 0){
//                    return '金额不能为负';
//                }
//            }
            $should_total = $v['psmoney'] + $v['pwmoney'] + $v['fixedPerformance'] + $v['psmonth'];
            $ret = Db::name('salary_record_log')
                ->alias('srl')
                ->join('salary_record sr','sr.id = srl.salary_record_id')
                ->where('sr.month',$data['month'])
                ->where('sr.del',0)
                ->whereRaw('srl.gwgz > 0 OR srl.xjgz > 0 OR srl.jcjx > 0 OR srl.yjx > 0')
                ->where('srl.user_id',$v['userId'])
                ->find();
            if($should_total > 0){// 发基本工资(只能发一次)
                if($ret){
                    return $v['name'].'已发过本月基本工资';
                }
            }else{
                if(!$ret){
                    return $v['name'].'未发过本月基本工资不能先发补助';
                }
            }
        }
        return true;
    }

    protected function checkMonth($value,$rule,$data=[])
    {
//        $map[] = ['month','=',$data['month']];
        $map[] = ['del','=',0];
        $map[] = ['type','=',$data['type']];
        $map[] = ['status','in',[0,1,3]];
        $info = Db::name('salary_record')->where($map)->find();
        if($info){
            return '有正在处理的工资未发放';
        }
        return true;
    }

}