<?php
namespace Wechat\Controller;

use Think\Controller;
header('Access-Control-Allow-Origin:*');
header("Content-Type:text/html/json;charset=utf-8");
class ApiController extends Controller {
	/**
	 * 入驻申请
	 */
	public function StoreEnter()
	{
        set_time_limit(0);
		$datas['openid']    = $_POST['openid']?:cookie("openid");
		$datas['county_id'] = $_POST['county_id'];
		$datas['contact']   = I("contact");
		$datas['mobile']    = I("mobile");
		$datas['address']   = I("address");
		$datas['business_licence'] = $_POST['business_licence'];
		$datas['fcc']	    = $_POST['fcc'];
		$datas['name']      = I("name");
		$datas['logo']      = $_POST['logo'];
		if ($this->dataCheck($datas['openid'])) {
			$data = array("status" => -1, "msg" => "openid有误");
		} elseif ($this->dataCheck($datas['county_id'])) {
			$data = array('status' => -1, "msg" => "所属区有误");
		} elseif ($this->dataCheck($datas['contact'])) {
			$data = array('status' => -1, "msg" => "姓名有误");
		} elseif ($this->dataCheck($datas['mobile'])) {
			$data = array('status' => -1, "msg" => "手机有误");
		} elseif ($this->dataCheck($datas['address'])) {
			$data = array('status' => -1, "msg" => "地址有误");
		} elseif ($this->dataCheck($datas['business_licence'])) {
			$data = array('status' => -1, "msg" => "营业执照有误");
		} elseif ($this->dataCheck($datas['fcc'])) {
			$data = array('status' => -1, "msg" => "食品流通证有误");
		} elseif ($this->dataCheck($datas['name'])) {
			$data = array('status' => -1, "msg" => "店名有误");
		} elseif ($this->dataCheck($datas['logo'])) {
			$data = array('status' => -1, "msg" => "LOGO有误");
		} else{
			// 业务代码
            $uid = M("users_oa")->where(array('openid' => $datas['openid']))->find();
			$datas['sn']   = "SE".$uid['uid'].date("YmdHis",time());
			$datas['create_time'] = time();
            $datas['business_licence'] = $this->doWechatPic($datas['business_licence']);
            $datas['fcc']  = $this->doWechatPic($datas['fcc']);
            $datas['logo'] = $this->doWechatPic($datas['logo']);
            $resadd = M("stores_enter")->add($datas);
			// 操作成功
            if ($resadd) {
               $data = array("status" => 1, "msg" => "申请成功");
            }else{
               $data = array("status" => -1, "msg" => "申请失败");
            }
		}
		apiReturn($data);
	}

