<?php
namespace app\cron;

use app\common\util\AppMsg;
use think\Db;
use yunwuxin\cron\Task;

class WasteTask extends Task
{
    public function configure()
    {
        $this->everyMinute(); //每分钟执行一次
    }

    /**
     * 执行任务
     * @return mixed
     */
    protected function execute()
    {
        try{
           $this->waste();
        }catch (\Exception $e){
            trace($e->getMessage());
        }

    }
    //医废未转运提醒 每分钟执行一次
    public function waste(){
        set_time_limit(0);
        ini_set("memory_limit","1024M");

        $orgids = Db::name('config_org')
            ->alias('co')
            ->join('config c','c.id = co.config_id')
            ->where('c.name','org_waste_status')
            ->where('co.value',1)
            ->column('co.org_id');
        if(!$orgids){
            return false;
        }
        $orgids2 = Db::name('config_org')
            ->alias('co')
            ->join('config c','c.id = co.config_id')
            ->where('c.name','org_waste_time')
            ->where('co.value',date('H:i'))
            ->column('co.org_id');
        if(!$orgids2){
            return false;
        }
        $orgids = array_unique(array_intersect($orgids,$orgids2));
        if(!$orgids){
            return false;
        }
        $users = [];
        foreach ($orgids as $v){
            //检查是否有未转运订单
            $ret = Db::name('waste_record')
                ->where('org_id',$v)
                ->where('status','in',[0,1])
                ->find();
            if(!$ret){
                continue;
            }

            // 检查是否设置通知人员
            $uids = model('Config')->getConfig('org_waste_user',$v);
            if($uids){
                $users = array_merge($users,explode(',',$uids));
            }
        }

        if($users){ //推送
            $length = 1000;
            $count = ceil(count($users)/$length);
            for ($i=0;$i<$count;$i++){
                $uids = array();
                $min = $i*$length;
                $max = $min + $length;
                if($max > count($users)){
                    $max = count($users);
                }
                for($j=$min;$j<$max;$j++){
                    $uids[] = $users[$j];
                }

                send_jpush($uids,AppMsg::PUSH_WASTE_UNFINISH);
            }
        }
    }

}