<?php
namespace Smi\Controller;

use Think\Controller;

header("Content-Type:text/html;CharSet=UTF-8");
class OrderController extends BaseController
{
    protected $dada;// 达达配送实例

    /**
     * [get_dada_ie 获取达达配送实例]
     * @AuthorHTL
     * @DateTime  2018-03-28T10:24:56+0800
     * @return    [type]                   [description]
     */
    private function get_dada_ie($business_id)
    {
        try {
            // 多门店-主账号business_id   主账号绑定app_key  app_secret  source_id
            $parent_id = M('admin')->where(array('id' => $business_id))->getField('parent_id');
            if (empty($parent_id)) {
                $config_p_id = $business_id;// 主门店id
            } else {
                $config_p_id = $this->parent_id;// 主门店id
            }

            $dada_config = M('dada_business')->where(array('admin_id' => $config_p_id))->field('id, source_id, app_key, app_secret')->find();

            if (empty($dada_config)) {
                return ['code' => 404, 'info' => 'Dada delivery information is not bound'];
            } else {
                $this->dada = new \Common\Controller\DadaController($config_p_id);
                return ['code' => 200, 'info' => 'An instance of dada distribution has been obtained'];
            }
        } catch (Exception $e) {
            return ['code' => 404, 'info' => $e->getMessage()];   
        }
    }

    public function order_list()
    {
        $sts=$_REQUEST['sts'];

        $map = " o.admin_id = a.id  ";
        
        $business_id = session('admin_id');
        $map.=" and o.admin_id=".$business_id;
        
        if($sts = I('sts')) $map .= " and o.status = {$sts} "; //订单状态

        else $map .= " and o.status != 0 ";//全部订单

        if($ctstar = I('ctstar')) $map .= " and o.create_time > ".strtotime($ctstar); //开始时间

        if($ctend = I('ctend')) $map .= " and o.create_time < ".strtotime($ctend); //结束时间

        if($order_sn = I('order_sn')) $map .= " and o.order_sn like '%{$order_sn}%' "; //订单号

        //新增代码2018-7-02
        if($kexiao_sn = I('kexiao_sn')) $map .= " and o.kexiao_sn like '%{$kexiao_sn}%' "; //核销码

        if($nickname = I('nickname')) $map .= " and u.nickname like '%{$nickname}%' "; //用户名

        if($address = I('address')) $map .= " and (o.address_name like '%{$address}%' OR o.address_phone like '%{$address}%') "; //收货人

        $order_type = I('order_t');
        if ($order_type == 1) {
            $map .= " and o.order_type = 1 "; //外卖订单
        } elseif ($order_type == 2) {
            $map .= " and o.order_type = 2 "; //食堂订单
        }elseif ($order_type == 3) {
            $map .= " and o.order_type = 3 "; //门店自提
        }

        $map .= ' and o.uid = u.id';

        $count = M()->table("am_order o,am_users u, am_admin a")->where($map)->count();

        $Page = new \Think\Page($count,15);

        $show = $Page->show();
        $op = I('op');
        if($op == 'export'){
            $limit=10000;
        }else{
            $limit = $Page->firstRow.','.$Page->listRows;
        }
        

        //订单列表
        $list = M()->table("am_order o,am_users u,am_admin a")->field('o.*,u.nickname')->where($map)->limit($limit)->order('o.create_time desc')->select();

        foreach($list as $k=>&$val){

            $map = "order_sn = '{$val['order_sn']}'";

            $list[$k]['goods'] = M('car')->where($map)->limit(1)->select()[0];
            $list[$k]['goods'] = unserialize($list[$k]['goods']['car_content']);
            $sum_gold=0;
            foreach($list[$k]['goods'] as $i=>&$vol){
                $vol['img']=M('goods')->where('id='.$vol['goods_id'])->getField('img');
                $vol['title']=M('goods')->where('id='.$vol['goods_id'])->getField('title');

                if($vol['attr_id']){
                    $attr=array_filter(explode(",", $vol['attr_id']));
                    $text="";
                    foreach ($attr as $key => $value) {
                        $goodsattr = M('goods_attr')->where('id='.$value)->find();
                        if($key==0){
                          $text=$goodsattr['attr_title'];
                        }else{
                          $text.="+".$goodsattr['attr_title'];
                        }
                    }

                    $vol['attr_title']=$text;
                }
            }
        }


       
        
        if($op == 'export'){

          //$list = $this->address_info($list,true);

          $data = array(array(

            'order number',

            'UID',

            'neckname',

            'name',

            'phone',

            'status',

            'price',

            'Place the order of time',

            'Payment time',

            

           

            'product name',

           

            ));

          unset($val);

           

          foreach($list as $val){

           

              

                switch ($val['status']) {



                  case 1: $val['status_name'] = 'For the payment'; break;

                  case 2: $val['status_name'] = 'Have order'; break;

                  case 3: $val['status_name'] = 'Has been completed'; break;

                  case 4: $val['status_name'] = 'Have a refund'; break;

                  case 5: $val['status_name'] = 'Has been cancelled'; break;

                  

                  default: break;

                }


                $goodstitle="";
                foreach ($val['goods'] as $k => $v) {
                    if($k==0){
                          $goodstitle=$v['title'];
                        }else{
                          $goodstitle.="+".$v['title'];
                        }
                }

                $val['goodstitle']=$goodstitle;

                

                $data[] = array(

                  $val['order_sn'],

                  $val['uid'],

                  $val['nickname'],


                  $val['address_name'],

                  $val['address_phone'],

                  $val['status_name'],

                  $val['total_price'],

                  cdate(0,$val['create_time']),

                  cdate(0,$val['pay_time']),

                 

                 

                  $val['goodstitle'],

                  

                  );

              

            

          }
         // print_r($data);die;

          create_xls($data,'The order list_'.date("Y-m-d H:i"));

          die;

        }

        $this->assign('list',$list);
        $this->assign('page',$show);
        $this->assign('count',$count);
        $count2 = M('order')->where("status = 2")->count();

        $this->assign("count2",$count2);

        $this->display();
    }

