<?php

namespace Smi\Controller;

use Think\Controller;

class GoodsController extends BaseController {

    /* ┏┳┳┳┳┳┳┳┳┳┳商品分类管理┳┳┳┳┳┳┳┳┳┳┓ */


    //一级分类
    public function goods_cat(){

//      auth_check("goods_cat_r");

//    $this->assign('auth',auth_check("goods_cat_w"));

        $map ="admin_id=".$_SESSION['admin_id'];

        $count = M('goods_cat')->where($map)->count();

        $Page = new \Think\Page($count,20);

        $show = $Page->show();

        $cat = M('goods_cat')->where($map)->limit($Page->firstRow.','.$Page->listRows)->order("status desc,home_show desc,seat_no desc,create_time desc")->select();

        foreach($cat as $k=>$val){

            $cat[$k]['img'] = __ROOT__."/Uploads/goods_cat/".$val['img'];

        }

        $this->assign('cat',$cat);

        $this->assign('page',$show);

        $this->display();

    }
    //商品二级分类
    public function goods_cat_child($pid){

//      auth_check("goods_cat_r");

//    $this->assign('auth',auth_check("goods_cat_w"));

        $pid = I('pid');

        $where='pid='.$pid;

        $count = M('goods_cat')->where($where)->count();

        $Page = new \Think\Page($count,20);

        $show = $Page->show();

        $cat = M('goods_cat')->where($where)->limit($Page->firstRow.','.$Page->listRows)->order("status desc,home_show desc,seat_no desc,create_time desc")->select();

        foreach($cat as $k=>$val){

            $cat[$k]['img'] = __ROOT__."/Uploads/goods_cat/".$val['img'];

        }

        $this->assign('cat',$cat);

        $this->assign('page',$show);

        $this->display();

    }

    public function goods_cat_op(){

//      auth_check("goods_cat_w");

        $op = I('op');
        $map ="admin_id=".$_SESSION['admin_id'];
        $id = I('id')?:0;

        $pid_lists=M('goods_cat')->where($map)->field('id,title')->select();
        // var_dump($pid_lists);exit;
        // var_dump($_POST);exit;
        if($op == 'save'){

            $data['seat_no'] = (int)I('seat_no');


            $data['title'] = I('title');
            $data['admin_id'] = session('admin_id');

            if(!$data['title']){$this->error("保存失败","",2);die;}



            if($id){

                $data['id'] = $id;

                if (!empty($_FILES['img']['name'])) {
                    $info = M('goods_cat')->where(array('id' => $id))->find();
                    $upload = ToolsController::upload('goods_cat/', 'img');
                    if ($upload['status'] == 1) {
                        $data['img'] = $upload['file_path'];
                    }
                }

                $result = M('goods_cat')->save($data);

                $url = session(__FUNCTION__.'_jump')?:'';

                session(__FUNCTION__.'_jump',null);

                if ($result) {
                    if (!empty($_FILES['img']['name'])) {
                        unlink(_ROOT__."/Uploads/".$info['img']);
                    }
                    $this->success('保存成功',$url,2);
                } else {
                    if (!empty($_FILES['img']['name'])) {
                        unlink(_ROOT__."/Uploads/".$data['img']);
                    }
                    $this->error('保存失败');
                }

                die;

            }else{

                $data['create_time'] = time();
                if (!empty($_FILES['img']['name'])) {
                    $upload = ToolsController::upload('goods_cat/', 'img');
                    if ($upload['status'] == 1) {
                        $data['img'] = $upload['file_path'];
                    }
                }
                $result = M('goods_cat')->add($data);

                if ($result) {
                    $this->success('保存成功','goods_cat',2);die;    
                } else {
                    if (!empty($_FILES['img']['name'])) {
                        unlink(_ROOT__."/Uploads/".$data['img']);
                    }
                    $this->error('保存失败');die;
                }
            }

        }else if($op == 'edit'){

            $cat = M('goods_cat')->where("id = {$id}")->find();

            if(!$cat){$this->error('该分类不存在','',2);die;}

            $this->assign('cat',$cat);

        }else if($op == 'dele'){

            M('goods_cat')->where("id = {$id}")->delete();

            $this->success('删除成功','',2);die;

        }
        $this->assign('pid_lists',$pid_lists);
        session(__FUNCTION__.'_jump',$_SERVER['HTTP_REFERER']);

        $this->display();

    }