    //获取所有订单
    public function getStoreOrderAll(){
        $openid = cookie("openid");
        $stores = M("stores")->where(array("openid"=>$openid))->find();
        if($stores){
            $order = M("order_city")
                    ->where(array("store_id" => $stores["id"]))
                    ->order("id desc")
                    ->field("id,order_sn,total_fee,create_time,expect_time,status")
                    ->select();
            if($order){             
                foreach ($order as $key => &$value) {
                    $good_id = M("order_city_good")->where(array("order_id" => $value['id']))->select();
                    foreach ($good_id as $k => $va) {
                        $good_name = M("stores_goods")->where(array("id" => $va['good_id']))->field("goods_name")->find();
                        $good_names .= $good_name['goods_name'];
                    }
                    $value['expect_time'] = date("Y-m-d H:i:s",$value['expect_time']);
                    $value['create_time'] = date("Y-m-d H:i:s",$value['create_time']);               
                    $value['goods_name'] = $good_names;
                    $good_names = "";
                }
                $data = $order; 
            }else{
                $data = array("status" => -1,"msg" => "没有订单");
            }
        }else{
            $data = array("status" => -1,"msg" => "openid有误");
        }
        apiReturn($data);
    }
    //获取订单详情
    public function getStoreOrderDetail(){
        $id       = $_GET['id'];
        $order_sn = $_GET['order_sn'];
        $order    = M("order_city")->where(array("id" => $id))->select();
        if($order){
            foreach ($order as $key => &$value) {
                $value['expect_time'] = date("Y-m-d H:i:s",$value['expect_time']);
                $value['create_time'] = date("Y-m-d H:i:s",$value['create_time']);
                $value['finish_time'] = date("Y-m-d H:i:s",$value['finish_time']);
            } 
            $openid   = M("stores")->where(array("id" => $order[0]['store_id']))->find();
            $storename= $openid['name'];
            $nickname = M("users_oa")->where(array("openid" => $openid['openid']))->find();
            $goods    = M("order_city_good")->where(array("order_id" => $order[0]['id']))->select();
            foreach ($goods as $k => &$va) {
                $good_name = M("stores_goods")->where(array("id" => $va['good_id']))->find();
                $va['goods_name'] = $good_name['goods_name'];
                $va['goods_price']= $good_name['goods_price'];
                $va['goods_img']  = $good_name['thumb'];
            }            
            $order = array("storename" => $storename,"nickname" => $nickname['nickname'],"order" => $order,"goods" => $goods);
            $data = $order;          
        }else{
            $data = array("status" => -1,"msg" => "订单id有误");
        }
        apiReturn($data);
    }
    /**
     * 商家处理订单 接单&拒绝
     * status：2接单 -2拒绝 1.待确认 2.待送货 3.已完成 -1.订单取消 -2.拒绝接单
     */
    public function handleStoreOrder(){
        $id     = $_GET['id'];
        $save['status'] = $_GET['status'];
        $save['reason'] = $_GET['reason'];       
        if ($this->dataCheck($id)){
            $datas = array("status" => -1,"msg" => "订单id有误"); 
        }elseif ($this->dataCheck($save['status'])) {
            $datas = array("status" => -1,"msg" => "订单状态有误");
        }elseif ($save['status'] == 2) {
            $result = M("order_city")->where(array("id" => $id))->field("status")->save($save);
            if($result){
                $datas = array("status" => 1,"msg" => "接单成功");

                $order = M("order_city")->where(array("id"=>$id))->find();
                $store = M("stores")->where(array("id"=>$order['store_id']))->find();
                //x 小程序发送模板消息  这里需要修正 模板ID，在配置文件修改 APPID & APP_SERECT ！！！
                vendor("WxPayPubHelper.WxPlugin");
                $WxPlugin = new \WxPlugin();
                $params['form_id']  = $order['form_id'];
                $params['touser']   = $order['openid'];
                $params['template_id'] = "-twe5IKusWg72ByKRL-nc4OH6yYpw6r8fYWCu6W9Tm8";
                $params['url']      = "http://" . $_SERVER['HTTP_HOST'] . U("");
                $params['data']     = array(
                    'first'    => array('value' => urlencode($store['name'].' 已接单'), 'color' => "#000000"),
                    'keyword1' => array('value' => urlencode($order['order_sn']), 'color' => '#000000'),
                    'keyword2' => array('value' => urlencode(date("Y-m-d H:i:s",$order['expect_time'])), 'color' => '#f35900'),
                    'keyword3' => array('value' => urlencode('商家专送'), 'color' => '#f35900'),
                    'remark'   => array('value' => urlencode(''), 'color' => '#000000')
                );
                $res = $WxPlugin->XcxSend($params);
                if ($res['status'] == -1) {
                    file_put_contents("./Logs/auditSuccess.log", JSON($res), FILE_APPEND);
                }

            }else{
                $datas = array("status" => -1,"msg" => "接单失败"); 
            }
        }elseif ($save['status'] == 3) {
            $save['finish_time'] = time();
            $result = M("order_city")->where(array("id" => $id))->field("status,finish_time")->save($save);
            if($result){
                $datas = array("status" => 1,"msg" => "订单已完成");
            }else{
                $datas = array("status" => -1,"msg" => "订单完成有误"); 
            }
        }elseif ($save['status'] == -1) {
            $result = M("order_city")->where(array("id" => $id))->field("status,reason")->save($save); 
            if($result){
                $datas = array("status" => 1,"msg" => "订单取消成功");
                $order = M("order_city")->where(array("id"=>$id))->find();

                //x 小程序发送模板消息  这里需要修正 模板ID，在配置文件修改 APPID & APP_SERECT ！！！
                vendor("WxPayPubHelper.WxPlugin");
                $WxPlugin = new \WxPlugin();
                $params['form_id']  = $order['form_id'];
                $params['touser']   = $order['openid'];
                $params['template_id'] = "ceOx4A6iRPYWCor1Zkd_7pXN3ijgKOr-jb-reM5ZOU4";
                $params['url']      = "http://" . $_SERVER['HTTP_HOST'] . U("");
                $params['data']     = array(
                    'first'    => array('value' => urlencode('订单已被取消'), 'color' => "#000000"),
                    'keyword1' => array('value' => urlencode($order['order_sn']), 'color' => '#000000'),
                    'keyword2' => array('value' => urlencode(date("Y-m-d H:i:s",time())), 'color' => '#f35900'),
                    'keyword3' => array('value' => urlencode($order['reason']), 'color' => '#f35900'),
                    'remark'   => array('value' => urlencode(''), 'color' => '#000000')
                );
                $res = $WxPlugin->XcxSend($params);
                if ($res['status'] == -1) {
                    file_put_contents("./Logs/auditSuccess.log", JSON($res), FILE_APPEND);
                }

            }else{
                $datas = array("status" => -1,"msg" => "订单取消失败"); 
            }    
        }elseif ($save['status'] == -2) { 
            $result = M("order_city")->where(array("id" => $id))->field("status,reason")->save($save); 
            if($result){
                $datas = array("status" => 1,"msg" => "订单拒绝成功");
            }else{
                $datas = array("status" => -1,"msg" => "订单拒绝失败"); 
            }
        }else {
            $datas = array("status" => -1,"msg" => "订单状态有误");
        }
        apiReturn($datas);
    }

