<?php
/**
 * 任务计划 - 分钟执行的任务
 *
 *
 *
 *
 */

defined('InShopNC') or exit('Access Invalid!');

class minutesControl extends BaseCronControl
{
    public function indexOp()
    {
        Log::record(__FUNCTION__ . " start",Log::DEBUG);
        //未付款订单超期自动关闭
        $this->_order_timeout_cancel();
        $this->_cron_common();
        $this->_web_index_update();
        $this->_cron_mail_send();
        Log::record(__FUNCTION__ . " end",Log::DEBUG);
    }

    /**
     * 未付款订单超期自动关闭
     */
    private function _order_timeout_cancel()
    {
        Log::record(__FUNCTION__,Log::DEBUG);
        //实物订单超期未支付系统自动关闭
        $_break = false;
        $model_order = Model('order');
        $logic_order = Logic('order');
        $condition = array();
        $condition['order_state'] = ORDER_STATE_NEW;
        $condition['add_time'] = array('lt',time() - ORDER_AUTO_CANCEL_DAY * 86400);

        //分批，每批处理100个订单，最多处理5W个订单
        for ($i = 0; $i < 500; $i++)
        {
            if ($_break) {
                break;
            }
            $order_list = $model_order->getOrderList($condition, '', '*', '', 100);
            if (empty($order_list)) break;
            foreach ($order_list as $order_info)
            {
                Log::record("1",Log::DEBUG);
                $result = $logic_order->changeOrderStateCancel($order_info,'system','系统','超期未支付系统自动关闭订单',true,false);
                Log::record("2",Log::DEBUG);
                if (!$result['state']) {
                    $this->log('实物订单超期未支付关闭失败SN:'.$order_info['order_sn']); $_break = true; break;
                } else {
                    Log::record("3",Log::DEBUG);
                    account_helper::onPredeposit('order_cancel',$order_info['buyer_id'],$order_info['order_sn']);
                    Log::record("4",Log::DEBUG);

                }
            }
        }

        //虚拟订单超期未支付系统自动关闭
        $_break = false;
        $model_vr_order = Model('vr_order');
        $logic_vr_order = Logic('vr_order');
        $condition = array();
        $condition['order_state'] = ORDER_STATE_NEW;
        $condition['add_time'] = array('lt',time() - ORDER_AUTO_CANCEL_DAY * 86400);

        //分批，每批处理100个订单，最多处理5W个订单
        for ($i = 0; $i < 500; $i++)
        {
            if ($_break) {
                break;
            }
            $order_list = $model_vr_order->getOrderList($condition, '', '*', '',100);
            if (empty($order_list)) break;
            foreach ($order_list as $order_info) {
                $result = $logic_vr_order->changeOrderStateCancel($order_info,'system','超期未支付系统自动关闭订单',false);
            }
            if (!$result['state']) {
                $this->log('虚拟订单超期未支付关闭失败SN:'.$order_info['order_sn']);
                $_break = true;
            }
        }
    }

    /**
     * 更新首页的商品价格信息
     */
    private function _web_index_update()
    {
         Model('web_config')->updateWebGoods();
    }

    /**
     * 发送邮件消息
     */
    private function _cron_mail_send()
    {
        //每次发送数量
        $_num = 50;
        $model_storemsgcron = Model('mail_cron');
        $cron_array = $model_storemsgcron->getMailCronList(array(), $_num);
        if (!empty($cron_array))
        {
            $email = new Email();
            $mail_array = array();
            foreach ($cron_array as $val)
            {
                $return = $email->send_sys_email($val['mail'],$val['subject'],$val['contnet']);
                if ($return) {
                    // 记录需要删除的id
                    $mail_array[] = $val['mail_id'];
                }
            }
            // 删除已发送的记录
            $model_storemsgcron->delMailCron(array('mail_id' => array('in', $mail_array)));
        }
    }

    /**
     * 执行通用任务
     */
    private function _cron_common()
    {
        Log::record(__FUNCTION__,Log::DEBUG);
        //查找待执行任务
        $model_cron = Model('cron');
        $cron = $model_cron->getCronList(array('exetime'=>array('elt',time())));
        if (!is_array($cron)) return ;

        $cron_array = array();
        $cronid = array();

        $exeid = 1;
        foreach ($cron as $v)
        {
            $type = intval($v['type']);
            if($type == 8) {
                $cron_array[$v['type']][$exeid] = $v;
                $exeid++;
            }
            else {
                $cron_array[$v['type']][$v['exeid']] = $v;
            }
        }
        foreach ($cron_array as $k=>$v)
        {
            // 如果方法不存是，直接删除id
            if (!method_exists($this,'_cron_'.$k)) {
                $tmp = current($v);
                $cronid[] = $tmp['id'];
                continue;
            }

            $method = '_cron_'.$k;
            Log::record("crontab minutest err:{$method}",Log::DEBUG);

            $result = call_user_func_array(array($this,'_cron_'.$k),array($v));
            if (is_array($result)){
                $cronid = array_merge($cronid,$result);
            }
            else {
                $method = '_cron_'.$k;
                Log::record("crontab minutest err:{$method}",Log::ERR);
            }
        }

        //删除执行完成的cron信息
        if (!empty($cronid) && is_array($cronid)){
            $model_cron->delCron(array('id'=>array('in',$cronid)));
        }
    }

