<?php
/**
 * 外卖管理
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaol <1094186793@qq.com>
 */
 
namespace Shop\Controller;
use Think\Controller;
class TakeoutController extends BaseController {
    public function _initialize(){
        parent::_initialize();
        if(!checksiteauth('WaiMai')){ exit;}
        $shops_info=session('shops_info');
        if(empty($shops_info)) $this->error('身份过期，请重新登录',U('Shop/Register/shop_login'));
		$this->mendian();
    }

    /**
     * 外卖门店列表
     */
    public function index(){
        $shops_info=session('shops_info');
		
		$shop_id = $shops_info['shop_id'];
		if(empty($shop_id)){$this->error('参数错误！');}
		if($this->shops_info['pid'] != 0){
			$this->error('您对此没有权限，请更换有权限的账户登录！');
		}
		$s_map = array();
		$s_map['shop_id'] = $shop_id;
		$s_map['pid'] = 0;
		$s_info=M('ShopsAccount')->where($s_map)->field('id,description')->find();
		$this->assign($s_info);
		$this->get_shipping_info($shop_id);
		$this->get_bagging_info($shop_id);
		// $this->get_location_takeout_label($shop_id);
		
        $this->display('setting');
    }
	
    /**
     * 获取运费设置
     * @param $shop_id  门店id，使用方法前先判断好权限
     */
    private function get_shipping_info($shop_id){
        $where=array();
		$where['shop_id']=$shop_id;
        $ShopsDelivery=M('ShopsDelivery')->where($where)->field('start_price,scale,delivery_price')->select();
        if (!empty($ShopsDelivery)) {
            foreach ($ShopsDelivery as $v) {
                $moreimgarr['start_price'][] = $v['start_price'];
                $moreimgarr['scale'][] = $v['scale'];
                $moreimgarr['delivery_price'][] = $v['delivery_price'];
            }
            $moreshipstr = implode('', $moreimgarr['start_price']) . implode('', $moreimgarr['scale']) . implode('', $moreimgarr['delivery_price']);
        }
        $this->assign('shops_delivery', $ShopsDelivery);
        $this->assign('moreshipstr', md5($moreshipstr));
    }

    /**
     * 获取包装费
     * @param $shop_id 门店id，使用方法前先判断好权限
     */
    private function get_bagging_info($shop_id){
        $where=array();$where['shop_id']=$shop_id;
        $ShopsPackage=M('ShopsPackage')->where($where)->field('package_price,package_start_price,to_time')->find();
        $this->assign($ShopsPackage);
    }

    /**
     * 更新门店信息
     */
    public function update_setting(){
		$shops_info=session('shops_info');
		$shop_id = $shops_info['shop_id'];
		
		$name = 'ShopsAccount';
        $model = D('Shop/ShopsAccount');
        $postdata = I('post.');	
        $data = M($name)->create($postdata);

        $jumpUrl = I('forward') ? I('forward') : U(CONTROLLER_NAME . '/index');
		$id = array_unique((array)I('id', 0));
        $id = is_array($id) ? implode(',', $id) : $id;
		
        if(empty($shop_id)){
			$this->error('参数错误！');
		}
        if($shops_info['pid'] != 0){
            $this->error('您对此没有权限，请更换有权限的账户登录！');
        }
        
		$where = array_merge(array('id' => array('in', $id)), (array)$where);
        $msg = array_merge(array('success' => L('edit_ok'), 'error' => L('edit_error'), 'url' => $jumpUrl, 'ajax' => IS_AJAX), (array)$msg);
        if (M($name)->where($where)->save($data) !== false) {
            $postdata['shop_id'] = $shop_id;
            $model->update_shipping_info($postdata);//更新配送信息
            $model->update_bagging_info($postdata);//更新包装费信息
            unset($data, $postdata);
            $this->success($msg['success'], $msg['url'], $msg['ajax']);
        } else {
            $this->error($msg['error'], $msg['url'], $msg['ajax']);
        }
    }
	
	
	

