<?php
namespace MpSmi\Controller;

use Think\Controller;

header("Content-Type:text/html;CharSet=UTF-8");
class ShopController extends BaseController
{
    public function shopList()
    {   
        if($_GET){
            $where .= "G.`store_id`=" . session("store_id") . " AND G.`deleted`=-1";
            $name = I("name");
            $cate = I("cate");
            if($name){
                $where .= " AND G.`goods_name` LIKE '%$name%'";
                $this->assign("name",$name);
            }
            if($cate){
                $where .= " AND C.`id`= {$cate}";
                $this->assign("cate",$cate);
            }
        }else{
            $where = "G.`store_id`=" . session("store_id") . " AND G.`deleted`=-1";
        }
        $l = 10;
        $Model = M("stores_goods");
        $count = $Model->join('G LEFT JOIN am_stores_goods_categories C ON C.id = G.pcate')->where($where)->order("G.id desc")->count();
        $Page = new \Think\Page($count, $l);
        $show = $Page->show();// 分页显示输出
        $list = $Model
            ->join('G LEFT JOIN am_stores_goods_categories C ON C.id = G.pcate')
            ->where($where)
            ->order("G.sort asc,G.id desc")
            ->field("G.*,C.name as cate_name")
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->select();
        // if ($count/$l > 1) {
        //    $this->assign('page', $show);// 赋值分页输出
        // }
        //商家商品分类
        $categories = M("stores_goods_categories")->where(array("store_id"=>session('store_id')))->select();
        //定义变量并显示模板
        $this->assign("categories",$categories);
        $this->assign('page', $show);// 赋值分页输出
        $this->assign("list", $list);
        $this->display("index");die;
    }
    
    /*商品删除*/
    public function shopDel()
    {
        if (!$_GET['id']) {
            $this->error("获取商品ID失败，请重新试一下！");die;
        } else {
            M("storesGoods")->where("id = {$_GET['id']}")->setField("deleted", 1);
            /*$row = M('storesGoods')->where("id = {$_GET['id']}")->find();
            $thumbDel = $row['thumb'];
            $carouselDel = unserialize($row['carousel']);
            $result = M('storesGoods')->delete($_GET['id']);
            if ($result) {
                unlink("./Uploads/{$thumbDel}");
                foreach ($carouselDel as $key => $value) {
                    unlink("./Uploads/{$value}");
                }
            }*/
            alertMsg("删除成功", U('Shop/shopList',array('p'=>I('p'))));
        }
    }