    public function getAllCat(){

        $admin_id=session('admin_id');
        $list = M('goods_cat')->where('admin_id = '.$admin_id)->select();

        $cat = array();

        foreach($list as $val){

            $cat[$val["id"]] = $val["title"];

        }

        return $cat;

    }

    /* ┗┻┻┻┻┻┻┻┻┻┻商品分类管理┻┻┻┻┻┻┻┻┻┻┛ */





    /* ┏┳┳┳┳┳┳┳┳┳┳商品管理┳┳┳┳┳┳┳┳┳┳┓ */

    public function goods(){

        //总商品数量

        $count=M('goods')->where('admin_id='.session('admin_id'))->select();
        // var_dump($count);exit;
        $this->assign('count',count($count));

//      auth_check('goods_list_r');

//    $this->assign('auth',auth_check("goods_list_w"));

        $op = I('op');

        $map = 'admin_id='.session('admin_id');


        $id = I('id')?:0;

        if($id){

            $map = " id = {$id} ";

        }else{

            $type = I('type');

            $title = I('title');

        }

        if($title){

            $map .= " and (title like '%{$title}%' or model like '%{$title}%') ";

        }

        if($type == 1){

            $map .= " and status = 1  ";

        }else if($type == 2){

            $map .= " and status = 0 ";

        }
        if($op != 'export'){

            $count = M("goods")->where($map)->count();

            $Page = new \Think\Page($count,20);

            $this->assign("page",$Page->show());

            $limit = $Page->firstRow.','.$Page->listRows;

        }

        $list = M("goods")->where($map)->order("id desc")->limit($limit)->select();
        // var_dump($list);exit;
        $cat = $this->getAllCat();

        foreach($list as &$val){

            $val["img"] = __ROOT__."/Uploads/".$val['img'];

            $val["cat_name"] = $cat[$val["cat_id1"]];

            $val["status_name"] = $val['status']==1?"上架":"下架";

        }

        if($op == "export"){

            $data = array(array('商品ID','所属分类','商品名称','型号','金币售价','原价','进货价','销量','库存数量','状态','添加时间'));

            unset($val);

            foreach($list as $val){

                $data[] = array($val["id"],$val["cat_name"],$val["title"],$val["model"],$val["price"],$val["orig_price"],$val["buy_price"],$val["sales"],$val["total"],$val["status_name"],date("Y-m-d H:i",$val["create_time"]));

            }

            create_xls($data,'商品列表_'.date("Y-m-d H:i"));

            die;

        }

        $this->assign("list",$list);

        $this->display();

    }