    public function detail()
    {
        $order_sn = I('order_sn');

        $map['order_sn']=$order_sn;
        $map['admin_id']=$_SESSION['admin_id'];
        $order=M('order')->where($map)->find();

        if(!$order){$this->error('The order does not exist','',2);die;}

        $map_ = "order_sn = '{$order_sn}'";
        $goods_info = M('car')->where($map_)->select();
        foreach ($goods_info as $key => &$val) {
            $val['car_content']=unserialize($val['car_content']);
            foreach($val['car_content'] as $i=>&$vil){
                $vil['img']=M('goods')->where('id='.$vil['goods_id'])->getField('img');
                $vil['title']=M('goods')->where('id='.$vil['goods_id'])->getField('title');


                if($vil['attr_id']){
                    $attr=array_filter(explode(",", $vil['attr_id']));
                    $text="";
                    foreach ($attr as $key => $value) {
                        $goodsattr = M('goods_attr')->where('id='.$value)->find();
                        if($key==0){
                          $text=$goodsattr['attr_title'];
                        }else{
                          $text.="+".$goodsattr['attr_title'];
                        }
                    }

                    $vil['attr_title']=$text;
                }
            }
        }

        $goods_user = M('users')->where('id='.$order['uid'])->find();

        // 外卖订单--查看配送信息
        if ($order['order_type'] == 1) {
            $dada_ie_status = $this->get_dada_ie($map['admin_id']);// 获取达达配送实例
            // 请求配送订单状态
            if ($dada_ie_status['code'] == 200){
                $order['dada_order'] = $this->dada->query(array('order_id' => $order['order_sn']));
                $order['is_dada'] = 1;// 显示达达配送信息
            } else {
                $order['is_dada'] = 0;// 不显示达达配送信息
            }
        }

        // dump($order['dada_order']);
        $this->assign('order',$order);
        $this->assign('goods_user',$goods_user);
        $this->assign('goods_info',$goods_info);
        $this->assign('car_content',$goods_info[0]['car_content']);

        $this->display();
    }

