<?php
namespace Smi\Controller;
use Think\Controller;
header("Content-Type:text/html;CharSet=UTF-8");
class StoreOrderController extends BaseController
{
	/**
	 * @description 商家订单Controller
	 * @date        2017-06-20
	 * @author      [yuanlin] 
	 */
	
	//商家订单列表
	public function storeOrderList()
	{
        if($_GET){
            $text   = I("text"); //订单编号、收货人、收货人电话 
            $store  = I("store");//商家
            $status = I("status"); //订单状态
            $start_time = I("start_time"); //开始时间
            $end_time   = I("end_time"); //结束时间
            if($text){
                $where['_string'] = '(order_sn like "%'.$text.'%") OR (name like "%'.$text.'%") OR (mobile like "%'.$text.'%")';
                $this->assign("text",$text);
            }
            if($store){
                $where['store_id'] = $store;
                $this->assign("store",$store);
            }
            if($status){
                $where['status'] = $status;
                $this->assign("status",$status);
            }
            if($start_time){
                $start_time = $start_time." 00:00:00";
                $where['create_time'] = array("egt",strtotime($start_time));
                $this->assign("start_time",I("start_time"));
            }
            if($end_time){
                $end_time   = $end_time." 23:59:59";
                $where['create_time'] = array("elt",strtotime($end_time));
                $this->assign("end_time",I("end_time"));
            }
            if($start_time && $end_time){                
                $start_time = I('start_time')." 00:00:00";               
                $end_time   = I('end_time')." 23:59:59";                
                $where['create_time'] = array(array("egt",strtotime($start_time)),array("elt",strtotime($end_time)));
                $this->assign("start_time",I("start_time"));
                $this->assign("end_time",I("end_time"));
            }
        }else{
            $where = $where;
        }
        $Model = M("order_city");
        $count = $Model->where($where)->count();
        $Page = new \Think\Page($count,10);//确定每页记录()
        //分页类传入条件参数
        foreach($where as $key=>$val) {
            $Page->parameter[$key] = urlencode($val);
        }
        $show = $Page->show();// 分页显示输出
        $list = $Model->where($where)->order("id desc")->limit($Page->firstRow . ',' . $Page->listRows)->select();
        //循环订单商品
        foreach ($list as $keyo => &$valueo) {
            $goods = M("order_city_good")->where(array("order_id"=>$valueo['id']))->select();
            foreach ($goods as $keyg => &$valueg) {
                $goods_name = M("stores_goods")->where(array("id"=>$valueg['good_id']))->find();
                $valueg['goods_name'] = $goods_name['goods_name'];
                $valueg['goods_price']= $goods_name['goods_price'];
            }
            $valueo['goods'] = $goods;
        }
        //订单商品过多显示处理
        foreach ($list as $k => &$v) {
            $goods = "";
            $count = "";
            foreach ($v['goods'] as $kg => $vg) {
                if($kg < 3){
                    $s  = $kg + 1;
                    $goods .= $s.". ".$vg['goods_name'].", ".$vg['goods_price']."x".$vg['num']."<br />";
                }else{
                    $goods .= ".  ......";
                }
            }
            $v['goods'] = $goods;
        }
        //商家名称，所属小区
        foreach ($list as $ks => &$vs) {
        	$store = $this->isVillage($vs['store_id']);
        	$vs['store_name']   = $store['name'];
        	$vs['store_village']= $store['village'];
        }
        $stores = M("stores")->order("id")->select();//所有商家
        $this->assign("stores",$stores);
        $this->assign('page', $show);// 赋值分页输出
        $this->assign("list", $list);//定义变量并显示模板
        $this->display();
	}

