<?php

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

require_once(BASE_ROOT_PATH . "/helper/kdn_helper.php");
require_once(BASE_ROOT_PATH . "/helper/predeposit_helper.php");
require_once(BASE_ROOT_PATH . "/helper/pay_helper.php");
require_once(BASE_ROOT_PATH . "/helper/bonus/witholder.php");
require_once(BASE_ROOT_PATH . '/helper/relation_helper.php');
require_once(BASE_ROOT_PATH . '/helper/area_helper.php');

class admin_operControl extends mbMemberControl
{
    public function __construct()
    {
        parent::__construct();
    }

    private function add_system(&$param)
    {
        $param['sender_id'] = $_SESSION['member_id'];
        $param['sender_name'] = "熊猫美妆";
    }

    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,6})\|(\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_activityOp()
    {
        if(empty($_GET['bonus_rate'])) {
            return self::outerr(errcode::ErrParamter,"bonus_rate 参数为空");
        }

        $rate_moneys = $this->parse_rate($_GET['bonus_rate']);
        if($rate_moneys == false) {
            return self::outerr(errcode::ErrParamter,"bonus_rate 或者 send_type 参数错误");
        } else {
            $_GET['rate_money'] = $rate_moneys;
        }

        $param = $this->check_param($_GET,$ret);
        if($param == false) {
            return self::outerr($ret['code'],$ret['msg']);
        }

        $param = array_merge($param,$_GET);
        $this->add_system($param);

        $pre_helper = new predeposit_helper($_SESSION['member_id']);
        $ret = $pre_helper->admin_make_bonus($param,$rate_moneys);
        if($ret === false) {
            return self::outerr(errcode::ErrBonus,"生成红包失败.");
        } else {
            $type_sn = $ret['type_sn'];
            $url = BASE_SITE_URL . "/mobile/index.php?act=bonusex&op=open&client_type=wap&type_sn={$type_sn}";
            return self::outsuccess(array('type_sn' => $ret,'url' => "{$url}"));
        }
    }

    public function makeOp()
    {
        if(empty($_GET['bonus_rate'])) {
            return self::outerr(errcode::ErrParamter,"bonus_rate 参数为空");
        }

        $rate_moneys = $this->parse_rate($_GET['bonus_rate']);
        if($rate_moneys == false) {
            return self::outerr(errcode::ErrParamter,"bonus_rate 或者 send_type 参数错误");
        } else {
            $_GET['rate_money'] = $rate_moneys;
        }

        $param = $_GET;
        $this->add_system($param);
        $pre_helper = new predeposit_helper($_SESSION['member_id']);
        $ret = $pre_helper->admin_make_bonus($param,$rate_moneys);

        if($ret === false) {
            return self::outerr(errcode::ErrBonus,"生成红包失败.");
        } else {
            $type_sn = $ret['type_sn'];
            $url = BASE_SITE_URL . "/mobile/index.php?act=bonusex&op=open&client_type=wap&type_sn={$type_sn}";
            return self::outsuccess(array('type_sn' => $ret,'url' => "{$url}"));
        }
    }

    public function resort_realtaionOp()
    {
        $mod = Model('member_relation');
        $items = $mod->field('member_mobile')->limit(false)->select();
        foreach ($items as $item)
        {
            try
            {
                $mobile = intval($item['member_mobile']);
                $relation = new \relation\mem_relation(0,$mobile);
                $relation->sort_mobile();
            }
            catch (Exception $ex) {
                Log::record($ex->getMessage(),Log::ERR);
            }
        }
    }

    public function putomsOp()
    {
        $pay_sn   = $_GET['pay_sn'];
        $trade_no = $_GET['trade_no'];
        if(empty($pay_sn) || empty($trade_no)) {
            return self::outerr(errcode::ErrApptype);
        }
        $logic_delivery = Logic('delivery');
        $ret = $logic_delivery->putOrder($pay_sn, $trade_no);
        if($ret == true) {
            return self::outsuccess(array('state' => true));
        } else {
            return self::outerr(array('state' => false));
        }
    }

    public function putallOp()
    {
        $order = Model('order');
        $items = $order->table('order')->field('pay_sn,trade_no')->where(array('order_state' => array('in',array(ORDER_STATE_PAY))))->limit(false)->select();
        foreach($items as $val)
        {
            $pay_sn = $val['pay_sn'];
            $trade_no = $val['trade_no'];

            $logic_delivery = Logic('delivery');
            $ret = $logic_delivery->putOrder($pay_sn, $trade_no);
            if(!$ret) {
                Log::record("putallOp pay_sn={$pay_sn} trade_no = {$trade_no}");
            }
        }
    }

    public function reset_bonus_typeOp()
    {
        $bonus_type = Model('bonus_type');
        $ret = $bonus_type->where(array('type_id' => array('gt',0),'bonus_rate' => 0))->update(array('bonus_rate' => 30));

        if($ret == false) {
            return self::outerr(errcode::ErrDB);
        } else {
            return self::outsuccess(null);
        }
    }

    public function reset_bonus_snOp()
    {
        $bonus_type = Model('bonus_type');
        $types = $bonus_type->field('type_id,type_sn')->where(array('type_id' => array('gt',0)))->limit(false)->select();
        foreach ($types as $type)
        {
            $type_id = intval($type['type_id']);
            $type_sn = $type['type_sn'];
            $user_bonus = Model('user_bonus');

            $bonuses = $user_bonus->field('bonus_id,bonus_sn')->where(array('type_id' => $type_id))->limit(false)->select();
            $count = count($bonuses);
            if($count <= 0) {
                continue;
            } elseif($count <= 10) {
                $format = "%d";
            } elseif($count <= 100) {
                $format = "%02d";
            } elseif ($count <= 1000) {
                $format = "%03d";
            } else {
                $format = "%04d";
            }
            $pos = 0;
            foreach ($bonuses as $bonus) {
                $bonus_sn = $type_sn . sprintf($format,$pos);
                $user_bonus->where(array('bonus_id' => intval($bonus['bonus_id'])))->update(array('bonus_sn' => $bonus_sn));
                if($user_bonus->affected_rows() <= 0) {
                    Log::record("update bonus_sn error",Log::ERR);
                }
                $pos++;
            }
        }
    }


//    // 更新商品序列号
//    public function updateGoodsSerialOp()
//    {
//        $sku_map = Model()->table('sku_map')->limit(10000)->select();
//
//        foreach ($sku_map as $value) {
//
//            $condition = array('goods_serial_tm' => trim($value['tmsku']));
//            $updateinfo = array('goods_serial' => $value['psku']);
//
//            $ret = Model('goods_common')->where($condition)->update($updateinfo);
//        }
//
//        joutput_data(array("ret" => 'complete'));
//    }
//
//    private function getSign($data)
//    {
//        return md5(self::$appkey . self::$appPassWord . $data);
//    }
//
//    public function omsOp()
//    {
//        $outdata = '{"type":"PUT_TRADE","data":[{"tid":"8000000000026501","total_fee":"360.00","discount_fee":"","post_fee":"0.00","created":"2016-01-11 14:51:39","pay_time":"2016-01-11 14:51:39","buyer_message":"","express_code":"","pay_account_type":"\u5fae\u4fe1\u652f\u4ed8","pay_account_id":"","pay_account_no":"1007070763201601112636550146","buyer_nick":"anonymous_36365","buyer_email":"","trade_memo":"","receiver_name":"\u6c5f\u6d77\u82d7","receiver_state":"\u4e0a\u6d77","receiver_city":"\u4e0a\u6d77\u5e02","receiver_district":"\u5f90\u6c47\u533a","receiver_address":"\u756a\u79ba\u8def876\u53f7","receiver_zip":"000000","receiver_mobile":"13911129867","receiver_phone":"","order_size":1,"orderList":[{"oid":"80000000000265010","tid":"8000000000026501","title":"DQ\u8482\u73c2 \u5378\u5986\u6cb9170ml 170ml","price":"360.00","num":"1","outer_sku_id":"P0300292","outer_sku_properties_name":"DQ\u8482\u73c2 \u5378\u5986\u6cb9170ml 170ml","buyer_nick":"anonymous_36365"}]}]}';
//        $sign = $this->getSign($outdata);
//        $headers = array('v_appkey: ' . self::$appkey, 'v_sign: ' . $sign, 'Content-Type: application/json');
//        http_request(self::$appURL, $outdata, 'POST', false, $headers);
//    }
//
//    public function test_callbackOp()
//    {
//        $param['order_sn'] = $_POST['tid'];
//        $status = $_POST['status'];
//        //$param['consign_time'] = $_POST['consign_time'];
//        $param['shipping_code'] = $_POST['logistics_no'];
//        $param['oms_code'] = $_POST['logistics_company'];
//
//        if (intval($status) === 1) {
//            $logic_delivery = Logic('delivery');
//            $ret = $logic_delivery->handleCallback($param);
//            joutput_data($ret);
//        } else {
//
//        }
//    }
//
//        /**
//     * 首页
//     */
//    public function indexOp()
//    {
//
//        $t = time();
//
//        $t1 = date("D F d Y", 1452355200);
//
////        $payment = 500;
////        $payment = $payment = $this->getAndUpdateBonus(36218,$payment);
////        joutput_data(array('$payment'=>$payment));
//
//        // 修改地址
//        $order_id = "order_id in (297, 401, 923, 928,1097,1145,1150,1154,1244,1248,1281)";
//        $model = Model('order_common')->where($order_id)->select();
//        $model_address = Model('area');
//        $recv_info_array = array();
//        if ($model != null) {
//
//            foreach ($model as $val) {
//                $recv_info = unserialize($val['reciver_info']);
//
//                $recv_info['area'] = $model_address->formatAddress($recv_info['area']);
//                Model()->table('recv_info')->insert(array('order_id' => $val['order_id'], 'reciver_info' => serialize($recv_info)));
//
//                Model('order_common')->where(array('order_id' => $val['order_id']))->update(array('reciver_info' => serialize($recv_info)));
//
//                array_push($recv_info_array, $recv_info);
//            }
//        }
//
//        joutput_data($recv_info_array);
//    }
//
//    public function getAndUpdateBonus($user_id, $pay_amount)
//    {
//
//        $condition['user_id'] = $user_id;
//        $condition['type_id'] = 1;
//        $bonus_list = Model()->table("user_bonus")->where($condition)->select();
//
//        $ret_value = 0;
//        if (!empty($bonus_list)) {
//
//            foreach ($bonus_list as $value) {
//                $bonus_value = doubleval($value['bonus_value']);
//
//                if (($pay_amount - $bonus_value) > 0.0000001) {
//
//                    $data['bonus_value'] = 0;
//                    $ret = Model()->table('user_bonus')->where(array('bonus_id' => $value['bonus_id']))->update($data);
//
//                    if ($ret) {
//                        $pay_amount -= $bonus_value;
//                    }
//                } else {
//
//                    $data['bonus_value'] = $bonus_value - $pay_amount;
//                    $ret = Model()->table('user_bonus')->where(array('bonus_id' => $value['bonus_id']))->update($data);
//
//                    if ($ret) {
//                        $pay_amount = 0;
//                    }
//                    break;
//                }
//            }
//        }
//
//        return $pay_amount;
//    }
//
//    /**
//     * order_sn
//     * member_id
//     *
//     * 手动退款接口
//     */
//    public function refundOp()
//    {
//        $model_trade = Model('trade');
//        $order_info = Model('order')->getOrderInfo(array('order_sn' => $_GET['order_sn']));
//        if (empty($order_info)) return;
//
//        $model_refund = Model('refund_return');
//        $order_id = intval($order_info['order_id']);
//        $condition = array();
//        $condition['buyer_id'] = $order_info['buyer_id'];
//        $condition['order_id'] = $order_id;
//        $order = $model_refund->getRightOrderList($condition);
//        $order_amount = $order['order_amount'];//订单金额
//        $condition = array();
//        $condition['buyer_id'] = $order['buyer_id'];
//        $condition['order_id'] = $order['order_id'];
//        $condition['goods_id'] = '0';
//        $condition['seller_state'] = array('lt', '3');
//        $refund_list = $model_refund->getRefundReturnList($condition);
//        $refund = array();
//        if (!empty($refund_list) && is_array($refund_list)) {
//            $refund = $refund_list[0];
//        }
//        $order_paid = $model_trade->getOrderState('order_paid');//订单状态20:已付款
//        $payment_code = $order['payment_code'];//支付方式
//        if ($refund['refund_id'] > 0 || $order['order_state'] != $order_paid || $payment_code == 'offline') {//检查订单状态,防止页面刷新不及时造成数据错误
//            joutput_error(array("result" => false));
//            return false;
//        }
//
//        $refund_array = array();
//        $refund_array['refund_type'] = '1';//类型:1为退款,2为退货
//        $refund_array['seller_state'] = '1';//状态:1为待审核,2为同意,3为不同意
//        $refund_array['order_lock'] = '2';//锁定类型:1为不用锁定,2为需要锁定
//        $refund_array['goods_id'] = '0';
//        $refund_array['order_goods_id'] = '0';
//        $refund_array['reason_id'] = '0';
//        $refund_array['reason_info'] = '取消订单，全部退款';
//        $refund_array['goods_name'] = '订单商品全部退款';
//        $refund_array['refund_amount'] = ncPriceFormat($order_amount);
//        $refund_array['buyer_message'] = $_POST['buyer_message'];
//        $refund_array['add_time'] = time();
//
//        $pic_array = array();
//        $pic_array['buyer'] = '';//$this->upload_pic();//上传凭证
//        $info = serialize($pic_array);
//        $refund_array['pic_info'] = $info;
//        $state = $model_refund->addRefundReturn($refund_array, $order);
//
//        if ($state) {
//            $model_refund->editOrderLock($order_id);
//            joutput_data(array("result" => true));
//            return true;
//        } else {
//            joutput_error(array("result" => false));
//            return false;
//        }
//    }
//
//    public function subscribe_kdnOp()
//    {
//        $ordersn = $_GET['order_sn'];
//        kdn_helper::req_subscribe('YD', '3941561454548', $ordersn);
//    }
//
//    private function merge_user($mod_member,$mobile,$name,$passwd,$balance)
//    {
//        $user = $mod_member->where(array('member_mobile' => $mobile))->limit(false)->find();
//        if(empty($user))
//        {
//            $data = array();
//            $data['member_mobile'] = $mobile;
//            $data['member_name'] = $mobile;
//            $data['member_passwd'] = $passwd;
//            $data['member_nickname'] = $name;
//            $data['available_predeposit'] = $balance;
//
//            $mod_member->insert($data);
//        }
//        else
//        {
//            $data = array();
//            $data['member_name'] = $mobile;
//            $data['member_nickname'] = $name;
//
//            $mod_member->where(array('member_id' => $user['member_id']))->update($data);
//            $money = intval($balance * 100 + 0.5);
//
//            if($money > 0) {
//                $pd_helper = new predeposit_helper($user['member_id']);
//                $pd_helper->transform_money($name,$balance);
//            }
//        }
//    }
//
//    public function imolduserOp()
//    {
//        $mod_users = Model('users');
//        $mod_member = Model('member');
//
//        $users = $mod_users->field('*')->limit(false)->select();
//        foreach($users as $val)
//        {
//            $mobile = $val['mobile'];
//            $name = $val['name'];
//            $passwd = $val['encrypted_password'];
//            $balance = $val['remain_balance'];
//
//            $this->merge_user($mod_member,$mobile,$name,$passwd,$balance);
//
//        }
//    }
//
//    public function sendbonusOp()
//    {
//        $pay_sn = '210510764647050484';
//
//        $pay = new pay_helper();
//        $pay->success($pay_sn);
//
//    }
//
//    public function balance_pdbonusOp()
//    {
//        $member_ids = Model()->table("member")->field("member_id")->order("member_id asc")->limit(false)->select();
//        foreach($member_ids as $val) {
//            $member_id = $val["member_id"];
//
//            $pd = new predeposit_helper($member_id);
//            $ret = $pd->get_predeposit();
//            $total = intval($ret['total_value'] * 100 + $ret['freeze_value'] * 100 + 0.5);
//
//            $holder = new bonus\witholder($member_id);
//            $usable_amount = intval($holder->usable_amount() * 100 + 0.5);
//
//            echo "total={$total},usable_amout={$usable_amount}<br/>";
//            if($total < $usable_amount) {
//                echo "witholding<br/>";
//                $holder->withold(($usable_amount - $total) / 100);
//            }
//        }
//    }
//
//    public function init_relationOp()
//    {
//        $member_ids = Model()->table("member")->field("member_id")->order("member_id asc")->limit(false)->select();
//        foreach($member_ids as $val) {
//
//            $member_id = $val["member_id"];
//            echo ("add member_id = {$member_id}<br/>");
//            relation_helper::onRegister($member_id);
//        }
//    }
//
//    public function add_bonus_expiretimeOp()
//    {
//        $is_dev = $_GET["dev"];
//        $day_secs = 3600 * 24;
//
//        if (isset($is_dev) && !empty($is_dev)) {
//            $left_secs = $day_secs;
//        } else {
//            $left_secs = $day_secs * 30;
//        }
//
//        echo "add bonus expire left seconds: {$left_secs} <br/>";
//
//        $expire_time = time() + $left_secs;
//
//        $cond = array("bonus_status" => 3);
//        $data = array("usable_time" => $expire_time);
//
//        $model = Model("user_bonus");
//        $ret = $model->edit($cond, $data);
//        if ($ret == false) {
//            echo 'failed';
//        } else {
//            echo 'update affect rows: ' . $model->affected_rows();
//        }
//
//    }
}