    public function goods_op(){

//      auth_check('goods_list_w');

        $op = I('op');

        $id = I('id')?:0;
        //商品一级分类
        $admin_id=session('admin_id');
        $one=M('goods_cat')->where('admin_id='.$admin_id)->field('id,title')->select();
        $this->assign("one",$one);


        //当前管理员商家id
        // $group_id=M('users')->where('id='.$_SESSION['toy_admin_id'])->getField('group_id');

        if($id){

            $goods = M('goods')->where("id = {$id}")->find();

            if(!$goods){$this->error('该商品不存在','',2);die;}
            // var_dump($goods);exit;
            if($goods['cat_id1']){
                $goods['cate1_name']=M('goods_cat')->where('id='.$goods['cat_id1'])->getfield('title');
                $cate2_lists=M('goods_cat')->where('pid='.$goods['cat_id1'])->field('id,title')->select();
                $this->assign("cate2_lists",$cate2_lists);
            }
            if($goods['cat_id']){
                $goods['cate2_name']=M('goods_cat')->where('id='.$goods['cat_id'])->getfield('title');
            }


            // print_r($goods['attr_lists']);exit;

        }
        // var_dump($_SESSION);exit;

        if($op == 'save'){



            $data['title'] = I('title');

            $data['price'] = (float)I('price');

            $data['admin_id'] = session('admin_id');


            // $data['deposit'] = (float)I('deposit');

            $data['cat_id'] = (int)I('cat_id');



//      foreach($data as $val){if(!$val){dump($data);$this->error("保存失败","",2);die;}}

            $data['seat_no'] = (int)I('seat_no');

            $data['status'] = I('status')?1:0;

            $data['allow_comment'] = I('allow_comment')?1:0;


//      $data['title2'] = I('title2');

            // $data['brand'] = I('brand');

//      $data['buy_price'] = (float)I('buy_price');

//      $data['total'] = (int)I('total');

            $data['model'] = I('model');
            $data['admin'] = $_SESSION['admin_id'];



            $data['content'] = I('content');
//        var_dump($data);
            //迭代代码
//      $data['unit'] = I('unit'); //商品单位名称
//      $data['is_hot'] = I('is_hot'); //商品属性
            $data['max_buy'] = I('max_buy'); //最大下单数量
            $data['false_sell'] = I('false_sell'); //虚拟销量
//      $data['parameter']=I('parameter'); //产品参数
            $data['cat_id1'] = I('cat_id1'); //一级分类id
//      $data['orig_price'] = (float)I('orig_price'); //进货价




            if($_FILES['img']['name']){

                $return = $this->upload('img',"goods",true);

                if(is_array($return)) $data['img'] = $return['savepath'].$return['savename'];

                else {$this->error($return,'',2);die;}

            }

            if(!$data['img'] && !$id){$this->error('保存失败','',2);die;}



            if($id){

                $imgs_old = unserialize($goods["imgs"]);

                $imgs_dele = explode(",",I('imgs_dele'));

                foreach($imgs_dele as $val){

                    if($val && $imgs_old[$val]){

                        unlink("./Uploads/".$imgs_old[$val]);

                        $imgs_old[$val] = "";

                    }

                }

            }

            $imgs = array();

            for($i=0;$i<9;$i++){

                if($_FILES["imgs_{$i}"]["name"]){

                    $return = $this->upload("imgs_{$i}","goods_swiper",true);

                    if(is_array($return)){

                        $imgs[$i] = $return['savepath'].$return['savename'];

                    }

                }

                if(!$imgs[$i]){

                    $imgs[$i] = $imgs_old[$i]?:"";

                }

            }

            $data['imgs'] = serialize($imgs);




            if($id){

                if($data['img']){

                    unlink("./Uploads/".$goods['img']);

                }

                $data['id'] = $id;
                // var_dump($data);exit;
                M('goods')->save($data);

                $attr= I('attr');
                // print_r($attr);exit;
                // M('goods_attr')->where('goods_id='.$id)->delete();
                foreach($attr as $i=>$val){
                    $cateattr_id=$val['cateattr_id'];

                    foreach($val['data'] as $k=>$vel){
                        $add['goods_id']=$id;
                        $add['cateattr_id']=$cateattr_id;
                        $add['attr_title']=$vel['title'];
                        $add['attr_price']=$vel['price'];
                        $rows=M('goods_attr')->where('goods_id='.$id.' and cateattr_id='.$cateattr_id.' and attr_title="'.$vel['title'].'"')->getField('id');
                        if($rows){
                            $save['attr_price']=$vel['price'];
                            $vers=M('goods_attr')->where('id='.$rows)->save($save);
                        }else{
                            $vers=M('goods_attr')->add($add);
                        }

                        // echo M()->getlastsql()."<br>";
                    }
                }

                $url = session(__FUNCTION__.'_jump')?:'';

                session(__FUNCTION__.'_jump',null);

                $this->success('保存成功',$url,2);

            }else{

                $data['create_time'] = time();
                
                $goods_id = M('goods')->add($data);
                // dump($goods_id);die;
                if($goods_id){
                    $attr= I('attr');
                    foreach($attr as $i=>$val){
                        $cateattr_id=$val['cateattr_id'];

                        foreach($val['data'] as $k=>$vel){
                            $add['goods_id']=$goods_id;
                            $add['cateattr_id']=$cateattr_id;
                            $add['attr_title']=$vel['title'];
                            $add['attr_price']=$vel['price'];
                            $vers=M('goods_attr')->add($add);
                            // echo M()->getlastsql()."<br>";
                        }
                    }
                }

                $this->success('保存成功','goods',2);

            }



            die;



        }else if($op == 'edit'){
            // var_dump($goods);exit;
            $goods["img"] = __ROOT__."/Uploads/".$goods['img'];

            $goods["imgs"] = unserialize($goods["imgs"]);

            foreach($goods["imgs"] as $k=>$val){

                if($val){

                    $goods["imgs_{$k}"] = __ROOT__."/Uploads/".$val;

                }else{

                    $goods["imgs_{$k}"] = "";

                }

            }
            // var_dump($goods);exit;
//            if($id){
//                //商品属性分类
//                $goods['attr_lists']=M('goods_cateattr')->where('cate_id='.$goods['cat_id'])->field('id,title')->order('sort desc')->select();
//                // print_r($goods['attr_lists']);exit;
//                $iii=[];
//                if($goods['attr_lists']){
//                    foreach($goods['attr_lists'] as $i=>&$val){
//                        $data=M('goods_attr')->where('goods_id='.$goods['id'].' and cateattr_id='.$val['id'])->order('id asc')->field('attr_title,attr_price')->select();
//                        if($data){
//                            $val['data']=$data;
//                        }
//                        $iii[$i]['id']=$val['id'];
//                        $iii[$i]['num']=count($val['data'])-1;
//                        if($iii[$i]['num']<0){
//                            $iii[$i]['num']=0;
//                        }
//                    }
//
//                }
//            }
            // print_r($goods['attr_lists']);exit;
            // var_dump($iii);exit;
//            $this->assign("iii",$iii);
            $this->assign("goods",$goods);

        }else if($op == 'dele'){

            // M('goods')->where("id = {$id}")->setField("status",-1);
            M('goods')->delete($id);

            $this->success('删除成功','',2);die;

        }



        /* 个人供方、商家供方列表 */

        // $personal = M("supply_personal")->order("create_time desc")->select();

        // $business = M("supply_business")->order("create_time desc")->select();

        // $this->assign('personal',$personal);

        // $this->assign('business',$business);



        session(__FUNCTION__.'_jump',$_SERVER['HTTP_REFERER']);

        $this->display();

    }

