<?php
namespace Smi\Controller;

use Think\Controller;

header("Content-Type:text/html;CharSet=UTF-8");
class ShopController extends BaseController
{
    /**
     * 商品列表
     */
    public function shopList()
    {
        auth_check("shop_read");
        $l = 10;
        $Model = M("");
        //商品ID/商品名/商品分类
         $where=array('deleted'=>array('eq','-1'));
         if($_GET['search']){
           $search=I('search'); 
           $types=D('Sales')->searching($search);
           if($types){
           		$where['G.pcate']=array('like',"%{$types}%");
           } else {
           		$where['G.goods_name|G.id']=array('like',"%{$search}%");
           }        
        }
         //dump($where);die;
        $count = $Model->table('am_goods G')
            ->join('LEFT JOIN am_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->table('am_goods G')
            ->join('LEFT JOIN am_goods_categories C ON C.id = G.pcate')
            ->order("G.is_daily desc,G.is_hot desc,G.is_new desc,G.is_material desc,G.sort asc,G.id desc")
            ->field("G.*,C.name as cate_name")
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->where($where)
            ->select();
        $this->assign('page', $show);// 赋值分页输出
        //定义变量并显示模板
        $this->assign("list", $list);
        $this->display("index");die;
    }
    
    /*商品删除*/
    public function shopDel()
    {
        auth_check("shop_opt");
        if (!$_GET['id']) {
            $this->error("获取商品ID失败，请重新试一下！");die;
        } else {
            M("goods")->where("`id`={$_GET['id']}")->setField("deleted", 1);
            alertMsg("删除成功", U('Shop/shopList'));
        }
    }

    /*商品添加*/
    public function shop_add()
    {
        auth_check("shop_opt");
        if (IS_POST) {
            if (M('goods')->where(array('goods_name' => I('goods_name'), 'admin_id' => session('admin_id')))->limit(1)->select()) {
                alertMsg('该商品已经存在', U('shop_add'));
            }

            // 缩略图
            if ($_FILES['thumb']['error'] != 0) {
                // 上传错误提示错误信息
                $this->error('请上传商品图片');die;
            }
            // dump(I());die;
            $data = array(
                'sort' => I('sort'),
                'goods_name' => I('goods_name'),
                'pcate' => $_POST['pcate'],
                'goods_price' => I("goods_price"),
                'is_sale' => $_POST['is_sale'],
                'des' => I("des"),
                'admin_id' => session('admin_id')
            );
            // dump($data);die;
            $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();
                    
            if ($info) {
                // 上传成功 获取上传文件信息
                $pic = $info['thumb']["savepath"] . $info['thumb']["savename"];
                $data['thumb'] = $pic; // 修改数据对象
            } else {
                // 上传错误提示错误信息
                $this->error($upload->getError());
            }
            
            if (M('goods')->data($data)->add()) {
                $this->success('添加成功');die;
            } else {
                $this->error('添加失败');die;
            }
        }

        /*商品分类*/
        $category = M('goods_categories')->field('id, name')->select();
        $this->assign("cate", $category);
        $this->display("shop_add");die;
    }

    /*分类管理*/
    public function category()
    {
        auth_check("shop_read");
        $res = M('goods_categories')->order("`sort` ASC")->select();
        $this->assign("list", $res);
        $this->display("category");die;
    }

    /**
     * 添加分类
     */
    public function category_add()
    {
        auth_check("shop_opt");
        if (IS_POST) {
            $data = array(
                'name' => I('name')
            );
            $sort = I("sort");
            if (is_numeric($sort) && $sort > 0) {
                $data['sort'] = $sort;
            }
            /*if ($_FILES['img']['error'] != 4) {
                $upload = new \Think\Upload();// 实例化上传类
                // $upload->maxSize = 3145728 ;// 设置附件上传大小
                // 设置附件上传类型
                $upload->exts = array('jpg', 'gif', 'png', 'jpeg');
                $upload->rootPath = './Uploads/'; // 设置附件上传根目录 
                $upload->savePath = 'cate_img/'; // 设置附件上传目录
                $upload->autoSub = false; //不要子文件夹
                // 上传文件
                $info = $upload->upload();
                if (!$info) {
                    // 上传错误提示错误信息
                    $this->error($upload->getError());die;
                } else {
                    // 上传成功 获取上传文件信息
                    $pic = $info['img']["savepath"] . $info['img']["savename"];
                    $data['img'] = $pic; // 修改数据对象  
                }
            }*/
            if ($data['name'] == null) {
                $this->error("分类名不能为空");die;
            }
            M('goods_categories')->add($data);
            $this->redirect('category');die;
        }
        $this->assign('category', 1);
        $this->display('brand');die;
    }

    /**
     * 更新分类
     */
    public function category_update()
    {
        auth_check("shop_opt");
        if (IS_POST) {
            $data = array(
                'name' => I('name')
            );
            $sort = I("sort");
            if (is_numeric($sort) && $sort > 0) {
                $data['sort'] = $sort;
            }
            if ($data['name']==null) {
                $this->error("分类名不能为空");die;
            }
            /*if ($_FILES['img']['error'] != 4) {
                $imgDel = M('goodsCategories')->where("id = {$_POST['id']}")->getField("img");
                $upload = new \Think\Upload();// 实例化上传类
                $upload->maxSize = 3145728 ;// 设置附件上传大小
                // 设置附件上传类型
                $upload->exts = array('jpg', 'gif', 'png', 'jpeg');
                $upload->rootPath = './Uploads/'; // 设置附件上传根目录 
                $upload->savePath = 'cate_img/'; // 设置附件上传目录
                $upload->autoSub = false; //不要子文件夹
                // 上传文件
                $info = $upload->upload();
                if(!$info) {
                // 上传错误提示错误信息
                    $this->error($upload->getError());die;
                }else{
                // 上传成功 获取上传文件信息
                    $pic = $info['img']["savepath"] . $info['img']["savename"];
                    $data['img'] = $pic; // 修改数据对象  
                }
            }*/
            $id = $_POST['id'];
            $result = M('goodsCategories')->where("id = {$id}")->save($data);
            if ($result) {
                unlink("./Uploads/{$imgDel}");
            }
            $this->redirect('category');die;
        }
    }

    /**
     * 删除分类
     */
    public function category_del()
    {
        auth_check("shop_opt");
        $id = $_GET['id'];
        $imgDel = M('goodsCategories')->where("id = {$id}")->getField("img");
        $result = M('goodsCategories')->where("id = {$id}")->delete();
        if ($result) {
            unlink("./Uploads/{$imgDel}");
        }
        $this->redirect('category');die;
    }

    /**
     * 特别照顾村 列表
     */
    public function shopVillageList()
    {
        auth_check("shop_read");
        $list = M("goodsVillageSet")
            ->where("gvs.`good_id`={$_GET['good_id']}")
            ->join("gvs LEFT JOIN `am_region_village` v ON gvs.`village_id`=v.`id`")
            ->field("gvs.*,v.`name` AS `village_name`")
            ->select();
        $this->assign("list", $list);
        $this->assign("good_id", $_GET['good_id']);
        $good_name = M("goods")->where("`id`={$_GET['good_id']}")->getField("goods_name");
        $this->assign("good_name", $good_name);
        $this->display("shopVillageList");die;
    }

    /**
     * 添加村独立设置
     */
    public function shopVillageAdd()
    {
        auth_check("shop_opt");
        if (IS_POST) {
            $data['good_id'] = $_POST['good_id'];
            $data['village_id'] = $_POST['village_id'];
            if (is_numeric($_POST['price']) && $_POST['price'] > 0) $data['price'] = $_POST['price'];
            if (is_numeric($_POST['expect_time']) && $_POST['expect_time'] > 0) $data['expect_time'] = $_POST['expect_time'];
            if (($data['price'] || $data['expect_time']) && $data['village_id']) {
                $existNum = M("goodsVillageSet")->where("`good_id`={$data['good_id']} AND `village_id`={$data['village_id']}")->count();
                if ($existNum > 0) {
                    alertMsg("该村已设置", U("shopVillageList", array("good_id" => $_POST['good_id'])));
                }
                $insert_id = M("goodsVillageSet")->add($data);
            }
            if ($insert_id) {
                alertMsg("添加成功", U("shopVillageList", array("good_id" => $_POST['good_id'])));
            } else {
                $this->redirect("shopVillageList?good_id={$_POST['good_id']}");die;
            }
        } else {
            $province = M("regionProvince")->select();
            $this->assign("province", $province);
            $this->assign("good_id", $_GET['good_id']);
            $this->assign("small", "添加独立设置");
            $this->display("shopVillageAdd");die;
        }
    }

    /**
     * 编辑村独立设置
     */
    public function shopVillageEdit()
    {
        auth_check("shop_opt");
        if (IS_POST) {
            $id = $_POST['id'];
            $data['good_id'] = $_POST['good_id'];
            $data['village_id'] = $_POST['village_id'];
            if (is_numeric($_POST['price']) && $_POST['price'] > 0) $data['price'] = $_POST['price'];
            if (is_numeric($_POST['expect_time']) && $_POST['expect_time'] > 0) $data['expect_time'] = $_POST['expect_time'];
            if (($data['price'] || $data['expect_time'])) {
                $result = M("goodsVillageSet")->where("`id`={$id}")->save($data);
            }
            if ($result) {
                alertMsg("修改成功", U("shopVillageList", array("good_id" => $_POST['good_id'])));
            } else {
                $this->redirect("shopVillageList?good_id={$_POST['good_id']}");die;
            }
        } else {
            $info = M("goodsVillageSet")->where("`id`={$_GET['id']}")->find();
            $this->assign("info", $info);
            $province = M("regionProvince")->select();
            $this->assign("province", $province);
            $this->assign("good_id", $_GET['good_id']);
            $this->assign("small", "添加独立设置");
            $village_id = $info['village_id'];    // 村ID
            $county_id = M("regionVillage")->where("`id`={$village_id}")->getField("county_id");    // 县ID
            $city_id = M("regionCounty")->where("`id`={$county_id}")->getField("city_id");// 市ID
            $province_id = M("regionCity")->where("`id`={$city_id}")->getField("province_id");// 省ID
            $thisRegion = array(
                "province_id" => $province_id,
                "city_id" => $city_id,
                "county_id" => $county_id,
                "village_id" => $village_id
            );
            $this->assign("thisRegion", $thisRegion);
            // 市列表
            $cityList = M("regionCity")
                ->where("`province_id`={$province_id}")
                ->field("`id`,`name`")
                ->select();
            $this->assign("cityList", $cityList);
            // 县列表
            $countyList = M("regionCounty")
                ->where("`city_id`={$city_id}")
                ->field("`id`,`name`")
                ->select();
            $this->assign("countyList", $countyList);
            // 村列表
            $villageList = M("regionVillage")
                ->where("`county_id`={$county_id}")
                ->field("`id`,`name`")
                ->select();
            $this->assign("villageList", $villageList);
            $this->display("shopVillageAdd");die;
        }
    }

    /**
     * 点击省获取市列表 ajax
     */
    public function cirtiesFromProvince()
    {
        $province_id = $_REQUEST['province_id'];
        $cities = M("regionCity")
            ->where("`province_id`={$province_id}")
            ->field("`id`,`name`")
            ->select();
        $this->ajaxReturn($cities);die;
    }

    /**
     * 点击市获取县列表 ajax
     */
    public function countiesFromCity()
    {
        $city_id = $_REQUEST['city_id'];
        $counties = M("regionCounty")
            ->where("`city_id`={$city_id}")
            ->field("`id`,`name`")
            ->select();
        $this->ajaxReturn($counties);die;
    }

    /**
     * 点击县获取村列表 ajax
     */
    public function villagesFromCounty()
    {
        $county_id = $_REQUEST['county_id'];
        $villages = M("regionVillage")
            ->where("`county_id`={$county_id}")
            ->field("`id`,`name`")
            ->select();
        $this->ajaxReturn($villages);die;
    }
}