<?php
namespace Smi\Controller;
use Think\Controller;
use Think\Log;
header("Content-type:text/html;charset=utf-8");
class BusinessController extends BaseController 
{
    protected $dada;// 达达配送实例
	/**
	 * 商户列表
	 */
	public function index()
	{	
		$count = M('admin')
				->field('am_admin.id, username, picture, business_name, business_address, am_admin.create_time, groupname')
				->join('am_group on am_admin.group_id = am_group.id')
				->where('am_admin.is_business = 1')
				->count();//总记录数
		$page = new \Think\Page($count, 15);
		$show = $page->show();//分页显示输出
		$list =	M('admin')
				->field('am_admin.id, username, picture, business_name, business_address, business_phone, am_admin.create_time, groupname, am_admin.status')
				->join('am_group on am_admin.group_id = am_group.id')
				->where('am_admin.is_business = 1')
				->order('am_admin.create_time DESC')
				->limit($page->firstRow . ',' . $page->listRows)
				->select();
		$this->assign('page', $show);// 赋值分页输出
        $this->assign("list", $list);//定义变量并显示模板
        $this->display();
	}

	/**
	 * 编辑商户
	 */
	public function edit($id = '')
	{
		if ($_POST) {
            // 检测商户地址格式非法性
            $matchs = array();
            $address_preg = '/^([\x7f-\xff]+省)?([\x7f-\xff]+市)([\x7f-\xff]+区|县)([\x7f-\xff_a-zA-Z0-9]+)$/';
            preg_match($address_preg, $_POST['business_address'], $matchs);
            if (empty($matchs[2]) || empty($matchs[3]) || empty($matchs[4])) {
                $this->error('Merchant address entry is illegal!');die;  
            }

            $result = $this->saveForm($_POST);
			if ($result) {
                $this->success('Edit success');die;
                
            } else {
                $this->error('Edit failure');die;
            }
		}

		$group_list = M('group')->field('id, groupname')->where(array('status' => 1))->select();// 权限组
		$data = I();
		$item = M('admin')->where(array('id' => $id))->find();// 商户信息
        // dump($item);die;
		$this->assign('item', $item);
		$this->assign('group_list', $group_list);
		$this->display('add');
	}

    /**
     * 保存表单
     */
    private function saveForm($data)
    {
//        $data = $_REQUEST;
        $is_set_id = isset($data['id']) && !empty($data['id']) ? true : false;
        if ($is_set_id) {
            $delFile = M('admin')->where(array('id' => $data['id']))->getField("picture");
        }
        if ($_FILES['picture']['error'] == 0) {
            $upload = new \Think\Upload();    // 实例化上传类
            // $upload->maxSize = 3145728 ;    // 设置附件上传大小
            // 设置附件上传类型
            $upload->exts = array('jpg', 'gif', 'png', 'jpeg');
            $upload->rootPath = './Uploads/';    // 设置附件上传根目录
            $upload->savePath = 'admin_busisness/';    // 设置附件上传目录
            $upload->autoSub = false;    //不要子文件夹
            // 上传文件
            $info = $upload->upload();

            if(!$info) {
                // 上传错误提示错误信息
                if ($is_set_id) {
                    $this->error($upload->getError(), U('edit', array('id' => $data['id'])));die;
                }
                $this->error($upload->getError());die;

            }else{
                // 上传成功 获取上传文件信息
                $pic = $info['picture']["savepath"] . $info['picture']["savename"];
                $data['picture'] = $pic;    // 修改数据对象
            }
        } else {
            // echo 111;die;
            if ($is_set_id && empty($delFile)) {
                // alertMsg("请上传图片", U('edit', array('id' => $data['id'])));
                $this->error('Please upload pictures', U('edit', array('id' => $data['id'])));die;
            } elseif (empty($is_set_id)) {
                // alertMsg("请上传图片", U('add'));
                $this->error('Please upload pictures');die;
            }
        }
        if (!$is_set_id) {
            $data['create_time'] = time();
            $data['password'] = md5($data['password']);
            $data['create_ip'] = $_SERVER['REMOTE_ADDR'];
            $data['is_business'] = 1;
            $result = M('admin')->add($data);
        } else {
            $data['edit_ip'] = $_SERVER['REMOTE_ADDR'];
            $data['edit_time'] = time();
            $result = M('admin')->save($data);
            if ($result && isset($data['picture'])) {
                @unlink("./Uploads/{$delFile}");    // 删除旧图
            }
        }
        return $result;
    }

	/**
	 * 新建商户
	 */
	public function add()
	{	
		if ($_POST) {
            $username= $_POST['username'];

            $user=M('admin')->where('username="'.$username.'"')->find();
            if($user!=''||$user!=null){
                $this->error('User name already exists, save failed!');die;
            }

            // 检测商户地址格式非法性
            $matchs = array();
            $address_preg = '/^([\x7f-\xff]+省)?([\x7f-\xff]+市)([\x7f-\xff]+区|县)([\x7f-\xff_a-zA-Z0-9]+)$/';
            preg_match($address_preg, $_POST['business_address'], $matchs);
            if (empty($matchs[2]) || empty($matchs[3]) || empty($matchs[4])) {
                $this->error('Merchant address entry is illegal!');die;  
            } 

			$result = $this->saveForm($_POST);
			if ($result) {
               $this->success('Save success');die;
            } else {
                $this->error('Save failed');die;
            }
		}

		$group_list = M('group')->field('id, groupname')->where(array('status' => 1))->select();// 权限组
		$this->assign('group_list', $group_list);
		$this->display();
	}

	/**
	 * 删除商户
	 */
	public function delete($id = '')
	{
		if (M('admin')->delete($id)) {
			// alertMsg("删除成功", U('index'));
			$this->success('Delete the success');
		} else {
			// alertMsg('删除失败', U('index'));
			$this->error('Delete failed');
		}
	}

    /**
     * 微信配置
     */
    public function wechat_config($admin_id)
    {
        if ($_POST) {
            $info = M('wechat_config')->where(array('admin_id' => $_POST['admin_id']))->find();
            if (empty($info)) {
                $_POST['create_time'] = time();
                
                if (M('wechat_config')->add($_POST)) {
                    $this->success('Save success');die;
                } else {
                    $this->error('Save failed');die;
                }
            } else {
                $_POST['edit_time'] = time();
                $result = M('wechat_config')->where(array('admin_id' => $_POST['admin_id']))->save($_POST);
                if ($result) {
                    $this->success('The update is successful');die;
                } else {
                    $this->error('Update failed');die;
                }
            }
        }

        $config = M('wechat_config')->where(array('admin_id' => $admin_id))->find();

        $this->assign('config', $config);
        $this->display();
    }
}