<?php
/**
 * 会员红包管理
 *
 ***/

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

require_once(BASE_ROOT_PATH . '/helper/algorithm.php');
require_once(BASE_ROOT_PATH . '/helper/account_helper.php');
require_once(BASE_ROOT_PATH . '/helper/member_helper.php');
require_once(BASE_ROOT_PATH . '/helper/sms_helper.php');
require_once(BASE_ROOT_PATH . '/mobile/util/errcode.php');


class activity_bonus
{
    const admin_member_id = 36429;
    private $mErrMessage;
    public function err() {
        return $this->mErrMessage;
    }
    private function parse_rate($bonus_rate)
    {
        $params = explode('#', urldecode($bonus_rate));
        $result = [];
        foreach ($params as $val)
        {
            if(preg_match_all('/^(\d{1,3})\|(\d{1,7})\|(\d{1,4})$/', $val, $match))
            {
                $item['rate'] = intval($match[1][0]);
                $item['amount'] = intval($match[2][0]);
                $item['num'] = intval($match[3][0]);
                $result[] = $item;
            }
        }

        if(empty($result)) {
            return false;
        }
        else {
            return $result;
        }
    }

    private function check_param($input, &$ret)
    {
        if(!isset($input['start_time'])) {
            $ret = array('code' => errcode::ErrParamter,'msg' => "请输入活动开始和结束时间.");
            return false;
        }

        $start_tm = strtotime($input['start_time']);
        if($start_tm == false) {
            $ret = array('code' => errcode::ErrParamter,'msg' => "错误的活动开始时间格式，请参考，2016-06-04 10:00:00.");
            return false;
        }

        if($start_tm <  time()) {
            $cur_time = date("Y-m-d H:i:s");
            $ret = array('code' => errcode::ErrParamter,'msg' => "活动时间不能小于服务器当前时间:{$cur_time}");
            return false;
        }

        if(isset($input['end_time'])) {
            $end_tm = strtotime($input['end_time']);
        } else {
            $end_tm = $start_tm + 24 * 3600;
        }

        if($end_tm <= $start_tm) {
            $ret = array('code' => errcode::ErrParamter,'msg' => "活动结束时间必须大于开始时间");
            return false;
        }

        $param = [];
        $param['send_start_date'] = $start_tm;
        $param['send_end_date']   = $end_tm;

        return $param;
    }

    public function make($input)
    {
        if(empty($input['bonus_rate'])) {
            $this->mErrMessage = "bonus_rate 参数为空";
            return false;
        }

        $result = [];
        $result['type_name']   = $input['type_name'];
        $result['type_bless'] = $input['type_bless'];
        $result['sender_id']   = self::admin_member_id;
        $result['sender_name'] = "熊猫美妆";
        $result['send_type']   = $input['send_type'];
        $result['usable_days']   = $input['usable_days'];

        $rate_moneys = $this->parse_rate($input['bonus_rate']);
        if($rate_moneys == false) {
            $this->mErrMessage = "bonus_rate 或者 send_type 参数错误";
            return false;

        } else {
            $result['rate_money'] = $rate_moneys;
        }

        $param = $this->check_param($input,$ret);
        if($param == false) {
            $this->mErrMessage = $ret['msg'];
            return false;
        }

        $result = array_merge($param,$result);

        $pre_helper = new predeposit_helper(self::admin_member_id);
        $ret = $pre_helper->admin_make_bonus($result,$rate_moneys);
        if($ret === false) {
            return false;
        }
        else
        {
            $type_sn = $ret['type_sn'];

            if(BASE_SITE_URL == 'http://manager.lrlz.com') {
                $url = "http://p.lrlz.com/mobile/index.php?act=bonusex&op=open&client_type=wap&type_sn={$type_sn}";
            } else {
                $url = BASE_SITE_URL . "/mobile/index.php?act=bonusex&op=open&client_type=wap&type_sn={$type_sn}";
            }

            return array('type_sn' => $type_sn,'url' => "{$url}");
        }
    }
}

class person_bonusControl extends SystemControl
{
    const EXPORT_SIZE = 5000;
    public function __construct()
    {
        parent::__construct();
        Language::read('points');

    }

