<?php
/**
 * 购买
 *
 *
 *
 *

 */

//use Shopnc\Tpl;

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

require_once (BASE_ROOT_PATH . '/helper/predeposit_helper.php');
require_once (BASE_ROOT_PATH . '/helper/buy_first.php');
require_once (BASE_ROOT_PATH . '/helper/pay_helper.php');
require_once (BASE_ROOT_PATH . '/helper/fcode/operator.php');
require_once (BASE_ROOT_PATH . '/helper/fcode/send_manager.php');
require_once (BASE_ROOT_PATH . '/helper/user_session/fcode.php');

class member_buyControl extends mbMemberControl
{
    private $mFcodeBannerID;

    public function __construct() {
        parent::__construct();

        global $config;
        $this->mFcodeBannerID = $config['autosend_fcodes']['payconfirm_spid'];
    }

    public function calc_cashOp()
    {
        $cart_ids = explode(',', urldecode($_POST['cart_id']));
        if(empty($cart_ids)) {
            return self::outerr(errcode::ErrParamter);
        }

        $logic_buy = logic('buy');
        $id_num = $this->pay_goods($cart_ids);
        //得到购买数据
        $result = $logic_buy->buyStep1($id_num, $_POST['ifcart'], $_SESSION['member_id'], $_SESSION['store_id']);
        if (!$result['state']) {
            return self::outerr(errcode::ErrOrder, $result['msg']);
        } else {
            $result = $result['data'];
        }

        $buy_helper = new buy_first($result);
        if($buy_helper->check_fcode($error) == false) {
            return self::outerr(errcode::ErrPayment,$error);
        }
        else {
            $result = $buy_helper->format();
            $cash_amount  = $result['payinfo']['pay_car_pred'];
            $total_amonut = $result['payinfo']['pay_car_nopred'];

            return self::outsuccess(['cash_amount' => $cash_amount,'goods_amount' => $total_amonut,'payinfo' => $result['payinfo']]);
        }
    }

    public function step_firstOp()
    {
        $cart_ids = explode(',', urldecode($_POST['cart_id']));
        if(empty($cart_ids)) {
            return self::outerr(errcode::ErrParamter);
        }

        $logic_buy = logic('buy');
        $id_num = $this->pay_goods($cart_ids);
        //得到购买数据
        $result = $logic_buy->buyStep1($id_num, $_POST['ifcart'], $_SESSION['member_id'], $_SESSION['store_id']);
        if (!$result['state']) {
            return self::outerr(errcode::ErrOrder, $result['msg']);
        } else {
            $result = $result['data'];
        }

        $buy_helper = new buy_first($result);
        if($buy_helper->check_fcode($error) == false) {
            return self::outerr(errcode::ErrPayment,$error);
        }
        else {
            $result = $buy_helper->format();
            return self::outsuccess($result);
        }
    }

    public function step_secondOp()
    {
        $cart_ids = explode(',', urldecode($_POST['cart_id']));
        if(empty($cart_ids)) {
            return self::outerr(errcode::ErrParamter);
        }

        $param = array();
        $param['ifcart'] = $_POST['ifcart'];
        $param['cart_id'] = $this->pay_goods($cart_ids);
        $param['address_id'] = $_POST['address_id'];
        $param['invoice_id'] = $_POST['invoice_id'];

        $param['vat_hash'] = $_POST['vat_hash'];
        $param['offpay_hash'] = $_POST['offpay_hash'];
        $param['offpay_hash_batch'] = $_POST['offpay_hash_batch'];

        $param['voucher'] = array();
        //手机端暂时不做支付留言，页面内容太多了
        //$param['pay_message'] = json_decode($_POST['pay_message']);
        $param['pd_pay'] = 0;
        $param['rcb_pay'] = 0;
        $param['password'] = "";
        $param['fcode'] = "";
        $param['order_from'] = 2; //从手机来
        $param['pay_name'] = "online";
        $usebonus = $_POST['usebonus'];

        $logic_buy = logic('buy');
        $result = $logic_buy->buyStep2($param, $_SESSION['member_id'], $_SESSION['member_name'], $_SESSION['member_email'],$usebonus);
        if (!$result['state']) {
            return self::outerr(errcode::ErrOrder, $result['msg']);
        }
        else
        {
            $pay_sn = $result['data']['pay_sn'];
            $payment = $_POST['payment'];

            $out_put = pay_helper::pay($pay_sn,$payment,$usebonus,$err);
            if($out_put == false) {
                return self::outerr($err['code'],$err['msg']);
            } else {
                $out_put['payment'] = $payment;
                $out_put['pay_sn']  = $pay_sn;
                return self::outsuccess($out_put);
            }
        }
    }

