<?php
namespace Smi\Controller;

use Think\Controller;

header("Content-Type:text/html;CharSet=UTF-8");
class StorageController extends BaseController
{
    //protected $type;
    /**
     * 商品库存
     */
    public function storageList()
    {
        auth_check("storage_read");
        $where = "s.`village_id`=0 AND g.`deleted`=-1";
        $order = "g.`sort` asc,g.`id` desc";
        $l = 10;//确定每页记录数
        // if ($_GET['search']) {
        //     $search = I("search");
        //     $where .= " AND `nickname` LIKE '%{$search}%'";
        //     $this->assign("search", $search);
        // }
        $count = M("goodsStorage")
            ->join("s INNER JOIN `am_goods` g ON s.`good_id`=g.`id`")
            ->where($where)
            ->count();// 查询满足要求的总记录数
        // 实例化分页类 传入总记录数和每页显示的记录数($l)
        $Page = new \Think\Page($count, $l);
        $show = $Page->show();// 分页显示输出
        $list = M("goodsStorage")
            ->join("s INNER JOIN `am_goods` g ON s.`good_id`=g.`id`")
            ->field("s.*,g.`goods_name`")
            ->order($order)
            ->where($where)
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->select();
        $this->assign('page', $show);// 赋值分页输出
        // 定义变量并显示模板
        $this->assign("list", $list);
        $this->display("storageList");die;
    }

    /**
     * 增加库存
     */
    public function storagePlus()
    {
        auth_check("storage_opt");
        $id = $_POST['id'];    // 商品库存表ID
        $num = I("num");
        // 总仓库库存 增加
        $result = M("goodsStorage")->where("`id`={$id}")->lock()->setInc("storage", $num);
        if ($result) {
            $row = M("goodsStorage")->where("`id`={$id}")->find();
            $good_id = $row['good_id'];
            // 总仓库入库记录
            $addData = array(
                "choice" => 2,
                "type" => 4,
                "order_id" => 0,
                "dinner_id" => 0,
                "good_id" => $good_id,
                "change_num" => $num,
                "create_time" => $_SERVER['REQUEST_TIME']
            );
            M("storageTotal")->add($addData);
        }
        $this->redirect("storageList");die;
    }

    /**
     * 调货
     */
    public function storageTransport()
    {
        auth_check("storage_opt");
        if (IS_POST) {
            $good_id = $_GET['good_id'];    // 商品ID
            $village_id = $_POST['village_id'];    // 村ID
            $deliveryman = $_POST['deliveryman'];    // 仓库送货员ID
            $num = I('num');    // 转移数量
            // 总仓库减存
            M("goodsStorage")->where("`village_id`=0 AND `good_id`={$good_id}")->lock()->setDec("storage", $num);
            // 生成 总仓库出库记录
            $addData = array(
                "choice" => 1,
                "type" => 2,
                "order_id" => 0,
                "dinner_id" => 0,
                "good_id" => $good_id,
                "change_num" => $num,
                "create_time" => $_SERVER['REQUEST_TIME']
            );
            M("storageTotal")->add($addData);
            // 分仓库增存
            M("goodsStorage")->where("`village_id`={$village_id} AND `good_id`={$good_id}")->lock()->setInc("storage", $num);
            // 生成 分仓库入库记录
            $addData = array(
                "choice" => 2,
                "type" => 2,
                "order_id" => 0,
                "dinner_id" => 0,
                "good_id" => $good_id,
                "change_num" => $num,
                "create_time" => $_SERVER['REQUEST_TIME']
            );
            M("storageVillage")->add($addData);
            // 生成调货记录
            $addData = array(
                "order_id" => 0,
                "good_id" => $good_id,
                "supply_sn" => "BH0{$good_id}" . date("YmdHis", $_SERVER['REQUEST_TIME']),
                "num" => $num,
                "village_id" => $village_id,
                "deliveryman" => $deliveryman,
                "create_time" => $_SERVER['REQUEST_TIME']
            );
            M("storageTransport")->add($addData);
            $this->redirect("storageList");die;
        }
        // 获取 省->市->县->村 列表
        $province = M("regionProvince")->select();
        $this->assign("province", $province);
        // 仓库送货员
        $dpc = M("storageDpc")->select();
        $this->assign("dpc", $dpc);
        $this->assign("good_id", $_GET['good_id']);
        $this->display("storageTransport");die;
    }

    /**
     * 修正库存
     */
    public function setStorage()
    {
        auth_check("storage_opt");
        $id = $_POST['id'];
        $storage = I("storage");
        $result = M("goodsStorage")->where("`id`={$id}")->setField("storage", $storage);
        if ($result) {
            alertMsg("操作成功", U("storageList"));
        } else {
            $this->redirect("storageList");die;
        }
    }

    /**
     * 通过省ID获取市列表 ajax
     */
    public function returnCity()
    {
        $province_id = $_POST['province_id'];
        $cityList = M("regionCity")->where("`province_id`={$province_id}")->select();
        if (!$cityList) {
            $row = M("regionProvince")->where("`id`={$province_id}")->find();
            $province = $row['name'];
            $data = array(
                "status" => -1,
                "msg" => "“{$province}”没有城市"
            );
        } else {
            $data = array(
                "status" => 1,
                "result" => $cityList
            );
        }
        $this->ajaxReturn($data);die;
    }