    public function addOp()
    {
        if (chksubmit())
        {
            $obj_validate = new Validator();
            $obj_validate->validateparam = array(
                array("input"=>$_POST["bonus_rate"],   "require"=>"true",'validator'=>'Compare','operator'=>' >= ','to'=> 1,"message" => '红包抵扣率必须大于0'),
                array("input"=>$_POST["bonus_amount"], "require"=>"true",'validator'=>'Compare','operator'=>' >= ','to'=> 0.01,"message" => '金额最少一分钱')
            );
            $error = $obj_validate->validate();
            if ($error != ''){
                showMessage($error,'','','error');
            }

            $optype = intval($_POST['operatetype']);
            if ($optype == 1)
            {
                $params = $this->add_params($_POST,$error);
                if($params == false) {
                    showMessage($error,'index.php?act=person_bonus&op=add','','error');
                } else {
                    QueueClient::push('sendBonusAndSMS',$params);
                    showMessage(Language::get('nc_common_save_succ'),'index.php?act=person_bonus&op=add');
                }
            }
            else
            {
                $members = member_helper::from_mobiles($_POST['members'],$error);
                if(!empty($members))
                {
                    $rate = intval($_POST['bonus_rate']);
                    $amount = doubleval($_POST['bonus_amount']);
                    foreach ($members as $member) {
                        $member_id = $member['member_id'];
                        $ret = account_helper::withhold_bonus($rate,$amount,$member_id);
                    }

                    showMessage(Language::get('nc_common_save_succ'),'index.php?act=person_bonus&op=add');
                } else {
                    showMessage("手机列表为空",'index.php?act=person_bonus&op=add','','error');
                }
            }
        }
        else
        {
            $items = Model()->table('sms_template')->where(array('disable' => 0))->field('yuntx_id,title,content')->select();
            Tpl::output('sms_tpls',$items);
            Tpl::showpage('person_bonus.add');
        }
    }


    private function add_params($input, &$err)
    {
        $params= [];

        $params['member']['input_type'] = $input['input_type'];
        if(empty($input['members'])) {
            $err = "手机号码或者SQL语句为空";
            return false;
        } else {
            $params['member']['data'] = $input['members'];
        }
        $params['member']['ex_brand'] = $input['ex_brand'] == 'on' ? true : false;
        $params['member']['ex_lrlz']  = $input['ex_lrlz'] == 'on' ? true : false;

        $params['bonus']['rate'] = intval($input['bonus_rate']);;
        $params['bonus']['amount'] = doubleval($input['bonus_amount']);;
        $params['bonus']['bless'] = $input['bonus_bless'];

        $params['sms']['open'] = $input['send_sms'] == 'on' ? true : false;
        if($params['sms']['open'])
        {
            $tmpid = $input['sms_template'];
            if($tmpid <= 0) {
                $err = "错误的短信模版";
                return false;
            }
            $params['sms']['template_id'] = $tmpid;
        }

        return $params;
    }

    public function checkmemberOp()
    {
        $name = trim($_GET['name']);
        if (!$name){
            echo ''; die;
        }
        /**
         * 转码
         */
        if(strtoupper(CHARSET) == 'GBK'){
            $name = Language::getGBK($name);
        }
        $obj_member = Model('member');
        $member_info = $obj_member->getMemberInfo(array('member_name'=>$name));
        if (is_array($member_info) && count($member_info)>0){
            if(strtoupper(CHARSET) == 'GBK'){
                $member_info['member_name'] = Language::getUTF8($member_info['member_name']);
            }
            echo json_encode(array('id'=>$member_info['member_id'],
                'name'=>$member_info['member_name'],
                'points'=>$member_info['member_points']));
        } else {
            echo ''; die;
        }
    }

    public function promotionOp()
    {
        if(chksubmit())
        {
            $copies = intval($_POST['copies']);
            if($copies <=0 ) {
                showMessage("份数参数必须大于0",'index.php?act=person_bonus&op=promotion','','error');
            }
            else
            {
                if($copies == 1)
                {
                    $maker = new activity_bonus();
                    $ret = $maker->make($_POST);
                    if($ret == false) {
                        $err = $maker->err();
                        showMessage($err,'index.php?act=person_bonus&op=promotion','','error');
                    } else {
                        Tpl::output('type_sn',$ret['type_sn']);
                        Tpl::output('bonus_url',$ret['url']);
                        Tpl::showpage('person_bonus.activity');
                    }
                }
                else
                {
                    $urls = [];
                    for($i = 0; $i < $copies; ++$i)
                    {
                        $maker = new activity_bonus();
                        $ret = $maker->make($_POST);
                        if($ret != false) {
                            $urls[] = $ret['url'];
                        }
                    }

                    $bonus_url = implode(",",$urls);
                    Tpl::output('type_sn',"multi_type_sn");
                    Tpl::output('bonus_url',$bonus_url);
                    Tpl::showpage('person_bonus.activity');
                }
            }
        }
        else
        {
            Tpl::showpage('person_bonus.activity');
        }
    }
}