    public function pay_confirmOp()
    {
        $pay_sn = $_GET['pay_sn'];
        if(empty($pay_sn)) {
            return self::outerr(errcode::ErrParamter,"支付号或者支付类型错误");
        }
        $paied = pay_helper::confirm($pay_sn,$err,$amount,$fcode_state);
        if($paied == false) {
            return self::outerr($err['code'],$err['msg']);
        }
        else
        {
            session_helper::add_order();
            if($fcode_state == 1)
            {
                return self::outsuccess(array('special_list' => null,
                    'summary'  => null,
                    'groupbuy' => null,
                    'limitime' => null,
                    'bundling' => null,
                    'mobile_page' => mobile_page(1)));
            }
            else
            {
                $result = fcode\send_manager::instance()->fetch($amount,$pay_sn,session_helper::cur_mobile(),session_helper::session_id());
                if($result != false)
                {
                    $order_pay = Model('order_pay');
                    $order_pay->where(['pay_sn' => $pay_sn])->update(['fcode_state' => 1]);

                    $fcode = new user_session\fcode();
                    $fcode->onStatus();

                    if($this->mFcodeBannerID > 0) {
                        $blocks = special_manager::instance()->special($this->mFcodeBannerID,$unused_gids);
                    }
                    else {
                        $blocks = [];
                    }

                    foreach ($result['banner'] as $block) {
                        $blocks[] = $block;
                    }

                    $fcodes = [];
                    $gids   = [];
                    foreach ($result['fcode'] as $item)
                    {
                        $fcoder = new fcode\mfcode($item);
                        $fcode = $fcoder->format();
                        if($fcode != false) {
                            $gids[] = intval($fcode['goods_id']);
                            $fcodes[] = $fcode;
                        }
                    }

                    $fcode_blocks = $this->fcode_blocks($fcodes);
                    foreach ($fcode_blocks as $fblock) {
                        $blocks[] = $fblock;
                    }

                    $helper = new goods_helper(false);
                    $ret = $helper->cart_summary($gids,$related_goods);

                    return self::outsuccess(array('special_list' => $blocks,
                        'fcodes'   => $fcodes,
                        'summary'  => $ret['summary'],
                        'groupbuy' => $ret['groupbuy'],
                        'limitime' => $ret['limitime'],
                        'bundling' => $ret['bundling'],
                        'mobile_page' => mobile_page(1)));
                }
                else
                {
                    return self::outsuccess(array('special_list' => null,
                        'summary'  => null,
                        'groupbuy' => null,
                        'limitime' => null,
                        'bundling' => null,
                        'mobile_page' => mobile_page(1)));
                }
            }
        }
    }
    private function fcode_blocks($fcodes)
    {
        $blocks = [];
        foreach ($fcodes as $fcode)
        {
            $block = [];
            $block['item_title'] = '';
            $block['item_type'] = 'home1';
            $block['scale'] = 3.224299;

            $item['image'] = '';
            $item['show_type'] = "fcode";
            $item['show_data'] = strval($fcode['fcode_id']);
            $item['type'] = "goods";
            $item['data'] = strval($fcode['goods_id']);;
            $item['title'] = '';

            $block['items'][] = $item;
            $blocks[] = $block;
        }

        return $blocks;
    }