    /*商品添加*/
    public function shop_add()
    {
        if (IS_POST) {
            $data = array(
                'store_id' => session("store_id"),
                'sort' => I('sort'),
                'goods_name' => I('goods_name'),
                'pcate' => $_POST['pcate'],
                'goods_price' => I('goods_price'),
                'parameter' => I('parameter'),
                'intro' => I('intro'),
                'des' => I("des"),
                'is_sale' => $_POST['is_sale'],
                'is_hot' => $_POST['is_hot'],
                'thumb_name' => $_POST['thumb_name'],
            );
            //dump($data);die;
            /*$parameter1 = I("parameter1");
            $parameter2 = I("parameter2");
            $array = array();    
            for ($i=0,$len=count($parameter1);$i<$len;$i++) {
                if ($parameter1[$i]) {
                    $array[] = array(
                        "name" => $parameter1[$i],
                        "content" => $parameter2[$i]
                    );
                }
            }*/
            $upload = new \Think\Upload();// 实例化上传类
            // $upload->maxSize = 3145728 ;// 设置附件上传大小
            // 设置附件上传类型
            $upload->exts = array('jpg', 'gif', 'png', 'jpeg');
            $upload->rootPath = './Uploads/'; // 设置附件上传根目录 
            $upload->savePath = 'goods_img/'; // 设置附件上传目录
            $upload->autoSub = true; //要子文件夹
            // 上传文件
            $info = $upload->upload();
            // 轮播图
            /*$carouselArray = array();
            foreach ($info as $k => $v) {
                if (substr($k, 0, 8) == "carousel") {
                    if ($_FILES[$k]['error'] != 4) {
                        $carouselArray[] = $v["savepath"] . $v["savename"];
                    }
                }
            }
            if ($carouselArray[0]) {
                $data['carousel'] = serialize($carouselArray);
                if ($_POST['id']) {
                    $carouselDel = M("storesGoods")->where("`id`={$_POST['id']}")->getField("carousel");
                    $carouselDel = unserialize($carouselDel);
                } 
            }*/
            // 缩略图
            if ($_FILES['thumb']['error'] != 4) {
                if(!$info) {
                    // 上传错误提示错误信息
                    $this->error($upload->getError());die;
                }else{
                    // 上传成功 获取上传文件信息
                    $pic = $info['thumb']["savepath"] . $info['thumb']["savename"];
                    $data['thumb'] = $pic; // 修改数据对象 
                    if ($_POST['id']) {
                        $thumbDel = M("storesGoods")->where("`id`={$_POST['id']}")->getField("thumb");
                    } 
                }
            } else {
                $galleryurl = I("galleryimg"); //从图库选择的图片
                if($galleryurl){ 
                    $data['thumb'] = str_replace("/am_shop/Uploads/", "", $galleryurl) ; //从图库选择的图片
                }                      
            }              
 
            // 保存数据
            if ($_POST['id']) {
                $oldthumb = M("stores_goods")->where(array("id"=>$_POST['id']))->find();//old thumb
                $result   = M('storesGoods')->where("`id`={$_POST['id']}")->save($data);//update data
                $oldthumbs = M("stores_goods")->where(array("thumb"=>$oldthumb['thumb']))->select(); 
                if (!$oldthumbs) {
                    $gallery = M("stores_goods_gallery")->where(array("thumb"=>$oldthumb['thumb']))->find();
                    if(!$gallery){ //添加图片到商品图库
                        $datathumb['store_id'] = $oldthumb['store_id'];
                        $datathumb['thumb'] = $oldthumb['thumb'];
                        $datathumb['thumb_name'] = $oldthumb['thumb_name'];
                        $datathumb['thumb_addtime'] = $oldthumb['thumb_addtime'];
                        M("stores_goods_gallery")->add($datathumb);   
                    }                                                                  
                    //unlink("./Uploads/{$thumbDel}");
                    unlink("./Uploads/{$introDel}");
                    foreach ($carouselDel as $key => $value) {
                        unlink("./Uploads/{$value}");
                    }
                }
                $gallerdel = M("stores_goods_gallery")->where(array("thumb"=>$data['thumb']))->delete();
            } else {
                $data['thumb_addtime'] = time();//缩略图添加时间
                $insert_id = M('storesGoods')->add($data);
            }
            $this->redirect('shopList',array('p'=>I('p')));die;
        }
        if ($_GET['id']) {
            $goods = M('storesGoods')->where("id = {$_GET['id']}")->find();
            // 轮播图转数组处理
            /*$goods['carousel'] = unserialize($goods['carousel']);
            $i = 1;
            $newArray = array();
            foreach ($goods['carousel'] as $k => $v) {
                $newArray[] = array(
                    "carousel" => $v,
                    "index" => $i
                );
                $i++;
            }
            $goods['carousel'] = $newArray;*/
            // 参数转数组处理
            /*$goods['parameter'] = unserialize($goods['parameter']);
            $i = 1;
            $newArray = array();
            foreach ($goods['parameter'] as $k => $v) {
                $newArray[] = array(
                    "name" => $v['name'],
                    "content" => $v['content']
                );
                $i++;
            }
            $goods['parameter'] = $newArray;*/
            $this->assign('goods', $goods);
            $this->assign("id", $_GET['id']);
        }
        /*商品分类*/
        $category = M('storesGoodsCategories')->where("`store_id`=" . session("store_id"))->select();
        $this->assign("cate", $category);
        $gallery = $this->galleryList();
        $this->assign("gallery", $gallery);
        $this->display("shop_add");die;
    }