    /* ┗┻┻┻┻┻┻┻┻┻┻商品管理┻┻┻┻┻┻┻┻┻┻┛ */





    public function upload($name,$folder='',$datefolder=false){

        $upload = new \Think\Upload();

        $upload->maxSize  = 52428800 ;

        $upload->exts     = array('jpg', 'gif', 'png', 'jpeg');

        if($datefolder && $folder){

            $upload->rootPath = "./Uploads/";

            $upload->savePath = "{$folder}/";

        }else{

            $upload->rootPath = './Uploads/';

            //当subName未定义而autoSub为true时，自动以日期创建目录。

            $upload->subName  = $folder?$folder:$name;

        }

        $upload->autoSub  = true;

        $info = $upload->uploadOne($_FILES[$name]);

        if(!$info) $info = $upload->getError();

        return $info;

    }

    public function get_two(){
        // echo $_POST['id'];exit;
        if(isset($_POST['id'])){
            $pid=$_POST['id'];
            $data=M('goods_cat')->where('pid='.$pid)->field('id,title')->select();
            // var_dump($data);exit;
        }
        // $this->ajaxReturn($data);
        echo json($data);
    }

    public function get_attr(){
        // echo $_POST['id'];exit;
        if(isset($_POST['id'])){
            $pid=$_POST['id'];
            $data=M('goods_cateattr')->where('cate_id='.$pid)->order('sort desc')->field('id,title')->select();
            // var_dump($data);exit;
        }
        // $this->ajaxReturn($data);
        echo json($data);
    }