    public function change_addrexOp()
    {
        $logic_buy = Logic('buy');
        $data = $logic_buy->changeAddr($_POST['freight_hash'], $_POST['city_id'], $_POST['area_id'], $_SESSION['member_id']);
        if (!empty($data) && $data['state'] == 'success')
        {
            $result['offpay_hash'] = $data['offpay_hash'];
            $result['offpay_hash_batch'] = $data['offpay_hash_batch'];

            $freight = 0.00;
            foreach ($data['content'] as $value) {
                $freight += $value['value'];
            }
            $result['freight'] = $freight;

            return self::outsuccess($result);
        } else {
            return self::outerr(errcode::ErrOrder, '地址修改失败');
        }
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /// 旧接口
    public function payOp()
    {
        $pay_sn  = $_GET['pay_sn'];
        $payment = $_GET['payment'];
        $usebonus = intval($_GET['usebonus']) == 0 ? false : true;

        if(empty($pay_sn) || empty($payment)) {
            return self::outerr(errcode::ErrParamter,"支付号或者支付类型错误");
        }

        $out_put = pay_helper::pay($pay_sn,$payment,$usebonus,$err);
        if($out_put == false) {
            return self::outerr($err['code'],$err['msg']);
        } else {
            $out_put['payment'] = $payment;
            $out_put['pay_sn']  = $pay_sn;

            return self::outsuccess($out_put);
        }
    }
    /**
     * 购物车、直接购买第一步:选择收获地址和配置方式
     */
    public function buy_step1Op()
    {
        $cart_id = explode(',', urldecode($_POST['cart_id']));
        $logic_buy = logic('buy');

        //得到购买数据
        $result = $logic_buy->buyStep1($cart_id, $_POST['ifcart'], $_SESSION['member_id'], $_SESSION['store_id']);
        if (!$result['state']) {
            return self::outerr(errcode::ErrOrder, $result['msg']);
        } else {
            $result = $result['data'];
        }

        //整理数据
        $store_cart_list = array();
        foreach ($result['store_cart_list'] as $key => $value) {
            $store_cart_item = array();
            $store_cart_item['goods_list'] = $value;
            $store_cart_item['store_goods_total'] = $result['store_goods_total'][$key];
            if (!empty($result['store_premiums_list'][$key])) {
                $result['store_premiums_list'][$key][0]['premiums'] = true;
                $result['store_premiums_list'][$key][0]['goods_total'] = 0.00;
                $store_cart_item['goods_list'][] = $result['store_premiums_list'][$key][0];
            }
            $store_cart_item['store_mansong_rule_list'] = $result['store_mansong_rule_list'][$key];
            $store_cart_item['store_voucher_list'] = $result['store_voucher_list'][$key];
            if (!empty($result['cancel_calc_sid_list'])) {
                $store_cart_item['freight'] = '0';
                $store_cart_item['freight_message'] = $result['cancel_calc_sid_list'][$key]['desc'];
            } else {
                $store_cart_item['freight'] = '1';
                $store_cart_item['freight_message'] = $result['need_calc_sid_list']['desc'];
            }
            $store_cart_item['store_name'] = $value[0]['store_name'];
            array_push($store_cart_list, $store_cart_item);
        }

        $buy_list = array();
        $buy_list['store_cart_list'] = $store_cart_list;
        $buy_list['freight_hash'] = $result['freight_list'];
        $buy_list['address_info'] = $result['address_info'];
        $buy_list['ifshow_offpay'] = null;
        $buy_list['vat_hash'] = $result['vat_hash'];
        $buy_list['inv_info'] = $result['inv_info'];
        $buy_list['available_predeposit'] = $result['available_predeposit'];
        $buy_list['available_rc_balance'] = $result['available_rc_balance'];

        return self::outsuccess($buy_list);
    }

    /**
     * 购物车、直接购买第二步:保存订单入库，产生订单号，开始选择支付方式
     */
    public function buy_step2Op()
    {
        $param = array();
        $param['ifcart'] = $_POST['ifcart'];
        $param['cart_id'] = explode(',', urldecode($_POST['cart_id']));
        $param['address_id'] = $_POST['address_id'];

        $param['vat_hash'] = $_POST['vat_hash'];
        $param['offpay_hash'] = $_POST['offpay_hash'];
        $param['offpay_hash_batch'] = $_POST['offpay_hash_batch'];
        $param['pay_name'] = $_POST['pay_name'];
        $param['invoice_id'] = $_POST['invoice_id'];

        //处理代金券
        $voucher = array();
        $post_voucher = explode(',', $_POST['voucher']);
        if (!empty($post_voucher)) {
            foreach ($post_voucher as $value) {
                list($voucher_t_id, $store_id, $voucher_price) = explode('|', $value);
                $voucher[$store_id] = $value;
            }
        }
        $param['voucher'] = $voucher;

        //手机端暂时不做支付留言，页面内容太多了
        //$param['pay_message'] = json_decode($_POST['pay_message']);
        $param['pd_pay'] = $_POST['pd_pay'];
        $param['rcb_pay'] = $_POST['rcb_pay'];
        $param['password'] = $_POST['password'];
        $param['fcode'] = $_POST['fcode'];
        $param['order_from'] = 2;
        $logic_buy = logic('buy');

        $result = $logic_buy->buyStep2($param, $_SESSION['member_id'], $_SESSION['member_name'], $_SESSION['member_email']);
        if (!$result['state']) {
            return self::outerr(errcode::ErrOrder, $result['msg']);
        }

        return self::outsuccess(array('pay_sn' => $result['data']['pay_sn']));
    }

    /**
     * 验证密码
     */
    public function check_passwordOp()
    {
        if (empty($_POST['password'])) {
            return self::outerr(errcode::ErrOrder, '参数错误');
        }

        $model_member = Model('member');

        $member_info = $model_member->getMemberInfoByID($_SESSION['member_id']);
        if ($member_info['member_paypwd'] == md5($_POST['password'])) {
            return self::outsuccess(array('result' => '1'));
        } else {
            return self::outerr(errcode::ErrOrder, '密码错误');
        }
    }

    /**
     * 更换收货地址
     */
    public function change_addressOp()
    {
        $logic_buy = Logic('buy');
        $data = $logic_buy->changeAddr($_POST['freight_hash'], $_POST['city_id'], $_POST['area_id'], $_SESSION['member_id']);
        if (!empty($data) && $data['state'] == 'success') {
            return self::outsuccess($data);
        } else {
            return self::outerr(errcode::ErrOrder, '地址修改失败');
        }
    }

    /**
     * @param $cart_ids
     * @return array
     */
    private function pay_goods($cart_ids)
    {
        if (boolval($_POST['ifcart']) == true)
        {
            $mod_cart = Model('cart');
            $items = $mod_cart->listCart('db', array('cart_id' => array('in', $cart_ids)), false);
            $id_num = [];
            foreach ($items as $val) {
                $cart_id = $val['cart_id'];
                $goods_num = $val['goods_num'];
                $id_num[] = "{$cart_id}|{$goods_num}";
            }
            return $id_num;
        } else {
            $id_num = $cart_ids;
            return $id_num;
        }
    }
}