<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Goods extends Score_Controller {

    protected $chance = array(1000,10000,100000,1000000);
   
    public function __construct()
    {
        parent::__construct();
        $this->load->library('pagination');
        $this->load->model('score/Goods_model', 'goods');
        $this->config->load('otherconf',TRUE);
    } 
    /**
     * [index 商品显示列表页面]
     * @return [type] [description]
     */
    public function index($offset ='')
    {
        #配置分页信息
        $config['base_url'] = site_url('score/goods/index');
        $config['total_rows'] = $this->goods->count();
        $config['per_page'] = 50;
        $config['uri_segment'] = 4;

        $config['first_link'] = '首页';
        $config['first_tag_open'] = '<li id="first">';
        $config['first_tag_close'] = '</li>';

        $config['last_link'] = '末页';
        $config['last_tag_open'] = '<li id="last">';
        $config['last_tag_close'] = '</li>';

        $config['next_link'] = '下一页';
        $config['next_tag_open'] = '<li id="down">';
        $config['next_tag_close'] = '</li>';

        $config['prev_link'] = '上一页';
        $config['prev_tag_open'] = '<li id="top">';
        $config['prev_tag_close'] = '</li>';
        $config['num_links'] = 5;

        $config['full_tag_open'] = '<div class="wrap"><div class="fenye"><ul>';
        $config['full_tag_close'] = '</ul></div></div>';
        
        #初始化分页类
        $this->pagination->initialize($config);

         #生成分页信息
        $data['pageinfo'] = $this->pagination->create_links();
        $limit = $config["per_page"];
        $listInfo = $this->goods->getGoodsList($limit,$offset);
        $status = $this->config->item('score','otherconf');

        $this->load->model('score/Exchange_model', 'exchange');
        foreach ($listInfo as $k=>$v) {
            $listInfo[$k]['cate'] = $status['cate'][$v['cate']];
            $listInfo[$k]['type'] = $status['type'][$v['type']];
            $listInfo[$k]['get_type'] = $status['get_type'][$v['get_type']];
            $listInfo[$k]['recommend'] = $status['recommend'][$v['recommend']];
            $listInfo[$k]['status'] = $status['status'][$v['status']];
            //备注处理字段
            $listInfo[$k]['c_recommend'] = $v['recommend'];
            $listInfo[$k]['c_status'] = $v['status'];
            //剩余库存量
            $listInfo[$k]['num'] = $v['num'];
        }
        $data['listInfo'] = $listInfo;
        $this->load->view('common/innerheader');
        $this->load->view('admin/score/goodsList',$data);
    }
    /**
     * [add 商品添加页面]
     */
    public function add($cate='')
    {
        $data['cate'] = $cate;
        $data['chances'] =$this->chance;
        $this->load->view('common/innerheader',$data);
        $this->load->view('admin/score/addGoods',$data);
        $this->load->view('common/footer');
    }

    /**
     * [edit 商品编辑页面]
     */
    public function edit($id='')
    {
        $data = $this->goods->getGoodsInfo($id);
        $data['title'] = '商品修改';
        $data['chances'] =$this->chance;
        //概率转换处理
        foreach ($this->chance as $v) {
            if(strstr($v*$data['chance'],'.') && $v*$data['chance']>0)
            {
                continue;
            }
            else{
                $data['chance2']=$v*$data['chance'];
                $data['chance1']=$v; 
                break;              
            }
        }
        $this->load->view('common/innerheader');
        $this->load->view('admin/score/editGoods',$data);
        $this->load->view('common/footer');
    }  
    /**
     * [save 商品添加和修改]
     */
    public function save($id='')
    {     
        $rules_config = array(
            array(
                'field' => 'name',
                'label' => '商品名称',
                'rules' => 'trim|required|max_length[16]'
            ),
            array(
                'field' => 'cate',
                'label' => '商品类别',
                'rules' => 'trim|required'
            ),
            array(
                'field' => 'type',
                'label' => '兑换方式',
                'rules' => 'trim|required'
            ),
            array(
                'field' => 'score',
                'label' => '消耗积分',
                'rules' => 'trim|required|regex_match[/^([1-9])\d{0,6}$/]'
            ),
            array(
                'field' => 'num',
                'label' => '数量',
                'rules' => 'required|trim|regex_match[/^([1-9])\d{0,6}$/]'
            ),
            array(
                'field' => 'exchange_num',
                'label' => '兑换数量',
                'rules' => 'required|trim|regex_match[/^([0-9])\d{0,6}$/]'
            ),
            array(
                'field' => 'get_type',
                'label' => '获取方式',
                'rules' => 'required|trim'
            ),
            array(
                'field' => 'message',
                'label' => '商品详情',
                'rules' => 'required|trim'
            ),           
        );
        if($_POST['type'] == 2){
            $rules_config[] = array(
                'field' => 'chance1',
                'label' => '中奖概率',
                'rules' => 'trim|required'
            );
            $rules_config[] = array(
                'field' => 'chance2',
                'label' => '中奖概率',
                'rules' => 'trim|required'
            );  
            $_POST['chance'] = $_POST['chance2'] /$_POST['chance1'];
        }
        if($_POST['cate'] ==1 && $_POST['address'] =='')
        {
            $this->load->model('score/shopInfo_model', 'info');
            $result = $this->info->getShopInfo();
            $_POST['address'] =  $result['addr'];        
        }
        $this->load->library('form_validation', $rules_config);  
 
        if($this->form_validation->run() == FALSE)
        {
            print_r($this->form_validation->error_array());
        }
        else
        {            
            $goods_id = $id ? $this->goods->update($_POST, $id) : $this->goods->insert($_POST);
        }

        redirect('score/goods/index');
    }


    /**
     * [summer 商品详情页图上传]
     * @return [type] [description]
     */
    public function summer()
    {     
        $path = '/card/uploads/score/';
        $url = dirname(base_url());
        if ($_FILES['file']['name']) {
            if (!$_FILES['file']['error']) {
                $name = md5(rand(100, 200));
                $ext = explode('.', $_FILES['file']['name']);
                $filename = $name . '.' . $ext[1];
                $types =array('gif','jpg','png');
                if(!in_array($ext[1],$types))
                {
                    echo  $message = '请上传正确格式图片';exit;
                }
                $destination =dirname(FCPATH).$path. $filename; //change this directory
                $location = $_FILES["file"]["tmp_name"];
                move_uploaded_file($location, $destination);

                $url = $url.$path.$filename;
                echo $url;
            }
            else
            {
              echo  $message = '请上传正确格式图片';
            }
        }
    }    
    /**
     * [upload 商品图片上传]
     */
    public function upload(){
        $path = '/card/uploads/score/';
        $config['upload_path']      = dirname(FCPATH).$path;
        $url = dirname(base_url());
        $config['allowed_types']    = 'gif|jpg|png';
        $config['file_name'] = date('YmdHis').rand(0,100);
        $this->load->library('upload', $config);


        if ( ! $this->upload->do_upload('avatar'))
        {
            $error = array('error' => $this->upload->display_errors());
            echo json_encode($error);exit;
        }
        else
        {
            $data = $this->upload->data();
            $url = $url.$path.$data['file_name'];
            $pic['url'] = $url;
            echo json_encode($pic);
            exit;
        }
       
    }
    /**
     * [operate 商品上架,下架,推荐,取消推荐操作]
     * @return [type] [json]
     */
    public function operate()
    {
        $rules_config = array(
            array(
                'field' => 'mod',
                'label' => '操作方法',
                'rules' => 'trim|required'
            ),
            array(
                'field' => 'status',
                'label' => '状态值',
                'rules' => 'trim|required'
            ),
            array(
                'field' => 'gid',
                'label' => '商品ID',
                'rules' => 'trim|required'
            ),          
        );   
        $this->load->library('form_validation', $rules_config);    
        if($this->form_validation->run() == FALSE)
        {
            print_r($this->form_validation->error_array());
        }
        else
        {            
            $_POST['mod'] == 'recommend'?$data['recommend']=$_POST['status']:$data['status']=$_POST['status'];
            $goods_id = $this->goods->update($data,$_POST['gid']);
            echo $goods_id>0?$this->json(1,''):$this->json(2,'操作失败');
        }

    }
}