    /**
     * [reAddOrder 配送订单重发，查询运费后发单]
     * @AuthorHTL
     * @DateTime  2018-03-30T17:12:25+0800
     * @return    [type]                   [description]
     */
    public function reAddOrder()
    {
        $data = I('post.');

        if (empty($data['order_sn'])) $this->ajaxReturn(['status' => -1, 'info' => 'The order number is empty']);

        $dada_ie_status = $this->get_dada_ie(session('admin_id'));// 获取达达配送实例

        if ($dada_ie_status['code'] != 200) $this->ajaxReturn(['status' => -1, 'info' => $dada_ie_status['info']]);

        $order_info = M('order')->where(array('order_sn' => $data['order_sn']))->field('deliveryNo')->find();

        if (!empty($order['deliveryNo'])) {
            $dada_return = $this->dada->addAfterQuery(array('deliveryNo' => $order['deliveryNo']));// 查询运费后发单接口
            if ($this->dada->errCode == 0) {
                $this->ajaxReturn(['status' => 1, 'info' => 'The order was redelivered successfully']);
            } else {
                $this->ajaxReturn(['status' => -1,'info' => 'Repeat order failed']);
            }
        } else {
            $this->ajaxReturn(['status' => -1,'info' => 'This order has no pre-issued order number']);
        }
    }

    /**
     * [reAddOrder 配送订单重发，已放弃]
     * @AuthorHTL
     * @DateTime  2018-03-28T16:01:38+0800
     * @return    [type]                   [description]
     */
    public function reAddOrder_()
    {
        $data = I('post.');

        if (empty($data['order_sn'])) $this->ajaxReturn(['status' => -1, 'info' => 'The order number is empty']);

        $dada_ie_status = $this->get_dada_ie(session('admin_id'));// 获取达达配送实例

        if ($dada_ie_status['code'] != 200) $this->ajaxReturn(['status' => -1, 'info' => $dada_ie_status['info']]);

        $order_info = M('order')->where(array('order_sn' => $data['order_sn']))->find();

        $business_info = M('admin')->where(array('id' => session('admin_id')))->field('dada_origin_shop_id, business_address')->find();

        $address_preg = '/^([\x7f-\xff]+省)?([\x7f-\xff]+市)([\x7f-\xff]+区|县)([\x7f-\xff_a-zA-Z0-9]+)$/';
        preg_match($address_preg, $business_info['business_address'], $matchs);
        $city = split('市', $matchs[2])[0];
        $cityCodeList = $this->dada->cityCodeList('');
        foreach ($cityCodeList as $key => $value) {
            if ($value['cityName'] == $city) {
                $cityCode = $value['cityCode'];// 城市编号
                break;
            }
        }

        // 回调地址
        $url = substr($_SERVER['PHP_SELF'],0,strrpos($_SERVER['PHP_SELF'], '/')-1);
        $url = substr($url,0,strrpos($url, '/')-1);
        $url = substr($url,0,strrpos($url, '/'));
        $notify_url = 'https://'.$_SERVER['HTTP_HOST'].substr($url,0,strrpos($url, '/')+1).'Api/Api/dadaNotifyUrl/a_id/'.$order_info['admin_id'];

        // 收货地址的经纬度--高德地图
        $location = split(',', json_decode($this->curlGet('http://restapi.amap.com/v3/geocode/geo?address='.$city.'市'.$order_info['address_info'].'&output=JSON&key=aba29ed8b30acb4e334d526b3f278c6d'), true)['geocodes'][0]['location']);

        $dada_return = $this->dada->reAddOrder(
                    array(
                        'shop_no' => $business_info['dada_origin_shop_id'],
                        'origin_id' => $data['order_sn'],
                        'city_code' => $cityCode,
                        'cargo_price' => $order_info['price'],
                        'is_prepay' => 1,
                        'receiver_name' => $order_info['address_name'],
                        'receiver_address' => $order_info['address_info'],
                        'receiver_lat' => $location[1],
                        'receiver_lng' => $location[0],
                        'callback' => $notify_url,
                        'receiver_phone' => $order_info['address_phone'],
                        'info' => $order_info['mark'],
                    )
                );

        if ($this->dada->errCode == 0) {
            $this->ajaxReturn(['status' => 1, 'info' => 'The order was redelivered successfully']);
        } else {
            $this->ajaxReturn(['status' => -1, 'info' => $this->dada->errMsg]);
        }
    }