	//商家订单详情
    public function storeOrderDetail(){
        $id = I("id");
        if(empty($id)){
            alertMsg("订单id接收出错！");die;
        }
        $detail  = M("order_city")->where("id=".$id)->select();
        $goods   = M("order_city_good")->where(array("order_id" => $detail[0]['id']))->select();
        $nickname= M("users_oa")->where(array("openid"=>$detail[0]['openid']))->find();
        foreach($goods as $k => &$v){
            $good = M("stores_goods")->where("id=".$v['good_id'])->find();
            $goodss .= ($k+1).". ".$good['goods_name'].", ".$good['goods_price']."x".$v['num']."<br />";
        }
        foreach ($detail as $key => &$val) {
            $val['expect_time'] = date("Y-m-d H:i:s",$val['expect_time']);
            $val['create_time'] = date("Y-m-d H:i:s",$val['create_time']);
            if($val['finish_time']){
                $val['finish_time'] = date("Y-m-d H:i:s",$val['finish_time']);    
            }
            $val['goods']    = $goodss;
            $val['nickname'] = $nickname['nickname'];
        } 
        //商家名称,所属小区
        $store = $this->isVillage($detail[0]['store_id']);
        $this->assign("detail",$detail[0]);  
        $this->assign("stores",$store['name']);
        $this->assign("village",$store['village']);
        $this->display();
    }
    //所属小区，商家名称
    public function isVillage($store_id){
    	$stores = M("stores")->where(array("id"=>$store_id))->find();
        $region = M("regionCounty")
            ->join("county LEFT JOIN `am_region_city` city ON county.`city_id`=city.`id`")
            ->join("LEFT JOIN `am_region_province` p ON city.`province_id`=p.`id`")
            ->join("LEFT JOIN `am_region_village` v ON p.`id`=v.`county_id`")
            ->where("county.`id`={$stores['county_id']}")
            ->field("p.`name` AS `province`,city.`name` AS `city`,county.`name` AS `county`,v.`name` AS `village`")
            ->find();
        $store['village']= $region['village']; //所属小区
        $store['name']   = $stores['name']; //商家名称   
        return $store;    
    }
    /**
     * [getOrderStatus 获取订单状态]
     * @date        2017-06-20
     * @param       [type]int    $status [订单状态]
     */
    public function getOrderStatus($status){
    	switch ($status) {
    		case '1':
    			$result = '待确认';
    			break;
    		case '2':
    			$result = '待送货';
    			break;
    		case '3':
    			$result = '已完成';
    			break;
    		case '-1':
    			$result = '已取消';
    			break;
    		case '-2':
    			$result = '已拒绝';
    			break;			
    		default:
    			$result = '未知';
    			break;
    	}
    	return $result;
    }
    /**
     * [storeExportToexcel 导出商家订单]
     * @date        2017-06-20
     */
    public function storeExportToexcel(){
        if($_GET){
            $text   = I("text"); //订单编号、收货人、收货人电话 
            $store  = I("store"); //商家
            $status = I("status"); //订单状态
            $start_time = I("start_time"); //开始时间
            $end_time   = I("end_time"); //结束时间
            if($store){
            	$where['store'] = $store;
            	$storeName = M("stores")->where(array("id"=>$store))->find();
            	$sheettile .= $storeName['name'];
            }
            if($text){
                $where['_string'] = '(order_sn like "%'.$text.'%") OR (name like "%'.$text.'%") OR (mobile like "%'.$text.'%")';
                $sheettile .= $text;
            }                    
            if($status){
                $where['status'] = $status;         
                $sheettile .= $this->getOrderStatus($status);
            }
            if($start_time){
                $start_time = $start_time." 00:00:00";
                $where['create_time'] = array("egt",strtotime($start_time));
                $this->assign("start_time",I("start_time"));
            }
            if($end_time){
                $end_time   = $end_time." 23:59:59";
                $where['create_time'] = array("elt",strtotime($end_time));
                $this->assign("end_time",I("end_time"));
            }
            if($start_time && $end_time){                
                $start_time = I('start_time')." 00:00:00";               
                $end_time   = I('end_time')." 23:59:59";                
                $where['create_time'] = array(array("egt",strtotime($start_time)),array("elt",strtotime($end_time)));
                $this->assign("start_time",I("start_time"));
                $this->assign("end_time",I("end_time"));
            }
            if(!$sheettile){
                $sheettile .= "所有商家";
            }
        }
        $netlist = M('order_city')->where($where)->order("id")->select();
        foreach ($netlist as $k => &$val) {
        	//所属小区，商家名称，用户微信昵称
        	$nameVillage = $this->isVillage($val['store_id']);
        	$val['village']  = $nameVillage['village'];
         	$val['store_id'] = $nameVillage['name'];
        	$val['openid']   = M("users")->getFieldByOpenid($val['openid'],'nickname');    	
        	//商品名称，数量，单价
            $goods_id = M("order_city_good")->where(array("order_id"=>$val['id']))->select();
            foreach ($goods_id as $keyg => $valueg) {
                $goods = M("stores_goods")->where(array("id"=>$valueg['good_id']))->field("goods_name,goods_price")->find();
                $goods_name .= $goods['goods_price']."x".$valueg['num'].",".$goods['goods_name']."\n";
            }
            $val['goods_name']  = rtrim($goods_name,"\n");
            //预计送达时间，下单时间，完成时间
            $val['expect_time'] = date("Y-m-d H:i:s",$val['expect_time']);
            $val['create_time'] = date("Y-m-d H:i:s",$val['create_time']);
            if($val['finish_time'] > 0){
                $val['finish_time'] = date("Y-m-d H:i:s",$val['finish_time']);    
            }
            //订单状态
            $val['status'] = $this->getOrderStatus($val['status']);

            $goods_name  = "";
        }
        Vendor("PHPExcel/Classes/PHPExcel");
        $objPHPExcel = new \PHPExcel();
        $objSheet = $objPHPExcel->getActiveSheet();//获取当前sheet
        $objSheet->setTitle($sheettile.'订单');//设置当前sheet的标题
        $objSheet
            ->setCellValue("A1", "订单ID")
            ->setCellValue("B1", "所属小区")
            ->setCellValue("C1", "商家名称")
            ->setCellValue("D1", "订单编号")
            ->setCellValue("E1", "订单商品")
            ->setCellValue("F1", "订单总价")
            ->setCellValue("G1", "收货人")
            ->setCellValue("H1", "微信昵称")
            ->setCellValue("I1", "联系方式")
            ->setCellValue("J1", "收货地址")
            ->setCellValue("K1", "小程序表单ID")
            ->setCellValue("L1", "订单状态")
            ->setCellValue("M1", "取消原因")
            ->setCellValue("N1", "预计到达时间")
            ->setCellValue("O1", "下单时间")
            ->setCellValue("P1", "完成时间");    
            //填充第二行的数据
            $i = 2;
            foreach ($netlist as $key=>$value) {
                $objPHPExcel->getActiveSheet()->getStyle('E'.$value['goods_num'])->getAlignment()->setWrapText(true);
                $objSheet
                    ->setCellValue("A".$i, $value['id'])
                    ->setCellValue("B".$i, $value['village'])
                    ->setCellValue("C".$i, $value['store_id'])
                    ->setCellValue("D".$i, $value['order_sn'])
                    ->setCellValue("E".$i, $value['goods_name'])
                    ->setCellValue("F".$i, "\t".$value['total_fee']."\t")
                    ->setCellValue("G".$i, $value['name'])
                    ->setCellValue("H".$i, $value['openid'])
                    ->setCellValue("I".$i, $value['mobile'])
                    ->setCellValue("J".$i, $value['address'])
                    ->setCellValue("K".$i, $value['form_id'])
                    ->setCellValue("L".$i, $value['status'])
                    ->setCellValue("M".$i, $value['reason'])
                    ->setCellValue("N".$i, $value['expect_time'])
                    ->setCellValue("O".$i, $value['create_time'])
                    ->setCellValue("P".$i, $value['finish_time']);                    
                $i++;
            }
            //设置宽度自适应
            $setAuto = array('A','B','C','D','E','F','G','H','I','J', 'K','L','M','N','O','P');
            foreach ($setAuto as $key => $value) {
                $objPHPExcel->getActiveSheet()->getColumnDimension($value)->setAutoSize(true);
            }
            //设置标题文字加粗、居中对齐 
            $setBold = array('A1','B1','C1','D1','E1','F1','G1','H1','I1','J1', 'K1', 'L1','M1','N1','O1','P1');
            foreach ($setBold as $value) {              
                $objPHPExcel->getActiveSheet()->getStyle($value)->getFont()->setBold(true);//设置文字加粗
                $objPHPExcel->getActiveSheet()->getStyle($value)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::VERTICAL_CENTER); //设置文字居中对齐
            }
            //设置内容居中
            $len = count($netlist);
            for ($i=0; $i < $len; $i++) { 
                $num=$i+2;
                foreach ($setAuto as $key => $val) {
                    if($val != 'E'){
                        $txt = $val.$num;
                        $objPHPExcel->setActiveSheetIndex(0)->getStyle($txt)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);  
                        $objPHPExcel->setActiveSheetIndex(0)->getStyle($txt)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER); 
                    }      
                }
            }
        //设置浏览器的下载
        header("Content-type:application/vnd.ms-excel;charset=UTF-8");
        header('Content-Disposition: attachment;filename="'.$sheettile.'订单'.date("Ymd").'.xls"');
        header('Cache-Control: max-age=0');  
        //保存和输出至浏览器
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
    }
}