<?php
/** App登录控制器
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaoq <xiaoq@570035208.com>
 */

namespace Wxsmall\Controller;
class TakeoutController extends BaseController {
	public function _initialize(){
        	parent::_initialize ();
    	}
	/**
	 * 获取附近门店列表页
	 */
	public function index(){
        $param = I('param.');
        $user_info=$this->checkuserauth();
        $param['uid']=$user_info['id'];
        $param['shop_id']=$user_info['HCshop']['bind_shop_id'];//追加当前会员匹配的门店
        $result = D('Takeout')->index($param,$user_info['rank_id']);
        $result['HCshop'] = $user_info['HCshop'];//当前会员匹配的门店存储到客户端
        $cart_info=D("Takeout")->get_cart_total_info($user_info['id']);
        $result['cart_info']=$cart_info;
        $result['temp_id']=C("LIST_TPL_WX");
        $result['data']['is_sell'] = C("IS_SHOW_SALES_VOLUME");
        $this->ajaxReturn($result);
	}
    /**
     * 获取商品价格
     */
    public function get_goods_price(){
        $return=array('status'=>1);
        $param=I('post.');
        $goods_ids=explode(',',$param['goods_ids']);
        $goods_price_info=array();
        if($goods_ids){
            foreach($goods_ids as $key=>$val){
                $price_info=D('Common/Takeout')->get_min_price($param['shop_id'],$val);
                $goods_price_info[$key]['shop_price']=$price_info['goods_price'];
                $goods_price_info[$key]['id']=$val;
                $goods_price_info[$key]['sprice']=format_price($price_info['goods_price']);
            }
        }
        $return['data']=$goods_price_info;
        $this->ajaxReturn($return);
    }

    /**
     * 商品详情页
     */
    public function cont(){
       $param=I('param.');
        $user_info=$this->checkuserauth();
        $param['uid']=$user_info['id'];
        $param['rank_id']=$user_info['rank_id'];
        $param['shop_id']=$user_info['HCshop']['bind_shop_id'];//追加当前会员匹配的门店
        $result = D('Takeout')->cont($param);
        $this->ajaxReturn($result);
    }