    //获取营业状态
    public function getStoreStatus(){ 
        $openid = cookie("openid");
        $status = M("stores")->where(array("openid"=>$openid))->find();
        if ($status) {
            if ($status['status'] == 1) {
                $data  = array("status" => 1,"name" => $status["name"],"msg" => "营业中","logo" => $status['logo']);
            }else{
                $data  = array("status" => 2,"name" => $status["name"],"msg" => "休息中","logo" => $status['logo']);
            }            
        }else{
            $data  = array("status" => -1,"msg" => "openid有误");
        }
        apiReturn($data);
    }
    //修改营业状态
    public function updateStoreStatus(){
        $openid = cookie("openid");
        $status['status'] = $_GET['status'];
        $save   = M("stores")->where(array("openid" => $openid))->save($status);
        if($save){
            $data = array("status" => 1,"msg" => "营业状态修改成功");
        }else{
            $data = array("status" =>-1,"msg" => "营业状态修改失败");
        }
        apiReturn($data);
    }
    //获取营业有效期
    public function getStoresInvalidTime(){
        $openid = cookie("openid");
        $result = M("stores")->where(array("openid"=>$openid))->find();
        if($result){
           $invalidtime = date("Y-m-d",$result['invalid_time']);
           $datetoday   = date("Y-m-d");
           $date1       = strtotime($invalidtime);
           $date2       = strtotime($datetoday);
           $days        = round(($date1 - $date2)/3600/24);
           $data  = array("status" => 1,"invalid_time" => $invalidtime,"days" => $days);
        }else{
           $data  = array("status" =>-1,"msg" => "openid有误");
        }
        apiReturn($data);
    } 
    //获取续费明细   
    public function getStoresRenew(){
        $openid = cookie("openid");
        $stores = M("stores")->where(array("openid"=>$openid))->find();
        if ($stores) {
            $result = M("stores_renew")->where(array("store_id" => $stores['id']))->select();
            if($result){
                $data = $result;
                foreach ($data as $key => &$val) {
                    $val['continue_time'] = date("Y-m-d H:i:s",$val['continue_time']);
                    $val['exp_date']      = date("Y-m-d H:i:s",$val['exp_date']);
                    $val['create_time']   = date("Y-m-d H:i:s",$val['create_time']);
                }
            }else{
                $data = array("status" => -1,"msg" => "商家id有误");
            }
        }
        apiReturn($data);
    } 
    //获取商家续费时间和金额接口
    public function getStoreRenewTimeMoney(){
        $info = M("set_store")->find();
        $info['fee'] = unserialize($info['fee']);
        if($info == false){
            $result = array("status" => -1, "msg" => "查询出错");
        }elseif ($info == NULL) {
            $result = array("status" => -1, "msg" => "查询结果为空");
        }else{
            $result = array("status" =>  1, "data" => $info['fee']);
        }
        apiReturn($result);
    }
    //申请入驻 数据检查
    public function dataCheck($data){
        if (!$data || $data == "undefined" || $data == "null"){
            return true;
        }else{
            return false;
        }
    }