    /**
     * 通过市ID获取县/区列表 ajax
     */
    public function returnCounty()
    {
        $city_id = $_POST['city_id'];
        $countyList = M("regionCounty")->where("`city_id`={$city_id}")->select();
        if (!$countyList) {
            $row = M("regionCity")->where("`id`={$city_id}")->find();
            $city = $row['name'];
            $data = array(
                "status" => -1,
                "msg" => "“{$city}”没有县/区"
            );
        } else {
            $data = array(
                "status" => 1,
                "result" => $countyList
            );
        }
        $this->ajaxReturn($data);die;
    }

    /**
     * 通过县/区ID获取村列表 ajax
     */
    public function returnVillage()
    {
        $county_id = $_POST['county_id'];
        $villageList = M("regionVillage")->where("`county_id`={$county_id} AND `type`=1")->select();
        if (!$villageList) {
            $row = M("regionCounty")->where("`id`={$county_id}")->find();
            $county = $row['name'];
            $data = array(
                "status" => -1,
                "msg" => "“{$county}”没有村"
            );
        } else {
            $data = array(
                "status" => 1,
                "result" => $villageList
            );
        }
        $this->ajaxReturn($data);die;
    }

    /**
     * 出入库记录
     */
    public function changeList()
    {
        auth_check("storage_read");
        $where = "1";
        $order = "s.`id` DESC";
        $l = 10;//确定每页记录数
        // if ($_GET['search']) {
        //     $search = I("search");
        //     $where .= " AND `nickname` LIKE '%{$search}%'";
        //     $this->assign("search", $search);
        // }
        $count = M("storageTotal")
            ->join("s LEFT JOIN `am_goods` g ON s.`good_id`=g.`id`")
            ->join("LEFT JOIN `am_order` o ON s.`order_id`=o.`id`")
            ->join("LEFT JOIN `am_dinner` d ON s.`dinner_id`=d.`id`")
            ->where($where)
            ->count();// 查询满足要求的总记录数
        // 实例化分页类 传入总记录数和每页显示的记录数($l)
        $Page = new \Think\Page($count, $l);
        $show = $Page->show();// 分页显示输出
        $list = M("storageTotal")
            ->join("s LEFT JOIN `am_goods` g ON s.`good_id`=g.`id`")
            ->join("LEFT JOIN `am_order` o ON s.`order_id`=o.`id`")
            ->join("LEFT JOIN `am_dinner` d ON s.`dinner_id`=d.`id`")
            ->field("s.*,g.`goods_name`,d.`dinner_sn`,o.`order_sn`")
            ->order($order)
            ->where($where)
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->select();
        $this->assign('page', $show);// 赋值分页输出
        // 定义变量并显示模板
        $this->assign("list", $list);
        $this->display("changeList");die;
    }

    /**
     * 仓库送货员 列表
     */
    public function homeDispatchers()
    {
        auth_check("storage_read");
        $l = 10;//确定每页记录数
        $where = "1";
        // $search = I("search");
        // if ($search) {
        //     $where .= " AND (o.`ordersn` LIKE '%$search%' OR o.`name` LIKE '%$search%' OR o.`tel` LIKE '%$search%')";
        //     $this->assign("search", $search);
        // }
        $order = "`id` DESC";
        $count = M("storageDpc") 
            ->where($where)
            ->count();// 查询满足要求的总记录数
        // 实例化分页类 传入总记录数和每页显示的记录数($l)
        $Page = new \Think\Page($count, $l);
        $show = $Page->show();// 分页显示输出
        $list = M("storageDpc") 
            ->where($where)
            ->order($order)
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->select();
        $this->assign('page', $show);// 赋值分页输出
        // 定义变量并显示模板
        $this->assign("list", $list);
        $this->display("homeDispatchers");die;
    }

    /**
     * 仓库送货员 添加
     */
    public function dpcAdd()
    {
        auth_check("storage_opt");
        if (IS_POST) {
            $name = I("name");
            $mobile = I("mobile");
            if (!$name) alertMsg("请输入姓名");
            if (!$mobile) alertMsg("请输入手机号码");
            $pattern = "/^1[3|4|5|7|8][0-9]{9}$/";
            $matchMobile = preg_match($pattern, $mobile);  //匹配正确返回 1,错误返回 0
            if ($matchMobile == 0) alertMsg("请输入正确的手机号码");
            $data = array(
                "name" => $name,
                "mobile" => $mobile
            );
            M("storageDpc")->add($data);
            $this->redirect("homeDispatchers");die;
        } else {
            $this->display("dpcAdd");die;
        }
    }