    /**
     * [addOrder 配送订单未发出,重发]
     * @AuthorHTL
     * @DateTime  2018-03-29T18:53:49+0800
     */
    public function addOrder()
    {
        $data = I('post.');

        if (empty($data['order_sn'])) $this->ajaxReturn(['status' => -1, 'info' => 'The order number is empty']);

        $api_controller = new \Api\Controller\ApiController();

        $api_return = $api_controller->addDadaOrder(session('admin_id'), $data['order_sn']);

        if ($api_return['code'] == 200) {
            $this->ajaxReturn(['status' => 1, 'info' => 'Resend success']);
        } else {
            $this->ajaxReturn(['status' => -1, 'info' => $api_return['info']]);
        }
    }

    /**
     * [cancelReasons 获取取消原因]
     * @return [type] [description]
     */
    public function cancelReasons()
    {
        $api_controller = new \Api\Controller\ApiController();

        $api_return = $api_controller->cancelReasons(session('admin_id'));

        if ($api_return['code'] == 200) {
            $this->ajaxReturn(['status' => 1, 'info' => $api_return['info'], 'data' => $api_return['data']]);
        } else {
            $this->ajaxReturn(['status' => -1, 'info' => $api_return['info']]);
        }
    }

    /**
     * [formalCancel 配送订单取消]
     * @return [type] [description]
     */
    public function formalCancel()
    {
        $data = I('post.');
        if (empty($data['order_sn'])) $this->ajaxReturn(['status' => -1, 'info' => 'The order number is empty']);
        if (empty($data['cancel_reason_id'])) $this->ajaxReturn(['status' => -1, 'info' => 'Cancel cause ID to be empty']);
        if ($data['cancel_reason_id'] == 10000 && empty($data['cancel_reason'])) $this->ajaxReturn(['status' => -1, 'info' => 'The reason for cancellation is null']);

        $api_controller = new \Api\Controller\ApiController();

        $api_return = $api_controller->formalCancel(session('admin_id'), $data['order_sn'], $data['cancel_reason_id'], $data['cancel_reason']);

        if ($api_return['code'] == 200) {
            $this->refund_common($data['order_sn']);// 全额退款返还给用户
            $this->ajaxReturn(['status' => 1, 'info' => $api_return['info']]);
        } else {
            $this->ajaxReturn(['status' => -1, 'info' => $api_return['info']]);
        }
    }

    /**
     * [complaintReason 商家投诉原因]
     * @AuthorHTL
     * @DateTime  2018-03-30T11:33:44+0800
     * @return    [type]                   [description]
     */
    public function complaintReason()
    {
        $api_controller = new \Api\Controller\ApiController();

        $api_return = $api_controller->complaintReason(session('admin_id'));
        
        if ($api_return['code'] == 200) {
            $this->ajaxReturn(['status' => 1, 'info' => $api_return['info'], 'data' => $api_return['data']]);
        } else {
            $this->ajaxReturn(['status' => -1, 'info' => $api_return['info']]);
        }
    }

    /**
     * [complaintDada 商家投诉]
     * @AuthorHTL
     * @DateTime  2018-03-30T11:33:11+0800
     * @return    [type]                   [description]
     */
    public function complaintDada()
    {
        $data = I('post.');
        if (empty($data['order_sn'])) $this->ajaxReturn(['status' => -1, 'info' => 'The order number is empty']);
        if (empty($data['reason_id'])) $this->ajaxReturn(['status' => -1, 'info' => 'The complaint reason ID is empty']);

        $api_controller = new \Api\Controller\ApiController();

        $api_return = $api_controller->complaintDada(session('admin_id'), $data['order_sn'], $data['reason_id']);

        if ($api_return['code'] == 200) {
            $this->ajaxReturn(['status' => 1, 'info' => $api_return['info']]);
        } else {
            $this->ajaxReturn(['status' => -1, 'info' => $api_return['info']]);
        } 
    }