    /**
     * 外卖分类
     */
    public function cate(){
        $tabid=I('tabid');
        if($tabid=='add_cate'){
            $this->get_location();
            $this->assign('shop_id',MID);
            $tabid='edit_cate';
        } elseif($tabid=='edit_cate'){
            $id=I('id');$where=array();$where['id']=$id;
            $shop_cate_info=M('ShopsCategory')->where($where)->field(true)->find();
            $this->assign($shop_cate_info);
            $this->get_location();
        } else {
            $map = array();
            $map['shop_id'] = MID;
            $list = page_list('ShopsCategory', $map);
            $this->assign($list);
            $tabid='cate';
        }
        $this->assign('menu_tab','cate');
        $this->assign('menu_action_current','cate');
        $this->display($tabid);
    }
	/**
     * shops_category表外卖分类上下架
     */
    public function cate_status(){
        $model = D('ShopsCategory');
		$id     = intval(I('id'));
        $type	= I('type');
		
        $values = $model->where('id='.$id)->field($type)->find();
        $data[$type]=($values[$type]+1)%2;
        $res=$model->where('id='.$id)->save($data);
        $this->ajaxReturn($data[$type]);
    }
    private function get_location(){
        $where = array();
		$where['shop_id']=MID;
		$where['status']=1;
        $where['pid']=0;
        $shops_account = M('ShopsAccount')->where($where)->field('id,name')->select();
        $account_arr = format_array2select($shops_account, 'name');
        $this->assign('account_arr', $account_arr);
    }