    //从微信服务器获取图片流  
    public function doWechatPic($media_id){
        vendor('Jssdk.Jssdk');
        $appid = "wx79072a671d933458";
        $appsecret = "d00816ccd2d1b6f4afcdb1b2e7b57360";
        $jssdk = new \JSSDK($appid,$appsecret);
        $access_token = $jssdk->getAccessToken();
        $pic_url  = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=".$access_token."&media_id=".$media_id;
        $filebody = file_get_contents($pic_url);
        $filename = uniqid().'.png';
        return $this->saveFile($filename, $filebody);  
    }
    //定义文件路径，写入图片流
    public function saveFile($filename, $filebody){
        $upload_dir = "./Uploads/goods_img/".date("Y-m-d");
        $mkpath = $upload_dir;
        if(!is_dir($mkpath)){
          if(!mkdir($mkpath)){
            die('no mkdir power');
          }
          if(!chmod($mkpath,0755)){// 阿里云上不建议使用0644 原来是0755
            die('no chmod power');
          }
        }
        $savepath = $upload_dir.'/'.$filename;
        if(file_put_contents($savepath, $filebody)){//写入图片流生成图片  
          return "goods_img/".date("Y-m-d")."/".$filename;//返回图片路径  
        }else{  
          die('save failed');  
        }  
    }
  
    //获取地区列表
    public function regionList(){
        $result = M("regionProvince")
            ->join("p INNER JOIN `am_region_city` city ON p.`id`=city.`province_id`")
            ->join("`am_region_county` county ON city.`id`=county.`city_id`")
            ->join("`am_region_village` v ON county.`id`=v.`county_id`")
            ->order("p.`sort` ASC,city.`sort` ASC,county.`sort` ASC")
            ->field("p.`name` AS `province`,city.`province_id`,city.`name` AS `city`,county.`city_id`,county.`name` AS `county`,county.`id` AS `county_id`,v.`name` AS `village`,v.`id` AS `village_id`,v.`type`")

            ->select();
        $villageArr = $countyArr = $cityArr = $provinceArr = array();
        // 把 村、县、市、省 组成独立数组
        foreach ($result as $key => $value) {
            // 村数组
            if ($value['village_id']) {
                array_push(
                    $villageArr,
                    array(
                        "village" => $value['village'],
                        "id" => $value['village_id'],
                        "county_id" => $value['county_id'],
                        "type" => $value['type']
                    )
                );
            }
            // 县数组
            $array = array(
                "county" => $value['county'],
                "id" => $value['county_id'],
                "city_id" => $value['city_id']
            );
            if (!in_array($array, $countyArr)) {
                array_push($countyArr, $array);
            }
            // 城市数组
            $array = array(
                "city" => $value['city'],
                "id" => $value['city_id'],
                "province_id" => $value['province_id']
            );
            if (!in_array($array, $cityArr)) {
                array_push($cityArr, $array);
            }
            // 省数组
            $array = array(
                "province" => $value['province'],
                "id" => $value['province_id']
            );
            if (!in_array($array, $provinceArr)) {
                array_push($provinceArr, $array);
            }
        }
        $data = array(
            "provinceArr" => $provinceArr,    // 纯粹的省数组
            "villageArr" => $villageArr,
            "countyArr" => $countyArr,
            "cityArr" => $cityArr
        );
        unset($key, $value, $result);
        // 把 村数组 放入 县数组
        foreach ($countyArr as $kc => $vc) {
            $countyArr[$kc]['village_list'] = array();
            foreach ($villageArr as $kv => $vv) {
                if ($vv['county_id'] == $vc['id']) {
                    array_push(
                        $countyArr[$kc]['village_list'],
                        $vv
                    );
                }
            }
            unset($kv, $vv);
        }
        unset($kc, $vc);
        // 把 新的县数组 放入 城市数组
        foreach ($cityArr as $kCity => $vCity) {
            $cityArr[$kCity]['county_list'] = array();
            foreach ($countyArr as $kCounty => $vCounty) {
                if ($vCounty['city_id'] == $vCity['id']) {
                    array_push(
                        $cityArr[$kCity]['county_list'],
                        $vCounty
                    );
                }
            }
            unset($kCounty, $vCounty);
        }
        unset($kCity, $vCity);
        // 把 新的城市数组 放入 省数组
        foreach ($provinceArr as $kp => $vp) {
            $provinceArr[$kp]['city_list'] = array();
            foreach ($cityArr as $kc => $vc) {
                if ($vc['province_id'] == $vp['id']) {
                    array_push(
                        $provinceArr[$kp]['city_list'],
                        $vc
                    );
                }
            }
            unset($kc, $vc);
        }
        unset($kp, $vp);
        // 返回组装好的新的省数组
        
        $data['region_list'] = $provinceArr;

        apiReturn($data);
    }
}