    /**
     * [curlGet curl请求  get]
     * @AuthorHTL
     * @DateTime  2018-03-28T17:40:27+0800
     * @param     [type]                   $url [description]
     * @return    [type]                        [description]
     */
    private function curlGet($url)
    {
        // 使用 curl_init()函数初始化一个CURL会话，初始化成功后返回一个句柄供curl_setopt(), curl_exec(),和 curl_close() 函数使用
        $curl = curl_init();
        // 使用curl_setopt()设置要获取的URL地址
        curl_setopt($curl, CURLOPT_URL, $url);
        // 设置是否输出header 设为0 否则影响输出
        curl_setopt($curl, CURLOPT_HEADER, 0);
        // 设置是否输出结果
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        // 设置是否输出结果
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        // 设置是否检查服务器端的证书
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        // 使用curl_exec()将CURL返回的结果转换成正常数据并保存到一个变量
        $data = curl_exec($curl);
        // 使用 curl_close() 关闭CURL会话
        curl_close($curl);
        return $data;
    }

    /**
     * [refund 订单退款]
     * @AuthorHTL
     * @DateTime  2018-03-10T10:31:15+0800
     * @return    [type]                   [description]
     */
    public function refund()
    {
        $data = I('post.');
         
        if (empty($data['order_sn'])) $this->ajaxReturn(['status' => -1, 'info' => 'The order number is empty']);

        //退款方式2018-6-21
        $order=M('order')->where('order_sn='.$data['order_sn'])->find();
        if($order['pay_type'] == 1){
            $return = $this->refund_common($data['order_sn']);
        }elseif($order['pay_type'] == 2){
             $return = $this->refund_yue($data['order_sn']);
        }
        
        //$return = $this->refund_common($data['order_sn']);
        $this->ajaxReturn($return);
    }

    private function refund_common($order_sn)
    {
        $Order=M('order');
        $order=$Order->where(array('order_sn' => $order_sn))->find();
        $out_trade_no = $order_sn;
        $out_refund_no=date('YmdHis') . str_pad(mt_rand(1, 99999), 4, '2', STR_PAD_LEFT).str_pad(mt_rand(1, 99999), 3, '4', STR_PAD_LEFT);
        // $out_refund_no = str_replace(' ', '', str_replace(':', '', str_replace('-', '', date('Y-m-d H:i:s').rand(100000, 999999))));
        // $this->ajaxReturn(['status' => -1, 'msg' => $out_refund_no]);
        // $out_refund_no = $out_trade_no;
        $total_fee=$order['price'];
        $refund_fee=$order['price'];
        
        // 实例支付接口，判断是否有多门店，并获取主门店id
        $parent_id = M('admin')->where(array('id' => $order['admin_id']))->getField('parent_id');
        // $this->ajaxReturn(['status' => -1, 'msg' => $parent_id ? $parent_id : $order['admin_id']]);

        // $this->ajaxReturn(['status' => 1, 'msg' => $out_trade_no.'------'.$out_refund_no]);
        if (empty($parent_id)) {
            $pay = & load_wechat('Pay', $order['admin_id']);    
        } else {
            $pay = & load_wechat('Pay', $parent_id);
        }
        // $this->ajaxReturn(['status' => -1, 'info' => json_encode($pay)]);
        // 调用退款接口
      
        $result = $pay->refund($out_trade_no , $out_refund_no, $total_fee*100, $refund_fee*100);
        
        // 处理创建结果
        if($result===FALSE){
            // 接口失败的处理
            // $this->ajaxReturn(['status' => -1, 'info' => $pay->errMsg.'-----']);
            return ['status' => -1, 'info' => $pay->errMsg.'-----'];
        }else{
            // 接口成功的处理
            $dat['status']=4;
            $dat['out_refund_no'] = $out_refund_no;
            $Order->where("order_sn=".$order_sn)->save($dat);
            // $this->ajaxReturn(['status' => 1, 'info' => $pay_errMsg.'+++++']);
            return ['status' => 1, 'info' => 'Refund success'];
        }
    }


    //余额退款2018-6-21
    private function refund_yue($order_sn)
    {
        $Order=M('order');
        $order=$Order->where(array('order_sn' => $order_sn))->find();

        $user_balance = M('user_money')->where(array('user_id' => $order['uid']))->field('money, balance')->find();
        $balance_result = M('user_money')->where(array('user_id' => $order['uid']))->save(array('money' => $user_balance['money'] - $order['price'], 'balance' => $user_balance['balance'] + $order['price'], 'update_time' => time()));
        
        // 处理创建结果
        if($balance_result){
            // 接口成功的处理
            $dat['status']=4;
            //$dat['out_refund_no'] = $out_refund_no;
            $Order->where("order_sn=".$order_sn)->save($dat);
            // $this->ajaxReturn(['status' => 1, 'info' => $pay_errMsg.'+++++']);
            return ['status' => 1, 'info' => 'Refund success'];
        }else{
           
            return ['status' => -1, 'info' => 'Refund failure'];
        }
    }

