<?php
/**
 * 店铺中心
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaol <1094186793@qq.com>
 */
namespace Shop\Controller;
use Think\Controller;
class ServiceController extends BaseController {
    public function _initialize(){
        parent::_initialize();
        if(!checksiteauth('FuWu')){ exit;}
		$shops_info=session('shops_info');
        if(empty($shops_info['id'])) $this->error('身份过期，请重新登录',U('Shop/Register/shop_login'));
		$this->mendian();
		$this->inputtype = array('text' => L('TEXT'), 'checkbox' => L('REDIO'));
        $this->assign('inputtype', $this->inputtype);
        // 1117 ggw 
        $suc=D('Shops')->shop_option(MID,'goods');
        if(!$suc){$this->error('该店铺没有此权限，请联系管理员授权！');die;}
    }

    /**
     * 回收站的商品
     */
    public function recycle()
    {
        $tabid = I('param.tabid');
        if (!empty($tabid)) 
			$this->display($tabid);
        else {
            $postdata = I('param.');
            $postdata['is_delete'] = 1;
            $postdata['shop_id'] = MID;
            $list = $this->get_shop_goods_list($postdata);
            $this->assign('list', $list);
            $this->assign($postdata);
            $this->display();
        }
    }
    private function get_shop_goods_list($postdata){
        $name = CONTROLLER_NAME;
        $map = D('Admin/Goods')->index_condition($postdata);
        if (!isset($postdata['catid'])) {
            $postdata['catid'] = 0;
        }
        if (!isset($postdata['brandid'])) {
            $postdata['brandid'] = 0;
        }
        if (!isset($postdata['suppliersid'])) {
            $postdata['suppliersid'] = 0;
        }
        if($postdata['goodstype']){
            $map['goods_type'] = $postdata['goodstype'];
        }
        $this->getcateTree($postdata['catid'], '', $postdata['brandid'], $postdata['suppliersid']);
        $return = $this->lists($name, $map);
        return $return;
    }
    /**
     * 删除，回收站
     * @param $is_delete 0恢复,1删除
     */
    public function recycling()
    {
        $name = 'Goods';
        $postdata = I('post.');
        $id = I('get.id');
        if (empty($postdata['id']) && !empty($id)) $postdata['id'][] = $id;
        $is_delete = I('is_delete');
        if (empty($postdata['id'])) {
            if ($is_delete == 1) $this->error('请选择要删除的商品！');
            else $this->error('请选择要恢复的商品！');
        }
        $where['is_delete'] = $is_delete;
        foreach ($postdata['id'] as $key => $value) {
            $map['id'] = $value;
            $g_info = M($name)->where($map)->save($where);
        }
        if ($is_delete == 1) {
            if (isset($g_info)) {
                $this->success('已成功放入回收站');
            } else {
                $this->error('删除失败');
            }
        } else {
            if (isset($g_info)) {
                $this->success('恢复成功');
            } else {
                $this->error('恢复失败');
            }
        }
    }

