<?php
namespace Smi\Controller;

use Think\Controller;

header("Content-Type:text/html;CharSet=UTF-8");
class OrderController extends BaseController
{
    public function order_list(){
        // var_dump($_SESSION);exit;
        // auth_check("order_list");
        $sts=$_REQUEST['sts'];
        // $this->assign('auth',auth_check("order_list_w"));

        $op = I('op');

        $map = " o.admin_id = a.id  ";
//        dump($_SESSION);
        $group_id=$_SESSION['admin_id'];

        if($group_id){
            $map.=" and o.admin_id=".$group_id;
        }
//         echo $group_id;exit;
        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}%' "; //订单号

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

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

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

        $count = M()->table("am_order o,am_users u, am_admin a")->where($map)->count();
//        echo M()->getLastSql();exit;
//        dump($count);exit;
        $Page = new \Think\Page($count,15);

        $show = $Page->show();

        $limit = $Page->firstRow.','.$Page->listRows;

        // dump($map);die;
        //订单列表
        $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');
            }
        }

        $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('该订单不存在','',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');
            }
        }
        // print_r($goods_info);exit;
        $goods_user = M('users')->where('id='.$order['uid'])->find();

    
        $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();

    }

    public function address_info($address,$list = false)
    {
        if(!$address){

            return "";

        }else{

            $city_data = M('city')->select();

            foreach($city_data as $val){

                $city[$val['id']] = $val['name'];

            }

            $pickup_data = M('pickup_station')->select();

            foreach($pickup_data as $val){

                $pickup[$val['id']] = $val;

            }

            if($list){

                foreach($address as $k=>$val){
                    $address[$k]['address']['province'] = $city[$val['address']['province']];
                    $address[$k]['address']['city'] = $city[$val['address']['city']];
                    $address[$k]['address']['county'] = $city[$val['address']['county']];
                    if($val['address']['pickup'] > 0){
                      $address[$k]['address']['pickup'] = $pickup[$val['address']['pickup']];
                    }

                }

            }else{

                $address = unserialize($address);

                $address['province'] = $city[$address['province']];

                $address['city'] = $city[$address['city']];

                $address['county'] = $city[$address['county']];

                if($address['pickup'] > 0){

                    $address['pickup'] = $pickup[$address['pickup']];

                }

            }

            return $address;

        }

    }

    public function order_op(){

        // if(!auth_check("order_list"))die;

        $op = I('op');

        $now = time();

        $order_sn = I('order_sn')?:0;

        $map = "order_sn = '{$order_sn}'";

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

        $order['address'] = unserialize($order['address']);

        $order['score_get'] = $order['type']==3?0:intval($order['price']);



        if($op == 'fachu'){ /* 发出 */

            if($order['status'] != 2 ){$this->ajaxReturn([0]);die;}


            $fachu['kuaidi_name'] = I('kuaidi_name');

            $fachu['kuaidi_sn'] = I('kuaidi_sn');

            // var_dump($fachu);exit;
            foreach($fachu as $val){if(!$val){$this->ajaxReturn([0]);die;}}


            $data['fachu_time'] = $now;
            $data['fachu_name'] = $fachu['kuaidi_name'];
            $data['fachu_sn'] = $fachu['kuaidi_sn'];

            $data['status'] = 3;

            M('order')->where($map)->save($data);



            // // 发送模板消息

            // $datat['openid'] = getUserInfo('openid','',$order['uid']);

            // $datat['order_sn'] = $order_sn;

            // $datat['create_time'] = cdate(0,$order['create_time']);

            // sendTempMsg('fachu',$datat);



            $this->ajaxReturn([1]);die;

        }

        if($op == 'refund'){ /* 受理申请 */
            // echo $order['status'];exit;


            if($order['status'] != 6 ){$this->ajaxReturn([0]);die;}

            $status = $_REQUEST['status'];
            $refund['status'] = $status;


            foreach($refund as $val){if(!$val){$this->ajaxReturn([0]);die;}}



            $data['refunded_time'] = $now;

            $data['status'] = $status;

            M('order')->where($map)->save($data);
            // echo M()->getlastsql();exit;


            // // 发送模板消息

            // $datat['openid'] = getUserInfo('openid','',$order['uid']);

            // $datat['order_sn'] = $order_sn;

            // $datat['create_time'] = cdate(0,$order['create_time']);

            // sendTempMsg('fachu',$datat);



            $this->ajaxReturn([1]);die;

        }

        if($op == 'express'){ /* 退货退款 */

            if($order['status'] != 8 ){$this->ajaxReturn([0]);die;}

            $status=I('status');
            $gold=I('sum_gold');
            $uid=I('uid');

            $express['status'] = $status;




            foreach($express as $val){if(!$val){$this->ajaxReturn([0]);die;}}

            $rows=M('wx_users')->where('uid='.$uid)->setInc('gold',$gold);

            $data['status'] = $status;

            M('order')->where($map)->save($data);

            $time['endtime']=$now;

            M('order_apply')->where('order_sn="'.$order_sn.'"')->save($time);


            // // 发送模板消息

            // $datat['openid'] = getUserInfo('openid','',$order['uid']);

            // $datat['order_sn'] = $order_sn;

            // $datat['create_time'] = cdate(0,$order['create_time']);

            // sendTempMsg('fachu',$datat);



            $this->ajaxReturn([1]);die;

        }

        if($op == 'recovery'){ /* 恢复已关闭的订单 */

            if($order['status'] != 5 ){$this->ajaxReturn([0]);die;}

            $data['status'] = 1;

            M('order')->where($map)->save($data);



            // // 发送模板消息

            // $datat['openid'] = getUserInfo('openid','',$order['uid']);

            // $datat['order_sn'] = $order_sn;

            // $datat['create_time'] = cdate(0,$order['create_time']);

            // sendTempMsg('fachu',$datat);



            $this->ajaxReturn([1]);die;

        }

    }

    public function refund($order_sn = 0,$refund_fee = 0){

        // $refund_fee = 1;

        // $order_sn = "SHP_I1ZYSURT";

        vendor('WxPayPubHelper.WxPayPubHelper');

        $log = M("wxpay_log")->where("order_sn='{$order_sn}' and status=2")->find();

        if($log){

            $refund = new \Refund_pub();

            $refund->setParameter("transaction_id",$log['transaction_id']);

            // $refund->setParameter("out_trade_no",$log['order_sn']);

            $refund->setParameter("out_refund_no",$log['order_sn']);

            $refund->setParameter("total_fee",$log['fee']);

            $refund->setParameter("refund_fee",$refund_fee?:$log['fee']);

            $refund->setParameter("op_user_id",session('toy_admin_username'));

            $refundResult = $refund->getResult();

            if($refundResult['result_code'] == 'SUCCESS'){

                $data['refund_fee'] = $refund_fee?:$log['fee'];

                $data['refund_time'] = time();

                M('wxpay_log')->where("id = {$log['id']}")->save($data);

                return 1;die;

            }else{

                return $refundResult['err_code_des'];

            }

        }

        return false;

    }



    public function order_comment(){

        // auth_check("order_comment");

        // $this->assign('auth',auth_check("order_comment_w"));

        $map = " o.uid = u.uid and o.comment != '' ";

        $count = M()->table('tbl_order o,tbl_wx_users u')->where($map)->count();

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

        $show = $Page->show();

        $list = M()->table('tbl_order o,tbl_wx_users u')->field('u.uid,u.nickname,u.headimgurl,o.order_sn,o.comment,o.comment_img,o.comment_time')->where($map)->limit($Page->firstRow.','.$Page->listRows)->order('o.comment_time desc')->select();

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

            $list[$k]['comment_img'] = unserialize($val['comment_img']);

        }

        $this->assign('page',$show);

        $this->assign('list',$list);

        $this->display();

    }

    public function comment_dele(){

        // auth_check("order_comment");

        $order_sn = I('order_sn')?:0;

        $data['comment'] = "";

        $data['comment_img'] = "";

        M('order')->where("order_sn = '{$order_sn}'")->save($data);

        $this->success('删除成功','',2);

    }



    public function order_set(){

        // auth_check("order_set");

        $op = I('op');

        $type = I('type');

        if(!in_array($type,[1,2,3])) dier();

        if($op == 'save'){

            $set = M('setting');

            if($type == 1){

                $set->save(array('name'=>'order_submit_explain','value'=>I('order_submit_explain')));

                $set->save(array('name'=>'order_postage','value'=>abs(intval(I('order_postage')))));

            }else if($type == 2){

                $set->save(array('name'=>'order_relet_explain','value'=>I('order_relet_explain')));

            }else if($type == 3){

                $set->save(array('name'=>'order_fanhuan_explain','value'=>I('order_fanhuan_explain')));

            }

            $this->success('保存成功','',2);die;

        }

        $list = M('setting')->select();

        foreach($list as $val){

            $set[$val['name']] = $val['value'];

        }

        $this->assign('set',$set);

        $this->display();

    }

    /**
     * 预约订单
     */
    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' => '消费金额不能为空']);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' => '确认消费成功']);die;
        } else {
            $this->ajaxReturn(['status' => -1, 'msg' => '确认消费失败']);die;
        }
    }

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

        if (empty($data['id'])) {
            $this->ajaxReturn(['status' => -1, 'msg' => '订单id不能为空']);die;
        } 

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

        if ($result) {
            $this->ajaxReturn(['status' => 1, 'msg' => '确认成功']);die;
        } else {
            $this->ajaxReturn(['status' => -1, 'msg' => '确认失败']);die;
        }
    }

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

        if ($info['admin_id'] != session('admin_id')) {
            alertMsg('非法操作');die;
        }

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

        if ($result) {
            $this->success('删除成功');die;
        } else {
            alertMsg('删除失败');die;
        }
    }

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

        if (empty($data['remark'])) {
            $this->ajaxReturn(['status' => -1, 'msg' => '备注内容不能为空']);die;
        } 

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

        if ($result) {
            $this->ajaxReturn(['status' => 1, 'msg' => '提交成功']);die;
        } else {
            $this->ajaxReturn(['status' => -1, 'msg' => '提交失败']);die;
        }
    }
}