    /**
     * [sure_order_complete 确认订单完成]
     * @AuthorHTL
     * @DateTime  2018-03-10T10:31:47+0800
     * @return    [type]                   [description]
     */
    public function sure_order_complete()
    {
        $data = I('post.');

        if (empty($data['order_sn'])) $this->ajaxReturn(['status' => -1, 'info' => 'The order number is empty']);
        $result = M('order')->where(array('order_sn' => $data['order_sn']))->save(array('status' => 3));
        if ($result) {
            $rec=M('distribution_rec')->where('order_sn='.$order_sn)->select();
            foreach($rec as $i => $val){
              M('distribution_rec')->where('id='.$val['id'])->setField('status',1);//修改佣金状态
              M('users')->where('id='.$val['user_id'])->setInc('count_sale',$val['money']);//累计可用提现佣金
            }
            
            $this->ajaxReturn(['status' => 1, 'info' => 'Operation is successful']);
        } else {
            $this->ajaxReturn(['status' => -1, 'info' => 'The operation failure']);
        }
    }

    /**
     * 预约订单
     */
    public function appointment_order($sts = '', $name = '', $mobile = '', $ctstar = '', $ctend = '')
    {   
        $where = 't.admin_id = '.session('admin_id');

        if(!empty($sts)) $where .= " and t.status = {$sts} "; //订单状态

        if(!empty($ctstar)) $map .= " and t.create_time > ".strtotime($ctstar); //开始时间

        if(!empty($ctend)) $map .= " and t.create_time < ".strtotime($ctend); //结束时间

        if(!empty($name)) $map .= " and t.name like '%{$name}%' "; //用户名

        if($address = I('mobile')) $map .= " and t.mobile like '%{$mobile}%' "; //联系方式

        $count = M('appointment t')
                ->where($where)
                ->count();

        $Page = new \Think\Page($count, 15);
        $show = $Page->show();
        $limit = $Page->firstRow.','.$Page->listRows;

        $list = M('appointment t')
                ->where($where)
                ->limit($limit)
                ->order('t.create_time DESC')
                ->field('t.*')
                ->select();

        if (!empty($list)) {
            foreach ($list as $key => &$value) {
                $value['table'] = '';
                $table_info = M('table t')
                            ->join('LEFT JOIN am_table tp ON tp.id = t.pid')
                            ->where(array('t.id' => $value['table_id']))
                            ->field('t.name, tp.name pname')
                            ->find();
                $value['table'] = $table_info['pname'].$table_info['name'];
            }
        }

        $count = M('appointment t')
                ->where('t.status = 1 AND t.admin_id = '.session('admin_id'))
                ->count();

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

    /**
     * 确认预约订单
     */
    public function sure_complete()
    {
        $data = I('post.');

        if (empty($data['p_money'])) {
            $this->ajaxReturn(['status' => -1, 'msg' => 'Consumption cannot be empty']);die;
        } 

        $result = M('appointment')->where(array('id' => $data['id']))->save(array('p_money' => $data['p_money'], 'status' => 3));

        if ($result) {
            $this->ajaxReturn(['status' => 1, 'msg' => 'Confirmed Customer Dined In']);die;
        } else {
            $this->ajaxReturn(['status' => -1, 'msg' => 'Confirm consumption failure']);die;
        }
    }

     /**
     * 确认订单
     */
    public function sure_o()
    {
        $data = I('post.');

        if (empty($data['id'])) {
            $this->ajaxReturn(['status' => -1, 'msg' => 'The order id cannot be empty']);die;
        } 

        $result = M('appointment')->where(array('id' => $data['id']))->save(array('status' => 2));

        if ($result) {
            $this->ajaxReturn(['status' => 1, 'msg' => 'Identify successful']);die;
        } else {
            $this->ajaxReturn(['status' => -1, 'msg' => 'Confirm the failure']);die;
        }
    }

    /**
     * 删除
     */
    public function delete($id)
    {
        $info = M('appointment')->where(array('id' => $id))->find();

        if ($info['admin_id'] != session('admin_id')) {
            alertMsg('Illegal operation');die;
        }

        $result = M('appointment')->where(array('id' => $id))->delete();

        if ($result) {
            $this->success('Successfully Deleted');die;
        } else {
            alertMsg('Delete failed');die;
        }
    }

    /**
     * 提交备注信息
     */
    public function commit_remark()
    {
        $data = I('post.');

        if (empty($data['remark'])) {
            $this->ajaxReturn(['status' => -1, 'msg' => 'The remarks should not be empty']);die;
        } 

        $result = M('appointment')->where(array('id' => $data['id']))->save(array('remark' => $data['remark']));

        if ($result) {
            $this->ajaxReturn(['status' => 1, 'msg' => 'Successfully Saved']);die;
        } else {
            $this->ajaxReturn(['status' => -1, 'msg' => 'submit failure']);die;
        }
    }




    public function zhiorder()
    {
        $business_id = session('admin_id');
        $map="admin_id=".$business_id;

        if($sts = I('sts')) $map .= " and status = {$sts} "; //订单状态

        //else $map .= " and status != 0 ";//全部订单

        if($ctstar = I('ctstar')) $map .= " and create_time > ".strtotime($ctstar); //开始时间

        if($ctend = I('ctend')) $map .= " and create_time < ".strtotime($ctend); //结束时间

        if($order_sn = I('order_sn')) $map .= " and order_sn like '%{$order_sn}%' "; //订单号

        //新增代码2018-7-02
        if($kexiao_sn = I('kexiao_sn')) $map .= " and kexiao_sn like '%{$kexiao_sn}%' "; //核销码

        //if($nickname = I('nickname')) $map .= " and u.nickname like '%{$nickname}%' "; //用户名

        if($address = I('address')) $map .= " and (address_name like '%{$address}%' OR address_phone like '%{$address}%') "; //收货人

        $order_type = I('order_t');
        if ($order_type == 1) {
            $map .= " and order_type = 1 "; //外卖订单
        } elseif ($order_type == 2) {
            $map .= " and order_type = 2 "; //食堂订单
        }elseif ($order_type == 3) {
            $map .= " and order_type = 3 "; //门店自提
        }

        //$map .= ' and o.uid = u.id';

        $count = M('order')->where($map)->count();

        $Page = new \Think\Page($count,15);

        $show = $Page->show();
        $limit = $Page->firstRow.','.$Page->listRows;
        $list=M('zhi_order')->where($map)->limit($limit)->order('create_time desc')->select();
        foreach ($list as $key => $value) {
            $user=M('users')->where('id='.$value['user_id'])->find();
            $list[$key]['username']=$user['nickname'];
            $list[$key]['create_time']=date("Y-m-d H:i",$value['create_time']);
            if($value['status']==1){
                $list[$key]['status']='For the payment';
            }elseif($value['status']==2){
                $list[$key]['status']='Payment has been';
            }
        }
        $this->assign('list', $list);
        $this->assign('page', $show);
        //print_r($list);die;

        $this->display();
    }





    //查询是否有新订单
    public function CheckNewOrder(){
        /*$data = M('order') 
        -> field('id,order_sn,gold,address_name,address_phone,message,create_time,status') 
        -> where("status=3") 
        -> order("id DESC") -> find();*/

        $data = M('order') 
        -> where("status=2 and admin_id=".session('admin_id')) 
        -> order("id DESC") -> find();

        if($data){
          $data['number']=$data['order_sn'];//订单号
          $data['money']=$data['total_price'];//金额
          $data['name']=$data['address_name'];//收货人
          $data['phone']=$data['address_phone'];//收货电话

         // $order_goods=M('order_goods')->where('order_sn='.$data['order_sn'])->select();
         $data['goods'] = M('car')->where('order_sn='.$data['order_sn'])->limit(1)->select()[0];
         $data['goods'] = unserialize($data['goods']['car_content']);

         $goods_text='';
         foreach($data['goods'] as $i=>&$vol){
                $vol['img']=M('goods')->where('id='.$vol['goods_id'])->getField('img');
                $vol['title']=M('goods')->where('id='.$vol['goods_id'])->getField('title');

                if($i==0){
                  $goods_text=$vol['title'].$vol['goods_num'];
                }else{
                  $goods_text.=' + '.$vol['title'].$vol['goods_num'];
                }
         }

          
          

          $data['serve_name']=$goods_text;//订单商品和数量
          if($data['pay_type']==1){
            $data['opayway']='WeChat pay';
          }elseif($data['pay_type']==2){
            $data['opayway']='The balance payment';
          }
          //$data['opayway']='微信支付';//支付方式
          $data['order_time']=date('Y-m-d H:i:s',$data['create_time']);//下单时间

          if($data['status'] == 2){
              M('order') -> where('order_sn='.$data['order_sn'].' and admin_id='.session('admin_id')) -> setField('pop_status',1); //更改弹出状态
              //M('order') -> where('order_sn='.$data['order_sn']) -> setField('pop_status',1); //更改弹出状态
          }
        }

        if(!$data){
         $info['status'] = -1;
            echo json_encode($info,true);exit;
        }

        if(session('newOrderId')){
          if(session('newOrderId') != $data['id']){

            $content = '<div class="all_div"><div class="first_di">order number</div><div class="second_di"> '.$data['number'].'</div></div><div class="all_div"><div class="first_di">Service Name</div> <div class="second_di">'.$data['serve_name'].'</div></div><div class="all_div"><div class="first_di">total payment</div> <div class="second_di">'.$data['money'].' '.$data['opayway'].'</div></div><div class="all_div"><div class="first_di">order time</div><div class="second_di">'.$data['order_time'].'</div></div><div class="all_div"><div class="first_di">Contact name</div> <div class="second_di">'.$data['name'].'</div></div><div class="all_div"><div class="first_di">phone</div> <div class="second_di">'.$data['phone'].'</div></div><div class="all_div"><div class="first_di">Method of payment</div><div class="second_di">'.$data['opayway'].'</div></div><div class="all_div"></div><div class="all_div"><div class="first_di">Leave a message</div><div class="second_di">'.$data['mark'].'</div></div>';

            $foot = '<button  class="am-btn close_box" style="margin-top:3px;background:#F37B1D;margin-top: 20px;width: 60%;margin-left: 20%;color: #fff;margin-top: 20px;">close</button>';
              
               $info['content'] = $content.$foot;
              
              
              $info['status'] = 1;
              session('newOrderId',$data['id']);
              
              echo json_encode($info,true);exit;
          }else{
            $info['status'] = -1;
            echo json_encode($info,true);exit;
          }
        }else{
            $content = '<div class="all_div"><div class="first_di">order number</div><div class="second_di"> '.$data['number'].'</div></div><div class="all_div"><div class="first_di">Service Name</div> <div class="second_di">'.$data['serve_name'].'</div></div><div class="all_div"><div class="first_di">total payment</div> <div class="second_di">￥'.$data['money'].' '.$data['opayway'].'</div></div><div class="all_div"><div class="first_di">order time</div><div class="second_di">'.$data['order_time'].'</div></div><div class="all_div"><div class="first_di">Contact name</div> <div class="second_di">'.$data['name'].'</div></div><div class="all_div"><div class="first_di">phone</div> <div class="second_di">'.$data['phone'].'</div></div><div class="all_div"><div class="first_di">Method of payment</div><div class="second_di">'.$data['opayway'].'</div></div><div class="all_div"><div class="first_di">Appointment booking </div><div class="second_di">'.$data['worker_name'].'</div></div><div class="all_div"><div class="first_di">Leave a message</div><div class="second_di">'.$data['mark'].'</div></div>';

            $foot = '<button  class="am-btn close_box" style="margin-top:3px;background:#F37B1D;margin-top: 20px;width: 60%;margin-left: 20%;color: #fff;margin-top: 20px;">close</button>';
            
             $info['content'] = $content.$foot;
            
            $info['status'] = 1;
            session('newOrderId',$data['id']);

            echo json_encode($info,true);exit;
        }
    }
}