    /**
     * 得到会员价
     * @param int $id
     */
    public function get_member_price($id=0){
        //会员
        $morerank = M('MemberRank')->field('id,name')->select();
        //会员价
        if(!empty($id))$user_price = M('MemberPrice')->where('goods_id = ' . $id)->select();
        $member_price = array();
        foreach ($morerank as $k => $v) {
            $member_price[$k]['id'] = $morerank[$k]['id'];
            $member_price[$k]['name'] = $morerank[$k]['name'];
            if(!empty($user_price[$k]['user_price']))$member_price[$k]['user_price'] = $user_price[$k]['user_price'];
        }
        $this->assign('member_price', $member_price);
        $this->assign('morerank', $morerank);
    }



    
    /**
     * 添加服务
     */
    public function service_add(){
         $auth_code = 'service_add';
        $ret=D('Shop/Shops')->shop_account_option($auth_code);
        if($ret['status']!=1) {$this->error($ret['msg']);exit;}
        
		// $return=D('Shops')->option(4,STYPE);
		// if($return == 0){
		// 	// $this->error('您还没添加服务的权限，请联系管理员！');
		// }
        $tab_id=I('param.tabid');
        $tab_id=empty($tab_id)?'service_baseinfo':$tab_id;
        if($tab_id=='service_baseinfo'){
            $basedefault = array('moreimg' => '', 'moreimgstr' => '', 'morecatarr' => '', 'morecatid' => '', 'configstr' => '');
            $this->assign($basedefault);
            $this->get_member_price();//会员价
        }
        $postdata['publish_wait'] = 0;
        $postdata['shop_id']=MID;
        $serviceCat = M('ServiceCategory')->where('status=1')->field('id,name')->select();
        $this->getSeviceCat();
        $this->assign($postdata);
        $this->assign('menu_tab',$tab_id);
        $this->assign('menu_action_current','service');
        $this->display($tab_id);
    }
    /**
     * 修改服务
     */
    public function service_edit(){
        $auth_code = 'service_edit';
        $ret=D('Shop/Shops')->shop_account_option($auth_code);
        if($ret['status']!=1) {$this->error($ret['msg']);exit;}

        $tab_id=I('param.tabid');
        $id = I('get.id');
        if (!$id) $this->error(L('PARAM_ERR'));
        $map['shop_ids']=MID;
        $map['id']=$id;
        $info = M('Goods')->where($map)->field(true)->find();
        if(!$info)$this->error('无此操作权限');
		
		if($info['service_spec']){
			$info['service_spec_info'] = json_decode($info['service_spec'],true);
			unset($info['service_spec']);
		}
		$info['speac_count'] = count($info['service_spec_info']);
		
        //获取商品的长字段
        $goodscontent = M('GoodsContent')->where('goods_id = ' . $id)->find();
        $info['content'] = $goodscontent['content'];
        $this->assign($info);
        $this->getSeviceCat();
        $this->assign('menu_tab',$tab_id);
        $this->assign('menu_action_current','service');
        $this->display('service_baseinfo');
    }
    /**
     * 插入服务
     */
    public function service_insert(){
          $auth_code = 'service_add';
        $ret=D('Shop/Shops')->shop_account_option($auth_code);
        if($ret['status']!=1) {$this->error($ret['msg']);exit;}

        $postdata = I('post.');
        if($postdata['is_integral']!=1){
            $postdata['is_integral']=0;
        }
        $postdata['status']=1;
        $postdata['publish_wait']=0;//是否审核
        $postdata['shop_id']=$postdata['shop_ids']=MID;
        $postdata['addtime']=NOW_TIME;
        $postdata['goods_type'] = 4;
		
		if($postdata['spec_spec'] && $postdata['spec_price']){
			$service_spec_info = array();
			foreach($postdata['spec_spec'] as $k => $v){
				if($v && $postdata['spec_price'][$k]){
					$service_spec_info[$v] = $postdata['spec_price'][$k];
				}
			}unset($k,$v,$postdata['spec_spec'],$postdata['spec_price']);
			$postdata['service_spec'] = json_encode($service_spec_info);
		}
			
        $tab_id=$postdata['menu_tab'];
        $model = D('Admin/Goods');
		if(!$postdata['service_tostore'] && !$postdata['service_tohome']){
			$this->error('服务类型请至少选择一种');
		}
		if(!$postdata['service_tostore'])$postdata['service_tostore'] = 0;
		if(!$postdata['service_tohome'])$postdata['service_tohome'] = 0;
        if($tab_id=='service_baseinfo') {
            if (false === D('Goods')->create($postdata)) {
                $this->error(D('Goods')->getError());
            }
            $id = D('Goods')->add();
            if ($id !== false) {
                $postdata['id'] = $id;
                // $model->update_goods_sn($postdata, 1);//更新货号
                $model->update_service_sn($postdata);
                $model->update_goods_content($postdata, 1);//更新商品详情和seo
                unset($postdata);
                if ($_POST['isajax']) $this->assign('dialog', '1');
                $jumpUrl = $_POST['forward'] ? $_POST['forward'] : U(CONTROLLER_NAME . '/service');
                $this->assign('jumpUrl', $jumpUrl);
                $this->success('添加成功',$jumpUrl);
            } else {
                $this->error('添加失败' . ': ' . $model->getDbError());
            }
        }
    }
    /**
     * 修改服务
     * @param string $model
     * @param string $data
     * @param string $where
     * @param string $msg
     */
    public function service_update($model = '', $data = '', $where = '1', $msg = ''){
         $auth_code = 'service_edit';
        $ret=D('Shop/Shops')->shop_account_option($auth_code);
        if($ret['status']!=1) {$this->error($ret['msg']);exit;}

        $model = D('Admin/Goods');
        $postdata = I('post.');
        if($postdata['is_integral']!=1){
            $postdata['is_integral']=0;
        }
		if(!$postdata['service_tostore'] && !$postdata['service_tohome']){
			$this->error('服务类型请至少选择一种');
		}
		
		if($postdata['spec_spec'] && $postdata['spec_price']){
			$service_spec_info = array();
			foreach($postdata['spec_spec'] as $k => $v){
				if($v && $postdata['spec_price'][$k]){
					$service_spec_info[$v] = $postdata['spec_price'][$k];
				}
			}unset($k,$v,$postdata['spec_spec'],$postdata['spec_price']);
			$postdata['service_spec'] = json_encode($service_spec_info);
		}
		
		if(!$postdata['service_tostore'])$postdata['service_tostore'] = 0;
		if(!$postdata['service_tohome'])$postdata['service_tohome'] = 0;
        $postdata['updatetime']=NOW_TIME;
        $id = array_unique((array)I('id', 0));
        // print_r($id);exit;
        $shop_id=idtoname($id['0'],'Goods','shop_ids','id',false);
		// $s_ids = array_filter(explode(',', $shop_id));
		// echo "<pre>";print_r($a);exit;
        if($shop_id != MID)$this->error('无此操作权限');
        $id = is_array($id) ? implode(',', $id) : $id;
        $where = array_merge(array('id' => array('in', $id)), (array)$where);
        $jumpUrl = $_POST['forward'] ? $_POST['forward'] : U(CONTROLLER_NAME . '/service');
        $msg = array_merge(array('success' => L('edit_ok'), 'error' => L('edit_error'), 'url' => $jumpUrl, 'ajax' => IS_AJAX), (array)$msg);
        $tab_id=$postdata['menu_tab'];
        $savedata['status']=1;
        $savedata['publish_wait']=$postdata['publish_wait'];
        D('Goods')->where($where)->data($savedata)->save();
        $data = D('Goods')->create($postdata);
        if (D('Goods')->where($where)->save($data) !== false) {
            $postdata['id'] = $id;
            // $model->update_goods_sn($postdata);//更新货号
            $model->update_service_sn($postdata);//更新货号
            $model->update_goods_content($postdata);//更新商品详情和seo
            clearhomehtml($id);//更新静态缓存
            unset($data, $postdata, $newgoodscat, $newgoodsimg, $goodstype, $goodstypearr, $newgoodsattr);
            $this->success($msg['success'], $msg['url'], $msg['ajax']);
        } else {
            $this->error($msg['error'], $msg['url'], $msg['ajax']);
        }
        
    }
    public function getSeviceCat(){
        $serviceCat = M('ServiceCategory')->where('status=1')->field('id,name')->select();
        if ($serviceCat) {
            $serviceCat = format_array2select($serviceCat); 
        }
        $this->assign('serviceCat', $serviceCat);
    }
	/**
     * 添加套餐
     */
    public function package_add(){
		$return=D('Shops')->option(5,STYPE);
		if($return == 0){
			$this->error('您还没添加套餐的权限，请联系管理员！');
		}
        $tab_id=I('param.tabid');
        $tab_id=empty($tab_id)?'package_baseinfo':$tab_id;
        if($tab_id=='package_baseinfo'){
            $basedefault = array('moreimg' => '', 'moreimgstr' => '', 'morecatarr' => '', 'morecatid' => '', 'configstr' => '');
            $this->assign($basedefault);
            $this->get_member_price();//会员价
        }
        $postdata['publish_wait'] = 0;
        $postdata['shop_id']=MID;
        $serviceCat = M('ServiceCategory')->where('status=1')->field('id,name')->select();
		$this->getService();
        $this->assign($postdata);
        $this->assign('menu_tab',$tab_id);
        $this->assign('menu_action_current','package');
        $this->display($tab_id);
    }
	/**
     * 修改套餐
     */
	public function package_edit(){
		$tab_id=I('param.tabid');
        $id = I('get.id');
        if (!$id) $this->error(L('PARAM_ERR'));
        $map['shop_id']=MID;
        $map['id']=$id;
        $info = M('Goods')->where($map)->field(true)->find();
        if(!$info)$this->error('无此操作权限');
		$info['contain_service'] = json_decode($info['contain_service'],true);
		$info['contain'] = $info['contain_service'];
		foreach($info['contain_service'] as $k=>$v){
			$info['contain_service'][$k] = idtoname($k,'Goods','goods_name')."(".idtoname($k,'Goods','shop_price').")(".$v."次)";
		}unset($k,$v);
		$info['check'] =implode(',',array_keys($info['contain_service']));
		
        //获取商品的长字段
        $goodscontent = M('GoodsContent')->where('goods_id = ' . $id)->find();
        $info['content'] = $goodscontent['content'];
        $this->assign($info);
        $this->getService();
        $this->assign('menu_tab',$tab_id);
        $this->assign('menu_action_current','package');
        $this->display('package_baseinfo');
	}
	/**
     * 插入套餐
     */
	public function package_insert(){
		$model = M('Goods');
		$postdata=I('param.');
		foreach($postdata['service'] as $k=>$v){
			$postdata['contain_service'][$v] = $postdata['nums'][$v]; 
		}unset($postdata['service'],$postdata['nums']);
		// if($postdata['shop_ids'])$postdata['shop_ids'] = ','.implode(',',$postdata['shop_ids']).',';
		$postdata['shop_ids'] = ','.MID.',';
		$postdata['shop_id'] = MID;
		$postdata['contain_service'] = json_encode($postdata['contain_service']);
		$postdata['continued'] = intval($postdata['continued']);
		$postdata['shop_price'] = $postdata['market_price'];
		$postdata['addtime'] = NOW_TIME;
		$postdata['publish_wait'] = 1;
		$postdata['status'] = 1;
		$postdata['goods_type'] = 6;
        $postdata['is_integral'] = 0;
		$map['goods_name'] = $postdata['goods_name'];
		$map['goods_type'] = 6;
		$count = $model->where($map)->count();
		if($count){
			$this->error('套餐名称重复');
		}
		$id = $model->add($postdata);
		$content['goods_id'] = $id;
		$content['content'] = $postdata['content'];
		M('GoodsContent')->add($content);
		if($id){
			$jumpUrl = $_POST['forward'] ? $_POST['forward'] : U(CONTROLLER_NAME . '/package');
			$this->assign('jumpUrl', $jumpUrl);
			$this->success('添加成功',$jumpUrl);
		}else{
			$this->error('添加失败');
		}
	}
	public function package_update(){
		$model = M('Goods');
		$postdata=I('param.');
		// echo "<pre>";
		// print_r($postdata);exit;
		foreach($postdata['service'] as $k=>$v){
			$postdata['contain_service'][$v] = $postdata['nums'][$v]; 
		}unset($postdata['service'],$postdata['nums']);
		$postdata['contain_service'] = json_encode($postdata['contain_service']);
		
		$postdata['shop_price'] = $postdata['market_price'];
		$postdata['continued'] = intval($postdata['continued']);
		$postdata['updatetime'] = NOW_TIME;
		$postdata['status'] = 1;
        $postdata['is_integral'] = 0;
		$postdata['publish_wait'] = 1;
		$map['goods_name'] = $postdata['goods_name'];
		$map['id'] = array('neq',$id);
		$count = $model->where($map)->count();
		if($count){
			$this->error('套餐名称重复');
		}
		$id = $model->save($postdata);
		$content['content'] = $postdata['content'];
		$where['goods_id'] = $postdata['id'];
		M('GoodsContent')->where($where)->save($content);
		if($id){
			$jumpUrl = $_POST['forward'] ? $_POST['forward'] : U(CONTROLLER_NAME . '/package');
            $this->assign('jumpUrl', $jumpUrl);
            $this->success('编辑成功',$jumpUrl);
		}else{
			$this->error('编辑失败');
		}
	}
	/**
     * 服务查询
     */
	private function getService(){
		$map = array();
		$map['goods_type'] = 4;
		$map['status'] = 1;
		$map['shop_id'] = MID;
		$map['is_delete'] = 0;
		$serviceData = M('Goods')->where($map)->field('id,goods_name,shop_price')->select();
		$this->assign('serviceData',$serviceData);
	}
	