    /**
     * 获取商品内容
     */
    public function cont_detial(){
        $param=I('param.');
        $data=D("Takeout")->get_goods_content($param);
        $this->ajaxReturn($data);
    }
    public function collect_goods(){
        $param=I('param.');
        $user_info=$this->checkuserauth();
        $param['uid']=$user_info['id'];
        $data=D("Takeout")->collect_goods($param);
        $this->ajaxReturn($data);
    }
    public function add_cart(){
        $param=I('param.');
        $user_info=$this->checkuserauth();
        $param['uid']=$user_info['id'];
        $param['shop_id']=$user_info['HCshop']['bind_shop_id'];//追加当前会员匹配的门店
        $data=D("Takeout")->add_cart($param);
        $this->ajaxReturn($data);
    }
    public function add_carts(){
        $param=I('param.');
        if($param['goods_attr']){
           $goods_attr= json_decode(htmlspecialchars_decode($param['goods_attr']),true);
        }
        if($goods_attr){
            $param['spec']=$goods_attr['key'];
            $param['name']=$goods_attr['name'];
        }
        $user_info=$this->checkuserauth();
        $param['uid']=$user_info['id'];
        $param['shop_id']=$user_info['HCshop']['bind_shop_id'];//追加当前会员匹配的门店
        $data=D("Common/Takeout")->add_cart_item($param);
        //404
        if($data['status']==1 && $param['live_anchor_id'] && $param['live_history_id']){
            //328换接口
            $groupid=trim(idtoname($param['live_anchor_id'],'LiveAnchor','group_id','id',false));
            $name = D('Chat')->getnickname($user_info);
            $im= new \Common\Vendor\JimIM;
            $admin = getconfig('USERSIG');
            if(!$admin || empty($admin)){
                $info = ['username' => 'admin','password' => 'password'];
                $ret=$im->registerAdmin($info);
                if($ret){
                    $save=$sarr=array();
                    $save['value'] = 'admin';
                    $sarr['name'] = array('like','%USERSIG%');
                    $sd = M('Config')->where($sarr)->save($save);
                }
            }
            // if(empty($ret['body'])){
            $from=$target=$msg=array();
            $from['type'] = 'admin';
            $from['id'] = 'admin';
            $target['type'] = 'chatroom';
            $target['id'] = $groupid;
            $msg['text'] = $name."正在购买";
            $res = $im->sendCustom($from,$target,$msg);
            // }
            //end
        }
        //end
        $cart_info=D("Takeout")->get_cart_total_info($user_info['id']);
        $data['cart_info']=$cart_info;
        $this->ajaxReturn($data);
    }
    public function sub_cart(){
        $return=array('status'=>3);
        $param=I('post.');
        $return['data']=$param;
        $user_info=$this->checkuserauth();
        $param['uid']=$user_info['id'];
        $param['shop_id']=$shop_id=$user_info['HCshop']['bind_shop_id'];//追加当前会员匹配的门店
        $goods_id=$param['goods_id'];
        $map = array();
        $map['id']=$goods_id;
        $goods_info=M('Goods')->where($map)->field('goods_name,goods_number,img,market_price,goods_sn,cat_id,promote_id,promote_price,promote_start_time,promote_end_time,sale_type,goods_number,sell_count,goods_max_number,goods_min_number,pt_id')->find();
        if($goods_info['pt_id'] && $param['type'] == 6){
            $map=array();
            $map['id']=$goods_info['pt_id'];
            $map['start_time'] = array('elt',NOW_TIME);
            $map['end_time'] = array('egt',NOW_TIME);
            $promote_info=M('PromotAct')->where($map)->field('buy_limit,start_time,end_time')->find();
            // 查询该会员在此活动下已购数量
            $p_num=D("Common/Takeout")->pro_num($promote_info,$param['uid'],$goods_id);
            $p_num=$param['number']+$p_num;
            if($goods_info['goods_min_number']>0 && $p_num > $goods_info['goods_min_number']){
                $return['msg'] = "本活动单人限量".$goods_info['goods_min_number']."您已超过单人限量";
                $this->ajaxReturn($return);
            }
            //总限量
            $p_num=D("Common/Takeout")->pro_num($promote_info,$param['uid'],$goods_id,1);
            $p_num=$param['number']+$p_num;
            if($goods_info['goods_max_number']>=0 && $p_num>$goods_info['goods_max_number']){
                $return['msg'] = $goods_info['goods_name'].'【已超过总限量，总限量'.$goods_info['goods_max_number'].'】';
                $this->ajaxReturn($return);
            }
        }
        //验证是否选择属性
        $goods_attr_map = array();
        $goods_attr_map['g.goods_id'] = $goods_id;
        $goods_attr_map['ga.type'] = array('neq', 'text');
        $map_attr['goods_id']=$goods_id;
        $stockcount = M('GoodsAttrStock')->where($map_attr)->count();
        if($stockcount>0) {
            $goods_attrs = M("GoodsAttr")->alias('g')->distinct("g.attr_id")->where($goods_attr_map)->JOIN('LEFT JOIN __GOODS_ATTRIBUTE__ ga ON g.attr_id=ga.id')->field('attr_id')->select();
            if (!empty($goods_attrs)) {
                $attrs=array();
                if($param['goods_attr'])$attrs = explode("_", $param['goods_attr']);
                if (count($attrs) != count($goods_attrs)) {
                    $return['msg'] = '请选择商品规格';
                    $return['app_data'] = 'open_attr';  //app返回直接加载属性页面
                    $return['status'] = 3;
                    $this->ajaxReturn($return);
                }
            }
        }
        if($param['goods_attr']){
            $goods_attr= json_decode(htmlspecialchars_decode($param['goods_attr']),true);
        }
        if($goods_attr){
            $param['spec']=$goods_attr['key'];
            $param['name']=$goods_attr['name'];
        }
        $uid=$user_info['id'];
        if(!empty($goods_id)){
            $is_num = D("Common/Cart")->shopgoodsstock($goods_id,$shop_id,$goods_attr['key']);
            if($is_num['goods_number'] <= 0){
                $return['msg']="库存不足！";
                $this->ajaxReturn($return);
            }
        }
        $map = array();$map['e.style_ext_id'] = $goods_id;$map['e.style'] = 4;
        $buy_limit = M('PromotAct')->alias('a')->join('__PROMOT_EXT__ e on a.id=e.act_id')->where($map)->order('e.id desc')->getField('buy_limit');
        if($param['number'] > $buy_limit && $buy_limit != 0){
            $return['msg']='按拼团价格买每人限购'.$buy_limit.'件，不得超过数量限制';
            $this->ajaxReturn($return);
        }
        $now_time = NOW_TIME;
        //是否成团
        $pid_order = I('get.pid');
        if(!empty($pid_order)){
            $map_tea['id']=$pid_order;
            $tid = M('OrderInfo')->where($map_tea)->getField('uid');
            if($tid==$uid){
                $return['msg']='你是该团的团长，不可参团购买';
                $this->ajaxReturn($return);
            }
            $map_son = array();$map_son['pid'] = $pid_order;$map_son['pay_status'] = 3;
            $son_uid = M('OrderInfo')->where($map_son)->field('uid')->select();
            if(!empty($son_uid)){
                foreach($son_uid as $k=>$v){
                    $arr[] = $v['uid'];
                }
                if(in_array($uid, $arr)){
                    $return['msg']='你已参加该团，不可再次购买';
                    $this->ajaxReturn($return);
                }
            }
            $p_order_status = M('OrderInfo')->where('id='.$pid_order)->getField('shipping_status');
            if($p_order_status == 1){
                $return['msg']='该团已成团，不可参团';
                $this->ajaxReturn($return);
            }
            $map = array();$map['e.style_ext_id'] = $goods_id;$map['e.style'] = 4;
            $group_time_limit = M('PromotAct')->alias('a')->join('__PROMOT_EXT__ e on a.id=e.act_id')->where($map)->order('e.id desc')->getField('group_time_limit');
            $p_time = M('OrderInfo')->where('id='.$pid_order)->getField('confirm_time');
            $p_end = $p_time + ($group_time_limit * 3600);
            if($p_end<$now_time){
                //已过期未成团的，返还余额
                $status = M('OrderInfo')->where('id='.$pid_order)->getField('status');
                if($status != 10 && $status != 4){
                    $postdata['order_id']=$pid_order;
                    $postdata['admin_id']=$uid;//操作日志用
                    $postdata['type']='Member';//操作日志用
                    $return=D('Common/OrderInfo')->cancel_order($postdata);
                    if($return['status'] == 1){
                        $save['status'] = 10;
                        $map = array();
                        $map['id'] = $pid_order;
                        $update = M('OrderInfo')->where($map)->save($save);
                    }
                    $map = array();
                    $map['pid'] = $pid_order;
                    $son_orders = M('OrderInfo')->where($map)->field('id')->select();
                    if(!empty($son_orders)){
                        $map_order['admin_id']=$uid;//操作日志用
                        $map_order['type']='Member';//操作日志用
                        foreach ($son_orders as $key => $value) {
                            $map_order['order_id']=$value['id'];
                            $updates = D('Common/OrderInfo')->cancel_order($map_order);
                            if($updates['status'] == 1){
                                $maps = array();
                                $maps['id'] = $value['id'];
                                $saves['status'] = 10;
                                $updates = M('OrderInfo')->where($maps)->save($saves);
                            }
                        }
                    }
                }
                $return['msg']='该团已过期，不可参团';
                $this->ajaxReturn($return);
            }
        }
        //是否过期
        $map = array();$map['e.style_ext_id'] = $goods_id;$map['e.style'] = 4;
        $end_time = M('PromotAct')->alias('a')->join('__PROMOT_EXT__ e on a.id=e.act_id')->where($map)->order('e.id desc')->getField('end_time');
        if($end_time<$now_time){
            $return['msg']='该团已过期，不可参团';
           $this->ajaxReturn($return);
        }
        $return['status']=1;
        $return['data']=$param;
        $this->ajaxReturn($return);
    }
    /**
     * 商品立即购买
     */
    public function buy_nows(){
        $param=$postdata=I("param.");
        $postdata['status'] = 1;
        $return['status']=3;
        $shop_id = get_wxsmall_shop_id();
        $user_info=$this->checkuserauth();
        $goods_id=$param['goods_id'];
        $map=array();
        $map['id']=$user_info['id'];
        $member_info=M("Member")->where($map)->getField('mobile');
        if(empty($member_info)){
            $return['msg'] = "手机号不存在";
            $return['data']='no_mobile';
            $this->ajaxReturn($return);
        }
        if($param['sub_list']){
            $param['sub_list'] = json_decode(htmlspecialchars_decode($param['sub_list']),true);
            foreach($param['sub_list'] as $key=>$val){
                $goods_attr = '';
                $goodsattr_info=array();
                if ($val['spec_format']) {
                    $goodsattr_info = array(
                        'key' => $val['spec_format']['key'],
                        'name' => $val['spec_format']['name']
                    );
                    $goods_attr = serialize($goodsattr_info);
                    $map = array();
                    $map['attr_key'] = $val['spec_format']['key'];
                    $map['goods_id'] = $val['id'];
                    $price_info['goods_price'] = M('GoodsAttrStock')->where($map)->getField('attr_price');
                    $price_info['price_type'] = 6;
                }else{
                    $price_info=D('Common/Takeout')->get_min_price($shop_id,$val['id']);//获取商品最终价格
                }
            }
        }
        $param['goods_attr']=$goodsattr_info['key']?$goodsattr_info['key']:0;
        if($param['goods_attr']){
            $goods_attr = serialize($goodsattr_info);
            $map = array();
            $map['attr_key'] = $val['spec_format']['key'];
            $map['goods_id'] = $val['id'];
            $price_info['goods_price'] = M('GoodsAttrStock')->where($map)->getField('attr_price');
            $price_info['price_type'] = 6;
        }
        $uid=$user_info['id'];


        $map = array();
        $map['id']=$goods_id;
        $goods_info=M('Goods')->where($map)->field('goods_name,goods_number,img,market_price,goods_sn,cat_id,promote_id,promote_price,promote_start_time,promote_end_time,sale_type,goods_number,sell_count,goods_max_number,goods_min_number,pt_id')->find();
        if($param['number']<=0){
            $return['msg'] = '请加入商品【'.$goods_info['goods_name'].'】数量';
            return $return;
        }
        $offline=idtoname($goods_id,'Goods','is_offline','id',false);//是否是线上商品
        if($offline==1){
            if(!$param['lshop_id'] && !cookie('lshop_id') && getconfig('REGISTERBUY_OPEN')==0){//不开放购物 并且不是等级会员
                $return['msg']='请先晋升等级在购买【'.$goods_info['goods_name'].'】';
                return $return;
            }
        }

        if($goods_info['sale_type']==1){//组合商品库存
            $goods_number = $this->get_group_goods_stock($goods_id,$shop_id);
            if($param['number']>$goods_number){
                $return['msg'] = $goods_info['goods_name'].'【库存不足，库存量'.$goods_number.'】';
                $this->ajaxReturn($return);
            }
        }else{
           /* if($goods_info['goods_number']>=0){
                if($param['number']>$goods_info['goods_number']){
                    $return['msg'] = $goods_info['goods_name'].'【已超过总限量，总限量'.$goods_info['goods_number'].'】';
                    $this->ajaxReturn($return);
                }
            }*/
        }
        if($goods_info['promote_id']){
            $map=array();
            $map['id']=$goods_info['promote_id'];
            $map['start_time'] = array('elt',NOW_TIME);
            $map['end_time'] = array('egt',NOW_TIME);
            $promote_info=M('PromotAct')->where($map)->field('buy_limit,start_time,end_time')->find();
            // 查询该会员在此活动下已购数量
            $p_num=D("Common/Takeout")->pro_num($promote_info,$param['uid'],$goods_id);
            $p_num=$param['number']+$p_num;
            if($goods_info['goods_min_number']>0 && $p_num > $goods_info['goods_min_number']){
                $return['msg'] = "本活动单人限量".$goods_info['goods_min_number']."您已超过单人限量";
                $this->ajaxReturn($return);
            }
            //总限量
            $p_num=D("Common/Takeout")->pro_num($promote_info,$param['uid'],$goods_id,1);
            $p_num=$param['number']+$p_num;
            if($goods_info['goods_max_number']>=0 && $p_num>$goods_info['goods_max_number']){
                $return['msg'] = $goods_info['goods_name'].'【已超过总限量，总限量'.$goods_info['goods_max_number'].'】';
                $this->ajaxReturn($return);
            }
        }else if($goods_info['pt_id']){
            $map=array();
            $map['id']=$goods_info['pt_id'];
            $map['start_time'] = array('elt',NOW_TIME);
            $map['end_time'] = array('egt',NOW_TIME);
            $promote_info=M('PromotAct')->where($map)->field('buy_limit,start_time,end_time')->find();
            // 查询该会员在此活动下已购数量
            $p_num=D("Common/Takeout")->pro_num($promote_info,$param['uid'],$goods_id);
            $p_num=$param['number']+$p_num;
            if($promote_info['buy_limit']>0 && $p_num > $promote_info['buy_limit']){
                $return['msg'] = "本拼团单人限量".$promote_info['buy_limit']."您已超过单人限量";
                $this->ajaxReturn($return);
            }
            //总限量
            $p_num=D("Common/Takeout")->pro_num($promote_info,$param['uid'],$goods_id,1);
            $p_num=$param['number']+$p_num;
            if($goods_info['goods_max_number']>=0 && $p_num>$goods_info['goods_max_number']){
                $return['msg'] = $goods_info['goods_name'].'【已超过总限量，总限量'.$goods_info['goods_max_number'].'】';
                $this->ajaxReturn($return);
            }
        }
        if($postdata['type'] == 6 || intval($postdata['type']) == 14 || $postdata['type']==''){
            $postdata['status'] = 1;
            $is_num = D("Common/Cart")->shopgoodsstock($postdata['goods_id'],$shop_id,$postdata['goods_attr']);
            if($is_num['goods_number'] <= 0){
                $postdata['status'] = 2;
                $postdata['msg'] = $is_num['info'];
                $this->ajaxReturn($postdata);
            }
            //验证是否选择属性
            $goods_attr_map = array();
            $goods_attr_map['g.goods_id'] = $postdata['goods_id'];
            $goods_attr_map['ga.type'] = array('neq', 'text');
            $map_attr['goods_id']=$postdata['goods_id'];
            $stockcount = M('GoodsAttrStock')->where($map_attr)->count();
            if($stockcount>0) {
                $goods_attrs = M("GoodsAttr")->alias('g')->distinct("g.attr_id")->where($goods_attr_map)->JOIN('LEFT JOIN __GOODS_ATTRIBUTE__ ga ON g.attr_id=ga.id')->field('attr_id')->select();
                if (!empty($goods_attrs)) {
                    $attrs = explode("_", $postdata['goods_attr']);
                    if (count($attrs) != count($goods_attrs)) {
                        $postdata['msg'] = '请选择商品属性';
                        $postdata['app_data'] = 'open_attr';  //app返回直接加载属性页面
                        $postdata['status'] = 2;
                        $this->ajaxReturn($postdata);
                    }
                }
            }
        }
        if($postdata['type'] == 11){
            $return = D("Common/OrderInfo")->check_service($postdata['goods_id'],$shop_id);
            if($return['status'] == 0){
                $postdata['status'] = 3;
                $postdata['msg'] = $return['msg'];
            }else{
                $postdata['status'] = 1;
            }
        }
        if($postdata['type'] == 3){//积分商品
            $postdata['status'] = 1;
            $is_num = D("Common/Cart")->shopgoodsstock($postdata['goods_id'],$shop_id);
            if($is_num['goods_number'] <= 0){
                $postdata['status'] = 3;
                $postdata['msg'] = '库存不足！';
            }
            if(empty($postdata['integra'])){
                $postdata['status'] = 3;
                $postdata['app_data'] = 'open_attr';
                $postdata['msg'] = '请选择付款方式';
            }
        }
        $this->ajaxReturn($postdata);
    }
    /**
     * 商品分享海报
     */
    public function cont_tgercode(){
        $return=array();
        $param=I('param.');
        // $user_info=$this->checkuserauth();
        // $param['uid']=$user_info['id'];
        $result = D('Takeout')->cont_tgercodes($param);
        $this->ajaxReturn($result);

    }
}