    /*分类管理*/
    public function category()
    {
        $res = M('storesGoodsCategories')->where("`store_id`=" . session("store_id"))->select();
        $this->assign("list", $res);
        $this->display("category");die;
    }

    public function category_add()
    {
        if (IS_POST) {
            $data = array(
                'name' => $_POST['name'],
                'store_id' => session("store_id")
            );
            if ($data['name'] == null) {
                $this->error("分类名不能为空");die;
            }
            M('storesGoodsCategories')->add($data);
            $this->redirect('category');die;
        }
        $this->assign('category', 1);
        $this->display('brand');die;
    }

    public function category_update()
    {
        if (IS_POST) {
            $data = array(
                'name' => $_POST['name']
            );
            if ($data['name']==null) {
                $this->error("分类名不能为空");die;
            }
            $id = $_POST['id'];
            $result = M('storesGoodsCategories')->where("id = {$id}")->save($data);
            $this->redirect('category');die;
        }
    }

    public function category_del()
    {
        $id = $_GET['id'];
        $result = M('storesGoodsCategories')->where("id = {$id}")->delete();
        $this->redirect('category');die;
    }

    //图库列表
    public function galleryList()
    {    
        $store_id = session("store_id");//商家id
        if($_GET){
            $where['store_id'] = $store_id;
            $name = I("name");
            $map  .= " thumb_name LIKE '%".$name."%' AND";
            if($name){
                $where['thumb_name'] = array('like','%'.$name.'%');
                $this->assign("name",$name);
            }
        }
        $where['store_id'] = $store_id;
        $map .= ' store_id='.$store_id.' ';
        $Model = M("stores_goods");
        $count = $Model->field('id,goods_name,store_id,thumb,thumb_name,thumb_addtime,deleted')
                      ->where($where)
                      ->group("thumb")
                      ->union('SELECT id,goods_name,store_id,thumb,thumb_name,thumb_addtime,deleted FROM am_stores_goods_gallery where'.$map,true)
                      ->select();
        $count = count($count);
        $Page = new \Think\Page($count, 8);//分页显示记录数
        $show = $Page->show();// 分页显示输出   
        $list = $Model->field('id,goods_name,store_id,thumb,thumb_name,thumb_addtime,deleted')
                      ->where($where)
                      ->group('thumb')
                      ->union('SELECT id,goods_name,store_id,thumb,thumb_name,thumb_addtime,deleted FROM am_stores_goods_gallery where'.$map,true)
                      ->select();
        //获取图片属性
        foreach ($list as $key => &$value) {
            $thumburl = "./Uploads/".$value['thumb'];
            $thumbsize= getimagesize($thumburl);
            $filesize = round(filesize($thumburl)/1024,2);
            $value['thumbsize'] = "尺寸:".$thumbsize[0]."x".$thumbsize[1]."，大小:".$filesize."KB<br />上传时间:".date("Y-m-d H:i:s",$value['thumb_addtime'])."<br />".$value['thumb'];
            
            $thumbs = "";   
            $thumbs = M("stores_goods")->where(array("store_id"=>session("store_id"),"thumb"=>$value['thumb']))->order("id desc")->select();
            $count  = count($thumbs);
            if($count > 1){
                $thumbss .= $thumbs;
                $value['goods_name'] = "";
                foreach ($thumbs as $k => $v) {
                    $value['goods_name'] .= $v['goods_name']."><br />";
                }
            }else{
                $value['goods_name'] = "";
                $value['goods_name'] .= $thumbs[0]['goods_name']."<br />";
            }
        }
        return $list;
    }
}