<?php
/**
 * 第三方物流
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaogg <xiaogg@sina.cn>
 */
 
namespace Admin\Controller;
class DistributeController extends BaseController{
    public function index(){
		$s_map=$map=array();
        $list = $this->lists('Distribute',$map,'sort,sort');
        $s_map['status']=1;
        $shop_info = M('Shops')->where($s_map)->order('id asc')->limit(1)->field('id,source_id')->find();
        $code=is_distribute();
        foreach($list as $k=>$v){
            if($v['code']=='Dada' && in_array('Dada',$code)){
                $list[$k]['shop_re'] = 1;
            }else{
                $list[$k]['shop_re'] = 0;
            }
        }
        $this->assign('source_id', $shop_info['source_id']);
        $this->assign('shop_id', $shop_info['id']);
        $this->assign('list', $list);
        $this->display();
    }
	public function _before_edit(){
        $id = I('get.id');
        if (empty($id)) $this->error(L('PARAM_ERR'));
    }
    public function select(){
    	$post = I('param.');
        if($post['order_id'])$map['order_id'] = $post['order_id'];
    	if($post['status'])$map['order_status'] = $post['status'];
        if(!empty($post['date_from']))$map['update_time'][]=array('EGT',strtotime($post['date_from']));
        if(!empty($post['date_to']))$map['update_time'][]=array('elt',strtotime($post['date_to'])+24*3600);
    	$wuliu_order_status = array('1'=>'待接单','2'=>'待取货','3'=>'配送中','4'=>'已完成','5'=>'已取消','7'=>'已过期','8'=>'指派单');
        $wuliu_marking = array('Dada'=>'达达','Meituan'=>'美团配送','Local'=>'自有配送');
        if($post['code'])$map['marking'] = $post['code'];
    	$list = $this->lists('TakeawayOrder',$map);
        $i=$all_delivery_money=0;
        foreach ($list as $key => $value) {
            $i++;
            $all_delivery_money+=$value['delivery_money'];
        }
        $count=M('TakeawayOrder')->where($map)->count();
        $delivery_money=M('TakeawayOrder')->where($map)->sum('delivery_money');
        $this->assign($post);
        $this->assign('list',$list);
        $this->assign('order_count',$i);
        $this->assign('all_delivery_money',$all_delivery_money);
        $this->assign('count',$count);
        $this->assign('delivery_money',$delivery_money);
        $this->assign('wuliu_marking',$wuliu_marking);
        $this->assign('wuliu_order_status',$wuliu_order_status);
        $this->display();
    }
    public function content(){
        $id = I('get.id');
        $data = M('TakeawayOrder')->where('id='.$id)->find();
        $save=array();
        if(empty(intval($data['delivery_money'])) && $data['marking']=='Dada'){
            $dis= new \Common\Vendor\Distribute($data['marking']);
            $result=$dis->details_order($data['order_id']);
            $save['delivery_money']=$result['info']['deliveryFee'];
            $save['id']=$data['id'];
            $save['update_time']=NOW_TIME;
            M('TakeawayOrder')->save($save);
            $data['delivery_money']=$save['delivery_money'];
        }        
        $wuliu_order_status = array('1'=>'待接单','2'=>'待取货','3'=>'配送中','4'=>'已完成','5'=>'已取消','7'=>'已过期','8'=>'指派单');
        $this->assign('data',$data);
        $this->assign('wuliu_order_status',$wuliu_order_status);
        $this->display();
    }
    public function dis_edit(){
        $id = I('get.id');
        $map['id'] = $id;
        $data = M('Distribute')->where($map)->field(true)->find();
        $this->assign($data);
        $this->display();
    }
    public function update(){
        $postdata = I('post.');
        $save_data['name'] = $postdata['name'];
        $save_data['code'] = $postdata['code'];
        $save_data['img'] = $postdata['img'];
        $save_data['app_key'] = $postdata['app_key'];
        $save_data['app_secret'] = $postdata['app_secret'];
        $save_data['param1'] = $postdata['param1'];
        $save_data['param2'] = $postdata['param2'];
        $save_data['content'] = $postdata['content'];
        $save_data['status'] = $postdata['status'];
        $save_data['sort'] = $postdata['sort'];
        $map['id'] = $postdata['id'];
        $save = M('Distribute')->where($map)->save($save_data);
        $url = U('Admin/distribute/index');
        if ($save) {
            S('tpl_mobile_default0',null);
            S('tpl_mobile_default1',null);
            S('tpl_mobile_default2',null);
            $this->success('修改成功',$url);
        } else {
            $this->error('修改失败',$url);
        }
    }
    public function shops(){
        $postdata = I('post.');
        $keyword = $postdata['keyword'];
        $map = array();
        if ($keyword) {
            $whereor['id'] = array('like', '%' . $keyword . '%');
            $whereor['name'] = array('like', '%' . $keyword . '%');
            $whereor['_logic'] = 'or';
            $map['_complex'] = $whereor;
        }

        $list = $this->lists('Shops', $map);
        $this->assign('list', $list);
        $this->assign($postdata);
        $this->display();
    }
    public function shop_re(){
        $id =intval(I('request.id'));
        if(!$id){
            $this->error('无有效的仓库',U('Distribute/index'));
            return;
        }
        if(C("DIS_TRIBUTE") != 1){
            $this->error('物流功能未开通',U('Distribute/index'));
            return;
        }
        if(!$id){
            $this->error('无仓库可注册，请先添加仓库',U('Distribute/index'));
            return;
        }
        $map['id'] = $id;
        $shop = M('Shops')->where($map)->field(true)->find();
        $city = idtoname($shop['city_id'],'Area','name');
        $this->assign('city',$city);
        $this->assign('shop',$shop);
        $post = I('post.');
        if($post){
            $post['distribute'] = "Dada";
            $result = D('Common/Distribute')->merchant_add($post);
            if($result['status'] == 1){
                $this->success($result['msg'],U('Distribute/index'));return;
            }else{
                $this->error('操作失败:'.$result["msg"],U('Distribute/shop_re'));return;
            }
        }
        $this->display();
    }
    /**
 * 添加第三方仓库
 */
    public function shop_add(){
        if(C("DIS_TRIBUTE") != 1){
            $this->error('物流功能未开通',U('Distribute/shops'));return;
        }
        $id = I('get.id');
        if(I('get.code')){
            $this->assign('wuliu',I('get.code'));
        }
        $shops_location = M('Shops')->where(array('id'=>$id))->find();
        $this->assign('shop',$shops_location);
        $this->display();
    }
    /**
     * 执行添加第三方仓库
     */
    public function shop_insert(){
        if(C("DIS_TRIBUTE") != 1){
            $this->error('物流功能未开通',U('Distribute/shops'));return;
        }
        $post = I('post.');
        $shop_id=$post['id'];
        $source_info = M('Shops')->where(array('id'=>$shop_id))->field("origin_id,logistics")->find();
        if($post){
            
            if($post['code'] || $post['bindtype']){//单个绑定
                $codefile='logistics';
                if($post['code']=='Dada' && in_array("Dada",is_distribute())){
                    $map=array();
                    $map['status']=1;
                    $map['code']='Dada';
                    $source_id=M('Distribute')->where($map)->getField('source_id');
                    if(empty($source_id)){
                        $this->error('请先注册成为商户',U('ShopsDelivery/index'));return;
                    }
                    $codefile='origin_id';
                }
                if($post['bindtype']==1){//手动绑定
                    $data=array();
                    if(empty($post['shops_code'])){
                        $this->error('请先填写仓库编号');return;
                    }
                    $data[$codefile]=$post['shops_code'];
                    $up=M('Shops')->where(array('id'=>$shop_id))->save($data);
                    if($up!==false){
                        $result['status']=1;
                    }else{
                        $result['status']=0;$result['msg']='没有任何变化';
                    }
                }else{//自动绑定
                    if($source_info[$codefile]){
                        $result = D('Common/Distribute')->shop_update($post);
                    }else{
                        $result = D('Common/Distribute')->shop_add($post);
                    }
                }                
            }else{//批量绑定
                $wuliu = M('Distribute')->field('code')->where(array('status'=>1))->select();
                foreach($wuliu as $k=>$v){
                    $post['code'] = $v['code'];
                    if($post['code']=='Dada')$codefile='origin_id'; else $codefile='logistics';
                    if($source_info[$codefile]){
                        $result = D('Common/Distribute')->shop_update($post);
                    }else{
                        $result = D('Common/Distribute')->shop_add($post);
                    }
                    if($result['status'] == 0)break;
                }
            }
            if($result['status']){
                $this->success("操作成功",U('ShopsDelivery/index'));return;
            }else{
                $this->error('操作失败:'.$result["msg"],U('ShopsDelivery/index'));return;
            }
        }
    }
    public function do_import(){
        $filename = $_FILES['file']['tmp_name'];
        if (empty ($filename)) {
            $this->error('请选择要导入的CSV文件！');exit;
        }
        if(!str_exists($_FILES['file']['name'],'.csv')){
            $this->error('导入的文件格式不正确！');exit;
        }
        $handle = fopen($filename, 'r');
        $result = $this->input_csv($handle); //解析csv
        $len_result = count($result);
        if($len_result==0){
            $this->error('没有任何数据！');exit;
        }    

        $shop_map=array('status'=>1);
        $logistics_list = M('Shops')->where($shop_map)->getField('logistics',true);

        for ($i = 1; $i < $len_result; $i++) { //循环获取各字段值
            if(!in_array($result[$i][10], $logistics_list))continue;
            $data_values = $map=array();
            $client_id=explode(',', $result[$i][1]);   
            $map['client_id']=$client_id[0];
            $map['marking']='Meituan';
            $count=M('TakeawayOrder')->where($map)->count();
            if($count)$data_values['delivery_money'] = $result[$i][33];
            if($data_values)$query=M('TakeawayOrder')->where($map)->save($data_values);
        }
        fclose($handle); //关闭指针
        if($query){
            $this->success('导入成功！');
        }else{
            $this->error('列中还有没有匹配的包裹ID！');
        }
    }
    public function input_csv($handle) {
        $out = array ();
        $n = 0;
        while ($data = fgetcsv($handle, 10000)) {
            $num = count($data);
            for ($i = 0; $i < $num; $i++) {
                $out[$n][$i] = $data[$i];
            }
            $n++;
        }
        return $out;
    }
}