    public function attr_op(){

        $op = I('op');

        if($op == 'save'){

            $data['title'] = I('title');

            $data['sort'] = I('sort');

            $data['status'] = I('status');


            foreach($data as $val){ if(!$val){ $this->error('保存失败,请填写完毕','',1);die; } }
            $data['addtime']=time();

            M('goods_attr')->add($data);

            $this->success('保存成功','',1);die;

        }else if($op == 'dele'){

            $id = I('id');

            M('goods_attr')->where("id = {$id}")->delete('status',0);

            $this->success('删除成功','',1);die;

        }else if($op == 'dowm'){

            $id = I('id');

            M('goods_attr')->where("id = {$id}")->setField('status',0);

            $this->success('隐藏成功','',1);die;

        }else if($op == 'up'){

            $id = I('id');

            M('goods_attr')->where("id = {$id}")->setField('status',1);

            $this->success('显示成功','',1);die;

        }

    }


    //分类属性类型列表
    public function cateattr_lists($pid){

        // auth_alert("cateattr_lists");
//      auth_check("goods_cat_r");

        // $this->assign('auth',auth_check("cateattr_lists"));

        $pid = I('pid');

        $where='cate_id='.$pid;

        $count = M('goods_cateattr')->where($where)->count();

        $Page = new \Think\Page($count,20);

        $show = $Page->show();

        $attr = M('goods_cateattr')->where($where)->limit($Page->firstRow.','.$Page->listRows)->order("sort desc")->select();

        $this->assign('attr',$attr);
        $cate_one_id=M('goods_cat')->where('id='.$_GET['pid'])->getField('pid');//获取一级分类id
        $this->assign('cate_one_id',$cate_one_id);

        $cate_one_list=M('goods_cat')->where('pid=0')->field('id,title')->select();//获取一级分类列表
        $cate_two_list=M('goods_cat')->where('pid='.$cate_one_id)->field('id,title')->select();//获取二级分类列表
        $this->assign('one',$cate_one_list);
        $this->assign('two',$cate_two_list);

        $this->assign('page',$show);

        $this->display();

    }


    public function cateattr_delete($id){
//      auth_check("cateattr_lists");

//    $this->assign('auth',auth_check("cateattr_lists"));

        $id = I('id');

        M('goods_cateattr')->where("id = {$id}")->delete();

        $this->success('删除成功','',2);die;

    }

    public function cateattr_add(){
//      auth_check("cateattr_lists");

//    $this->assign('auth',auth_check("cateattr_lists"));

        // var_dump($_REQUEST);exit;
        $add['cate_id'] = I('cate_id');

        $add['title'] = I('title');

        $add['sort'] = I('sort');

        M('goods_cateattr')->add($add);

        $this->success('新增成功','',2);die;

    }

    public function cateattr_edit(){
//      auth_check("cateattr_lists");

//    $this->assign('auth',auth_check("cateattr_lists"));

        // var_dump($_REQUEST);exit;
        $id = I('id');

        $save['cate_id'] = I('cate_id');

        $save['title'] = I('title');

        $save['sort'] = I('sort');

        M('goods_cateattr')->where('id='.$id)->save($save);

        $this->success('修改成功','',2);die;

    }

}