	public function service(){

         $auth_code = 'service_list';
        $ret=D('Shop/Shops')->shop_account_option($auth_code);
        if($ret['status']!=1) {$this->error($ret['msg']);exit;}

        $name = 'Goods';
		$tabid = I('param.tabid');
        if (!empty($tabid)) $this->display($tabid);
        else{
            $postdata = I('param.');
            $map['is_delete'] = 0;
            $map['goods_type'] = 4;
			$map['_string'] = "shop_ids = ".MID." OR shop_ids='0'";
            if($postdata['catid'])$map['cat_id'] = $postdata['catid'];
            $keyword = $postdata['keyword'];
            if(!empty($keyword)){
                $whereor['id']=array('like','%'.$keyword.'%');
                $whereor['goods_sn']=array('like','%'.$keyword.'%');
                $whereor['goods_name']=array('like','%'.$keyword.'%');
                $whereor['_logic'] = 'or';
                $map['_complex'] = $whereor;
                $seotitle=$keyword.'_';
            }
            $this->getSeviceCat();
            $list = $this->lists($name, $map);
			foreach($list as $k=>$v){
				if($v['shop_id'] === MID){
					$list[$k]['s_edit'] = 1;
				}
				if($v['shop_ids'] === MID){
					$list[$k]['s_shop'] = 1;
				}
			}unset($k,$v);
            $this->assign('list', $list);
            $this->assign($postdata);
            $this->display();
        }
	}
	public function package(){
		$name = M('Goods');
		$map = array();
		$map['goods_type'] = 6;
        $postdata = I('param.');
		$keyword = $postdata['keyword'];
        if(!empty($keyword)){
            $map['name']=array('like','%'.$keyword.'%');
		}
		if(!empty($postdata['reg_from']))$map['addtime'][]=array('EGT',strtotime($postdata['reg_from']));
		if(!empty($postdata['reg_to']))$map['addtime'][]=array('elt',strtotime($postdata['reg_to']));
		$shop_ids = ','.MID.',';
		$map['is_delete'] = 0;
		$map['goods_type'] = 6;
		$map['_string'] = "shop_ids like '%".$shop_ids."%' OR shop_ids='0'";
        $list = $this->lists($name, $map);
		foreach($list as $k=>$v){
			$list[$k]['contain_service'] = json_decode($v['contain_service'],true);
		}
		foreach($list as $k=>$v){
			if($v['shop_id'] === MID){
				$list[$k]['s_edit'] = 1;
				$list[$k]['s_shop'] = 1;
			}
		}unset($k,$v);
        $this->assign('list', $list);
        $this->assign($postdata);
        $this->display();
	}
	//套餐发放
    public function package_send(){
		//权限
		$return=D('Shops')->option(6,STYPE);
		$this->assign('return',$return);
		
        $postdata = I('param.');
        $where = array();
        $keyword = $postdata['keyword'];
        if(!empty($keyword)){
            $whereor['member_card']=array('like','%'.$keyword.'%');
            $whereor['member_name']=array('like','%'.$keyword.'%');
            $whereor['member_mobile']=array('like','%'.$keyword.'%');
            $whereor['_logic'] = 'or';
            $where['_complex'] = $whereor;
		}
        if(!empty($postdata['reg_from']))$where['add_time'][]=array('EGT',strtotime($postdata['reg_from']));
		if(!empty($postdata['reg_to']))$where['add_time'][]=array('elt',strtotime($postdata['reg_to']));
        if($postdata['package_id'])$where['package_id'] = array('eq',$postdata['package_id']);
        $where['send_shop'] = MID;
        $list = $this->lists('PackagesendLog',$where);
        $pscount = M('PackagesendLog')->where($where)->count();
        $this->assign('pscount',$pscount);
        $this->assign('list',$list);
		$this->assign($postdata);
        $this->assign('p_log',$p_log);
    	$map = array();
        // $map['shop_ids'] = ','.MID.',';
		$shop_ids = ','.MID.',';
		$map['status'] = 1;
        $map['goods_type'] = 6;
        $map['is_delete'] = 0;
		$map['_string'] = "shop_ids like '%".$shop_ids."%' OR shop_ids='0'";
		$packageData = M('Goods')->where($map)->field('id,goods_name,shop_price')->select();
		foreach ($packageData as $v) {
			$newpackageData[$v['id']] = $v['goods_name']."(".$v['shop_price']."元)";
		}$packageData=$newpackageData;
		$this->assign('packageData',$packageData);
		$this->display();
    }
    public function get_pdata(){
    	$id = I('param.id');
		$return['status'] = 0;
		
		if(!$id){
			$return['info'] = '请选择套餐';
			$this->ajaxReturn($return);
		}
		$map['id'] = $id;
		$info = M('Package')->field(true)->where($map)->find();
		if($info){
			$info['service'] = '';
			$info['contain_service'] = json_decode($info['contain_service'],true);
			foreach ($info['contain_service'] as $key => $value) {
				$s_id = idtoname($key,'Goods','shop_id','id',false);
				if($s_id){
					$s_name = idtoname($s_id,'Shops','name','id',false);
				}else{
					$s_name = '全店通用';
				}
				
				$info['service'] .= idtoname($key,'Goods','goods_name','id',false).'('.$value.'次)--'.$s_name.' &nbsp;&nbsp;';
			}
			$return['status'] = 1;
			$return['data'] = $info;
		}else{
			$return['info'] = '操作错误';
		}
		$this->ajaxReturn($return);
    }
	/**
      *套餐发放
      */
	public function sub_packagesend(){
		$postdata = I('param.');
		$return=D('Shops')->option(6,STYPE);
		if($return == 0){
			$this->error('您还没有发放套餐的权限，请联系管理员！');
			$tabid = 'index';
		}
        // $data = D('Common/Shops')->sub_packagesend($postdata);
		$this->ajaxReturn($data);
	}
}
?>