    //'任务类型 1商品上架 2根据商品id更新商品促销价格 3优惠套装过期 4推荐展位过期 5团购开始更新商品促销价格 6团购过期 7限时折扣过期',

    //1商品上架
    private function _cron_1($cron = array())
    {
        $condition = array('goods_commonid' => array('in',array_keys($cron)));
        $update = Model('goods')->editProducesOnline($condition);
        if ($update){
            //返回执行成功的cronid
            $cronid = array();
            foreach ($cron as $v) {
                $cronid[] = $v['id'];
            }
        } else {
            return false;
        }
        return $cronid;
    }

    //2根据商品id更新商品促销价格
    private function _cron_2($cron = array())
    {
        $condition = array('goods_id' => array('in',array_keys($cron)));
        $update = Model('goods')->editGoodsPromotionPrice($condition);
        if ($update){
            //返回执行成功的cronid
            $cronid = array();
            foreach ($cron as $v) {
                $cronid[] = $v['id'];
            }
        }else{
            return false;
        }
        return $cronid;
    }

    //3优惠套装过期
    private function _cron_3($cron = array())
    {
        $condition = array('store_id' => array('in', array_keys($cron)));
        $update = Model('p_bundling')->editBundlingQuotaClose($condition);
        if ($update) {
            //返回执行成功的cronid
            $cronid = array();
            foreach ($cron as $v) {
                $cronid[] = $v['id'];
            }
        } else {
            return false;
        }
        return $cronid;
    }

    //4推荐展位过期
    private function _cron_4($cron = array())
    {
        $condition = array('store_id' => array('in', array_keys($cron)));
        $update = Model('p_booth')->editBoothClose($condition);
        if ($update) {
            //返回执行成功的cronid
            $cronid = array();
            foreach ($cron as $v) {
                $cronid[] = $v['id'];
            }
        } else {
            return false;
        }
        return $cronid;
    }

    //5团购开始更新商品促销价格
    private function _cron_5($cron = array())
    {
        $condition = array();
        $condition['goods_commonid'] = array('in', array_keys($cron));
        $condition['start_time'] = array('lt', time());
        $condition['end_time'] = array('gt', time());
        $groupbuy = Model('groupbuy')->getGroupbuyList($condition);
        foreach ($groupbuy as $val) {
            Model('goods')->editGoods(array('goods_promotion_price' => $val['groupbuy_price'], 'goods_promotion_type' => 1), array('goods_commonid' => $val['goods_commonid']));
        }
        //返回执行成功的cronid
        $cronid = array();
        foreach ($cron as $v) {
            $cronid[] = $v['id'];
        }
        return $cronid;
    }

    /**
     * 抢购过期
     *
     * @param array $cron
     */
    private function _cron_6($cron = array())
    {
        $condition = array('goods_commonid' => array('in', array_keys($cron)));
        //抢购活动过期
        $update = Model('groupbuy')->editExpireGroupbuy($condition);
        if ($update){
            //返回执行成功的cronid
            $cronid = array();
            foreach ($cron as $v) {
                $cronid[] = $v['id'];
            }
        }else{
            return false;
        }
        return $cronid;
    }

    /**
     * 限时折扣过期
     *
     * @param array $cron
     */
    private function _cron_7($cron = array())
    {
        $condition = array('xianshi_id' => array('in', array_keys($cron)));
        //限时折扣过期
        $update = Model('p_xianshi')->editExpireXianshi($condition);
        if ($update){
            //返回执行成功的cronid
            $cronid = array();
            foreach ($cron as $v) {
                $cronid[] = $v['id'];
            }
        }else{
            return false;
        }
        return $cronid;
    }

    private function _cron_8($cron = array())
    {
        $cronid = [];
        foreach ($cron as $v)
        {
            $cronid[] = intval($v['id']);
            $params = $v['params'];
            if(!empty($params))
            {
                $params = unserialize($params);
                if(is_array($params))
                {
                    foreach ($params as $key => $value) {
                        QueueClient::push($key,$value);
                    }
                }
            }
        }

        return $cronid;
    }
}