    /**
     * 仓库送货员 修改
     */
    public function dpcEdit()
    {
        auth_check("storage_opt");
        if (IS_POST) {
            $id = $_POST['id'];
            $name = I("name");
            $mobile = I("mobile");
            if (!$name) alertMsg("请输入姓名");
            if (!$mobile) alertMsg("请输入手机号码");
            $pattern = "/^1[3|4|5|7|8][0-9]{9}$/";
            $matchMobile = preg_match($pattern, $mobile);  //匹配正确返回 1,错误返回 0
            if ($matchMobile == 0) alertMsg("请输入正确的手机号码");
            $data = array(
                "name" => $name,
                "mobile" => $mobile
            );
            M("storageDpc")->where("`id`={$id}")->save($data);
            $this->redirect("homeDispatchers");die;
        } else {
            $id = $_GET['id'];
            $info = M("storageDpc")->where("`id`={$id}")->find();
            $this->assign("info", $info);
            $this->display("dpcAdd");die;
        }
    }

    /**
     * 仓库送货员 删除
     */
    public function dpcDel()
    {
        auth_check("storage_opt");
        $id = $_GET['id'];
        M("storageDpc")->where("`id`={$id}")->delete();
        $this->redirect("homeDispatchers");die;
    }

    /**
     * 破损管理
     */
  
    
     public function goodsDamage()
    {       
        auth_check("storage_read");
        $type=I('get.type');
        if($type){
            $where['a.type']=$type;
        }
        $num=10;
        $Model=M("");        
         if($_GET['search']){
           $search=I('search');                      
           $where['a.goods_name|b.name|a.create_time']=array('like',"%{$search}%"); 
        }  
        $count=$Model->table('am_reimburse')->alias('a')
                    ->join("left join am_region_village b ON  a.village_id=b.id")
                    ->where($where)->count();
        $Page = new \Think\Page($count, $num);
        $show = $Page->show();// 分页显示输出
        $data=$Model->table('am_reimburse')->alias('a')
                    ->join("left join am_region_village b ON  a.village_id=b.id")
                    ->limit($Page->firstRow.','.$Page->listRows)
                    ->where($where)->order('a.id desc')
                    ->field('a.*,b.name')->select();        
        //dump($data);die;
        $this->assign('data',$data);
        $this->assign('page',$show);
        $this->display();    
    }

  
    /**
     * 修改状态
     */
    public function doVerify()
    {
       auth_check("storage_opt"); 
       $id=I('get.id');
        $p=I('get.p');
       $data['status']=2;
       $res=M('reimburse')->where("`id`={$id}")->save($data);
       if($res){                      
                alertMsg('状态修改成功',U('goodsDamage'));         
       } else {                      
                 alertMsg('修改失败',U('goodsDamage'));           
       }
    }
    /**
     * 修改破损审核状态
     */
    public function damage_details()
    {
        auth_check("storage_read");
        $id=I('get.id');

        $Model=M("");
        $data=$Model->table('am_reimburse')->alias('a')
        ->where(array('a.id'=>$id))       
        ->join("left join am_region_village b ON  a.village_id=b.id")
        ->field('a.*,b.name')->find();
        //dump($data);die;
        $this->assign('data',$data);
        $this->display();
    }
    
    public function del_damages()
    {
        $id=I('get.id');
        $res=M('reimburse')->where("`id`={$id}")->delete();
        if($res){
            alertMsg('删除成功',U('goodsDamage'));    
        } else {
            alertMsg('删除失败');
        }
    }
    /**
    *后台添加报损
     */
    public function back_damage()
    {
    	auth_check("storage_opt");
    	//获取省
    	$province=M("region_province")->select();
    	$type=I('get.type');
    	if(IS_POST){
    		$imges=$this->uploads();
    		$lent=count($imges);
    		$village_id=I('village_id');
    		$sn=$village_id.time();
    		if($lent>4){
    			alertMsg('图片不能超过四张',U('back_damage')); die;
    		} else {
    			$data=array(
    				'sn'=>$sn,
    			'village_id'=>$village_id,
    			'goods_name'=>I('goods_name'),
    			'num'=>I('num'),
    			'type'=>2,
    			'thumb_1'=>$imges[0],
    			'thumb_2'=>$imges[1],
    			'thumb_3'=>$imges[2],
    			'thumb_4'=>$imges[3],
    			'create_time'=>date("Y-m-d",time())
    			);
    			$res=M('reimburse')->add($data);
    			if($res){
    				alertMsg("添加成功",U('back_damage'));
    			} else {
    				alertMsg("添加失败");
    			}
    		}
    		
    	}
    	
    	$this->assign('province',$province); 
    	$this->display();

    }
    public function uploads()
    {
    	if($FILES['img']['error']!=4){  	
            $upload = new \Think\Upload();
	    	$upload->maxSize = 3145728;
	    	$upload->exts = array('jpg','gif','png','jpeg');
	    	$upload->rootPath = './Uploads/'; // 上传附件根目录
	    	$upload->savePath = 'goods_img/'; //设置附件上传子目录
	    	//上传文件
	    	$info = $upload->upload();
	    	
	    		foreach ($info as $key => $val) {
	    			$imgs[]=$val['savepath'].$val['savename'];
	    		}
	    	
	    	
	    	return $imgs;
    	} 
    }
}