    public function insert_cate(){
        $name='ShopsCategory';
        $model = D($name);
        $postdata = I('post.');
        if (false === $model->create($postdata)) {
            $this->error($model->getError());
        }
        $id = $model->add();
        if ($id !== false) {
            $jumpUrl = $_POST['forward'] ? $_POST['forward'] : U('Takeout/cate');
            $this->assign('jumpUrl', $jumpUrl);
            $this->success(L('ADD_OK'));
        } else {
            unset($postdata);$this->error(L('ADD_ERROR') . ': ' . $model->getDbError());
        }
    }
    public function update_cate(){
        $name='ShopsCategory';
        $model = D($name);
        $postdata = I('post.');
        $data = $model->create($postdata);
        $jumpUrl = I('forward') ? I('forward') : U('Takeout/cate');

		$where['id'] = I('id');
        $where['shop_id'] = MID;
        $msg = array_merge(array('success' => L('edit_ok'), 'error' => L('edit_error'), 'url' => $jumpUrl, 'ajax' => IS_AJAX), (array)$msg);
        if ($model->where($where)->save($data) !== false) {
            $this->success($msg['success'], $msg['url'], $msg['ajax']);
        } else {
            unset($postdata);
            $this->error($msg['error'], $msg['url'], $msg['ajax']);
        }
    }
    public function delete_shops_cate(){
        $id=I('id');
		$where=array();
		$where['id']=$id;
		$where['shop_id']=MID;
        $count=M('ShopsCategory')->where($where)->delete();
        if($count){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }

    /**
     * 某个商户的外卖商品管理列表及搜索
     */
    public function goods()
    {
        $tabid=I('tabid');
        $name = 'Goods';
        $postdata = I('param.');
        if($tabid=='checking'){//审核的商户外卖商品
            $postdata['is_delete'] = 0;
            $postdata['publish_wait'] = array('neq', 1);
            $postdata['shop_id']=MID;
            $map = D('Shop/'.$name)->takeout_index_condition($postdata);
            $map_account=array();
            if($this->shops_info['is_main']!=1){
                $map_account = D('Shop/'.$name)->get_map_account(3,$this->shops_info['shop_ids']);
            }
            $map=array_merge($map,$map_account);
            $list = $this->lists($name, $map);
            $this->assign('list', $list);
            $this->getTakeoutCategory($postdata['cat_id']);
            $this->getTakeoutShopsCategory();
            $this->assign($postdata);
            $this->assign('menu_tab','checking');
            $this->assign('menu_action_current','goods');
        } elseif($tabid=='recover'){//回收站的商户外卖商品
            if (!isset($postdata['shops_keyword'])) {
                $postdata['shops_keyword'] = '';
            }
            $postdata['is_delete'] = 1;
            $postdata['shop_id']=MID;
            $map = D('Shop/'.$name)->takeout_index_condition($postdata);
            $map_account=array();
            if($this->shops_info['is_main']!=1){
                $map_account = D('Shop/'.$name)->get_map_account(3,$this->shops_info['shop_ids']);
            }
            $map=array_merge($map,$map_account);
            $list = $this->lists($name, $map);
            $this->assign('list', $list);
            $this->getTakeoutCategory($postdata['cat_id']);
            $this->getTakeoutShopsCategory();
            $this->assign($postdata);
            $this->assign('menu_tab','recover');
            $this->assign('menu_action_current','goods');
        } elseif($tabid=='add_goods'){//添加外卖商品
            $tabid='edit_goods';
            $this->get_takeout_label();
            $this->get_location();
            $this->getTakeoutCategory(0);
            $this->getTakeoutShopsCategory();
            $this->assign($postdata);
            $this->assign('menu_tab','goods');
            $this->assign('menu_action_current','goods');
        } elseif($tabid=='edit_goods'){//编辑外卖商品
            $map=array();$map['id']=$postdata['id'];
            $goods_info=M($name)->field(true)->where($map)->find();
            $this->assign($goods_info);
            $this->get_takeout_label();
            $this->get_location();
            $this->get_takeout_label_id($goods_info['id']);
            $this->get_shop_id($goods_info['id']);
            $this->getTakeoutCategory($goods_info['cat_id']);
            $this->getTakeoutShopsCategory();
            $this->assign($postdata);
            $this->assign('menu_tab','goods');
            $this->assign('menu_action_current','goods');
        } else {//某个商户的外卖商品管理列表及搜索
            $tabid='goods';
            $postdata['is_delete'] = 0;
            $postdata['publish_wait'] = 1;
            $postdata['shop_id']=MID;
            $map = D('Shop/'.$name)->takeout_index_condition($postdata);
            $map_account=array();
            if($this->shops_info['is_main']!=1){
                $map_account = D('Shop/'.$name)->get_map_account(3,$this->shops_info['shop_ids']);
            }
            $map=array_merge($map,$map_account);
            $list = $this->lists($name, $map);
            $this->assign('list', $list);
            $this->getTakeoutCategory($postdata['cat_id']);
            $this->getTakeoutShopsCategory();
            $this->assign($postdata);
            $this->assign('menu_tab','goods');
            $this->assign('menu_action_current','goods');
        }
        $this->display($tabid);
    }

    /**
     * 取商户可以用的外卖分类
     */
    private function getTakeoutCategory($id){
        $where=$whereor=$map=array();
        $map['shop_id']=MID;$map['type']=4;$map['status']=array('in','2,4');
        $pid=M('ShopsCateLink')->where($map)->getField('cat_id',true);
        if(!empty($pid)) {
            $whereor['id'] = array('in', $pid);
            $whereor['pid'] = array('in', $pid);
            $whereor['_logic'] = 'or';
            $where['_complex'] = $whereor;
            $GoodsCate = M('TakeoutCategory')->where($where)->field('id,pid,name')->select();
            $Tree = new \Common\Vendor\Tree();
            $select_categorys = '';
            $treemini = $Tree->treemini($GoodsCate);
            $select_categorys .= $Tree->treeminioption($treemini, $id);
            $this->assign('cate_option', $select_categorys);
        }
    }

    /**
     * 取商户下的外卖分类
     */
    private function getTakeoutShopsCategory(){
        $where=array();$where['shop_id']=MID;
        $GoodsCate=M('TakeoutShopsCategory')->where($where)->field('id,name')->select();
        $this->assign('goodscate_option',$GoodsCate);
    }

    /**
     * 取到所有外卖标签
     */
    private function get_takeout_label(){
        $where=array();$where['status']=1;
        $TakeoutLabel=M('TakeoutLabel')->where($where)->field('id,name')->select();
        $takeout_label_option = format_array2select($TakeoutLabel, 'name');
        $this->assign('takeout_label_option',$takeout_label_option);
    }

    /**
     * 取到商品所属的外卖门店
     * @param $id
     */
    private function get_shop_id($id){
        if (!empty($id)) {
            $where = $goods_location_link = array();$where['goods_id']=$id;
            if($this->shops_info['is_main']!=1){
                $shop_ids=$this->shops_info['shop_ids'];
                $shop_ids=array_filter($shop_ids);
                if(!empty($shop_ids)){$where['shop_id']=array('in',$shop_ids);}
                else{$where['shop_id']=0;}
            }
            $shops_location = M('GoodsLocationLink')->where($where)->field('goods_id,shop_id')->select();
            if (!empty($shops_location)) {
                foreach ($shops_location as $key => $val) {
                    $goods_location_link[$key] = $val['shop_id'];
                }
            }
            $select_location_str = implode(',', $goods_location_link);
            $this->assign('select_location_str', $select_location_str);
            $selectlocationstr = md5($select_location_str);
            $this->assign('selectlocationstr', $selectlocationstr);
        }
    }

    /**
     * 取到商品的外卖标签
     * @param $id
     */
    private function get_takeout_label_id($id){
        if (!empty($id)) {
            $where = $label_link = array();$where['goods_id']=$id;
            $label = M('TakeoutLabelLink')->where($where)->field('goods_id,label_id')->select();
            if (!empty($label)) {
                foreach ($label as $key => $val) {
                    $label_link[$key] = $val['label_id'];
                }
            }
            $select_label_str = implode(',', $label_link);
            $this->assign('select_label_str', $select_label_str);
            $selectlabel_str = md5($select_label_str);
            $this->assign('selectlabel_str', $selectlabel_str);
        }
    }

    /**
     * 插入商品
     */
    public function insert_goods()
    {
        $name = 'Goods';$model = D($name);$shop_id=MID;
        $postdata = I('post.');$postdata['shop_id']=$shop_id;$postdata['type']=2;$postdata['publish_wait']=0;
        if (false === $model->create($postdata)) {
            $this->error($model->getError());
        }
        $id = $model->add();
        if ($id !== false) {
            $postdata['id'] = $id;
            $update_model=D('Shop/'.$name);
            $update_model->update_takeout_label($postdata, 1);//更新外卖标签
            $update_model->update_takeout_location($postdata, 1);//更新外卖门店
            unset($postdata);
            if ($_POST['isajax']) $this->assign('dialog', '1');
            $jumpUrl = $_POST['forward'] ? $_POST['forward'] : U('Takeout/goods',array('shop_id'=>$shop_id));
            $this->assign('jumpUrl', $jumpUrl);
            $this->success(L('ADD_OK'));
        } else {
            $this->error(L('ADD_ERROR') . ': ' . $model->getDbError());
        }
    }

    /**
     * 修改商品
     * @param string $model
     * @param string $data
     * @param string $where
     * @param string $msg
     */
    public function update_goods()
    {
        $name = 'Goods';$model = D($name);$shop_id=MID;
        $postdata = I('post.');$postdata['shop_id']=$shop_id;$postdata['type']=2;$postdata['publish_wait']=0;
        $data = $model->create($postdata);
        $jumpUrl = I('forward') ? I('forward') : U('Takeout/goods',array('shop_id'=>$shop_id));
        $id = array_unique((array)I('id', 0));
        $id = is_array($id) ? implode(',', $id) : $id;
        $where = array_merge(array('id' => array('in', $id)), (array)$where);
        $msg = array_merge(array('success' => L('edit_ok'), 'error' => L('edit_error'), 'url' => $jumpUrl, 'ajax' => IS_AJAX), (array)$msg);
        if ($model->where($where)->save($data) !== false) {
            $postdata['id'] = $id;$update_model=D('Shop/'.$name);
            $update_model->update_takeout_label($postdata);//更新外卖标签
            $update_model->update_takeout_location($postdata);//更新外卖门店
            unset($data, $postdata);
            $this->success($msg['success'], $msg['url'], $msg['ajax']);
        } else {
            $this->error($msg['error'], $msg['url'], $msg['ajax']);
        }
    }
}
?>