<?php
/**
 * 第三方订单管理
 * @Copyright (C) 2018 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaogg <xiaogg@sina.cn>
 */
 
namespace Admin\Controller;
class ThreeorderController extends BaseController{
    public function _initialize(){
        parent::_initialize ();
        $is_auth=check_use_auth("WEBSHOP");
        if($is_auth['status']==0){
            $this->error('该版本没有此权限',$is_auth['url']);return;
        }
        $this->order_status=array('1'=>'待接单','2'=>'待取货','3'=>'配送中','4'=>'已完成','5'=>'已取消','7'=>'已过期');
        $this->assign('three_order_status',$this->order_status);
        $this->order_type=array('0'=>'自配','1'=>'众包','9'=>'未知');$this->assign('order_type',$this->order_type);
        $this->order_code=array('jddj'=>'京东到家','ele'=>'饿了吗');$this->assign('order_code',$this->order_code);
        $this->order_delivery=array('1'=>'已配送',2=>'未配送');$this->assign('order_delivery',$this->order_delivery);
        $this->get_shops_list();
    }
	public function index(){
        $name = CONTROLLER_NAME;
        $map=array();
        $postdata=I('param.');
        if($postdata['code']==1 || $postdata['code']=='jddj')$map['code']='jddj';
        if($postdata['code']==2 || $postdata['code']=='ele')$map['code']='ele';
        if($postdata['order_sn'])$map['ordersn']=$postdata['order_sn'];
        if($postdata['status'])$map['order_status']=$postdata['status'];
        if($postdata['shop_id'])$map['shop_id']=$postdata['shop_id'];
        if($postdata['type'])$map['type']=$postdata['type'];
        if($postdata['keyword']){
            $whereor['buyer_name']=array('like','%'.$postdata['keyword'].'%');
            $whereor['buyer_mobile']=array('like','%'.$postdata['keyword'].'%');
            $whereor['delivery_name']=array('like','%'.$postdata['keyword'].'%');
            $whereor['delivery_mobile']=array('like','%'.$postdata['keyword'].'%');
            $whereor['_logic'] = 'or';
            $map['_complex'] = $whereor;
        }
        $list = $this->lists('ThreeOrder',$map);
        $i=$goods_amount=0;
        if($list){
            foreach ($list as $key => $value) {
                if($value['order_status']==8)$list[$key]['order_status']=3;
                if($value['order_status']==6)$list[$key]['order_status']=1;
            }
        }
        $order_count=M('ThreeOrder')->where($map)->count();
        $goods_amount=M('ThreeOrder')->where($map)->sum('order_amount');
        $this->assign('goods_amount',$goods_amount);
        $this->assign('order_count',$order_count);
        $this->assign('list',$list);$this->assign($postdata);
        $this->display();
    }
    public function _before_delete(){exit();}
    public function view(){
        $id=I('id');
        if(empty($id))$this->error('参数不正确');
        $map = array();
        $map_oi['id'] = $id;
        $order_info=M('ThreeOrder')->where($map_oi)->find();
        $group=unserialize($order_info['goods_info']);

        $order_info['goodsinfo']=$group;
        foreach ($order_info['goodsinfo'] as $key => $value) {
            if($value['act_good_ids']){
                $val=$value['act_good_ids'];
                $order_info['goodsinfo'][$key]['act_good_ids']=$val;

                if(strpos($val,"-")){
                    $new_arr = $arr = array();
                    $new_arr = explode('-',$val);
                    $arr['attr_key'] = $new_arr[1];
                    $arr['goods_id'] = $new_arr[0];
                    $order_info['goodsinfo'][$key]['goods_id'] = $new_arr[0];
                    $order_info['goodsinfo'][$key]['goodsname'] = idtoname($new_arr[0],'Goods','goods_name');
                    $order_info['goodsinfo'][$key]['attr']='('.attr_key2name($arr['attr_key'],$arr['goods_id']).')';
                    $order_info['goodsinfo'][$key]['goods_sn']=idtoname($arr['attr_key'],'GoodsAttrStock','goods_attr_sn','attr_key',false);
                }else{
                    $order_info['goodsinfo'][$key]['goods_id'] = $val;
                    $order_info['goodsinfo'][$key]['goodsname'] = idtoname($val,'Goods','goods_name');
                    $order_info['goodsinfo'][$key]['goods_sn']=idtoname($val,'Goods','goods_sn','id',false);
                }
            }else{
                $whereor=array();
                $whereor['goods_name']=$value['goods_name'];
                $goods=M('Goods')->where($whereor)->field(true)->find();
                if(empty($goods)){$whereor=array();$whereor['goods_sn']=$value['goodssn'];$goods=M('Goods')->where($whereor)->field(true)->find();}
                if($goods){
                    $order_info['goodsinfo'][$key]['goods_id'] = $goods['id'];
                    $order_info['goodsinfo'][$key]['goodsname'] = $goods['goods_name'];
                    $order_info['goodsinfo'][$key]['goods_sn']=$goods['goods_sn'];
                }else{
                    $order_info['goodsinfo'][$key]['goodsname'] = '请匹配该商品';
                }                
            }
        }
        $order_info['three_status']=$order_info['order_status'];
        if($order_info['order_status']==8)$order_info['three_status']=3;
        if($order_info['order_status']==6)$order_info['three_status']=1;

        $GoodsCategory = getcache('PurchaseCategory');
        $Tree = new \Common\Vendor\Tree();
        $select_categorys = '';
        $treemini = $Tree->treemini($GoodsCategory);
        $select_categorys .= $Tree->treeminioption($treemini, $pid);
        $this->assign('select_categorys', $select_categorys);
        $this->assign($order_info);
        $this->display();
    }
    public function manage(){
        $postdata=I('post.');
        if(empty($postdata['order_id']))$this->error('参数不正确');   
        if($postdata['shopid'])$postdata['shop_id']=$postdata['shopid'];     
        $postdata['operator']='Admin';
        $result=D('Pad/ThreeOrder')->three_manage($postdata);
        if($result['status']){
            $this->success($result['info']);
        }else{
            $this->error($result['info']);
        }
    }
    public function cancel_reason(){
        $postdata=I('param.');
        $order_id=I('order_id');
        $this->assign('order_id',$order_id);
        $this->assign($postdata);
        $order_reason=D('Pad/ThreeOrder')->get_reason('ele');
        $this->assign('order_reason',$order_reason);
        $this->display();
    }
	public function quickedit(){
        $name = I('param.name');        
        if (empty($name)) $this->error(L('PARAM_ERR'));
        $three = new \Common\Vendor\Threeorder($name);
        $appid=C('appid');
        if(IS_POST){
            $postdata=I('post.');
            if(!$postdata['param']['shop_id']){$this->error('参数错误');exit();}
            $base=array($appid=>$postdata['param']['venderId']);
            $three->orderconfig('base',$base);
            $postdata['param']['siteid']=$appid;
            $postdata['param']['update_time']=NOW_TIME;
            $result=$three->orderconfig($postdata['param']['venderId'],$postdata['param']);
            if($result!==false){
                $this->success(L('EDIT_OK'));
            }else{
                $this->error(L('EDIT_ERROR'));
            }
        }else{
            $config=$authurl='';
            $configs=$three->orderconfig('base');            
            if(!empty($configs[$appid])){
                $venderId=$configs[$appid];
                $config=$three->orderconfig($venderId);
                $this->assign($config);                
                $authurl=$three->get_auth_url($venderId);
            }
            $this->assign('authurl',$authurl);
            $this->assign('name',$name);
            $this->display();
        }
    }
    /**
     * 获取下拉仓库
     */
    private function get_shops_list(){
           // $map=array('shop_type'=>1);
        $shops_list=M('Shops')->where(1)->field('id,name')->order('name')->cache(true)->select();
        $shops_list=format_array2select($shops_list);
        $this->assign('shops_list',$shops_list);
    }
    /*搜索店铺商品*/
    public function choose_goods(){
        $postdata=I('post.');
        
        $type=1;//1单选 2多选
        
        $map=array();
        $map['g.status']=1;
        $map['g.is_delete']=0;
        //$map['is_internet']=1;
        $map['g.publish_wait']=1;
        //$map自行扩展
        $map['g.goods_type']=5;
        if(!isset($postdata['keywords'])){
            $postdata['keywords']='';
        }
        if (is_numeric($postdata['keywords'])) {
            $map['g.id|g.goods_name'] = array(intval($postdata['keywords']), array('like', '%' . $postdata['keywords'] . '%'), '_multi' => true);
        } else if (!empty($postdata['keywords'])) {
            $map['g.goods_sn|g.goods_name'] = array('like', '%' . (string)$postdata['keywords'] . '%');
        }
        if (!empty($postdata['search_catid'])) {
            $cat_sons = get_children($postdata['search_catid'], 1,5);
            $catstr = implode(',', $cat_sons);
            $extension_goods_id = get_extension_goods($postdata['search_catid'], 1);
            $extensionstr = implode(',', $extension_goods_id);
            $where = array();
            if (!empty($cat_sons) && !empty($catstr)) {
                $where['g.cat_id'] = array('in', $cat_sons);
            }
            if (!empty($extension_goods_id) && !empty($extensionstr)) {
                $where['g.id'] = array('in', $extension_goods_id);
            }
            if (!empty($where)) {
                $where['_logic'] = 'or';
                $map['_complex'] = $where;
            }
        }
        $join="";
        if($postdata['shop_id']>0){
            $map['s.shop_id']=$postdata['shop_id'];
            $join=" LEFT JOIN __SHOPS_GOODS_STOCK__ s ON g.id=s.goods_id";
        }
        $total=M('Goods')->alias('g')->where($map)->join($join)->count();
        if(empty($total)){
            $return['status']=2;
            $return['info']='没有查询到商品';
            $this->ajaxReturn($return);//返回查询商品为空
        }
        
        $listRows=!empty($postdata['pagesize'])?$postdata['pagesize']:8;
        $page = new \Common\Vendor\Page($total, $listRows);
        $pageconfig='%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%';
        $page->setConfig('theme',$pageconfig);
        $page->rollPage=6;
        $pagehtml = $page->show();
        $list=array();
        //echo "<pre>";print_r($map);exit;
        $list=M('Goods')->alias('g')->where($map)->field('g.id,g.goods_name,g.img,g.goods_sn')->join($join)->limit($page->firstRow.','.$listRows)->select();

        $html='';
        if(!in_array($type,array(1,2)))$type=1;
        foreach($list as $k=>$v){
            $input=$type==2?'<input type="checkbox" value="'.$v['id'].'" name="choose_goods" data-id="'.$v['id'].'" class="f_l" />':'<input value="'.$v['id'].'" name="choose_goods" data-id="'.$v['id'].'" type="radio" class="f_l" />';
            $html.=
            '<div class="choose_goods_item clearfix" title="'.$v['goods_name'].'" attr_data="'.$v['attr_key'].'" attr_name="'.$v['attr'].'" goods_sn="'.$v['goods_sn'].'"><label>'.$input.
                '<img src="'.thumb($v['img']).'" />'.
                '<p>'.str_cut($v['goods_name'],70).'【'.$v['goods_sn'].'】</p><span>'.str_cut($v['attr'],70).'</span></label>'.
            '</div>';
        }        
        $return['status']=1;
        $return['data']=$html;
        $return['page']=$pagehtml;
        $return['totalpages']=$page->totalPages;
        $this->ajaxReturn($return);
    }
    /**
     * 获取商品信息
     */
    public function get_goods(){
        $return=$where=$map = array();
        $postdata = I('param.');
        $id= intval($postdata['id']);
        $html='';
        if($id){
            $map['id'] = $id;
            $map['goods_type']=5;
            $info = M('Goods')->where($map)->field('id,shop_price,supply_price,goods_sn,unit_id,is_type,goods_name')->find();
            $where['goods_id'] =$id;
            $attr_key = M('GoodsAttrStock')->where($where)->field('attr_key,attr_price,goods_attr_sn')->select();
            if($attr_key){

                $html='<select class=\'form-control width_2\' name=\'attr_key[]\' onchange=\'shopprice('.this.')\'>';
                foreach($attr_key as $k=>$v){
                    $attr = attr_key2name($v['attr_key'],$id);
                    $html.='<option value='.$id.'-'.$v['attr_key'].' attrprice='.$v['attr_price'].' goodssn='.$v['goods_attr_sn'].'>'.$attr.'</option>';
                }
                $html.='</select>';
                $info['shop_price']=$attr_key[0]['attr_price'];
                $info['goods_sn']=$attr_key[0]['goods_attr_sn'];
                $info['attr_keys']=$html;
            }else{
                $info['attr_keys']='';
            }
            $info['unit_name']=idtoname($info['unit_id'],'GoodsUnit','name','id',false);
            $return['status'] = 1;
            $return['info'] = $info;
        }else{
            $return['status'] = 0;
            $return['info'] = '数据获取错误';
        }

        $this->ajaxReturn($return);
    }
}
?>