<?php
/**
 * Created by PhpStorm.
 * User: 29925
 * Date: 2018/8/20
 * Time: 16:44
 */

namespace app\portal\controller;

use app\admin\model\OrderModel;
use app\admin\model\OrderSortModel;
use app\admin\model\LogisticsModel;
use app\admin\model\SlideItemModel;
use cmf\controller\HomeBaseController;
use think\Cache;
use think\Db;
use traits\controller\Jump;

class OrderController extends HomeBaseController
{
    protected $table;
    protected $order_table;
    protected $order_model;
    protected $order_sort_model;
    protected $option_table;
    protected $sort_model;
    public function _initialize()
    {
        parent::_initialize();
        $this->table = 'OrderSort';
        $this->order_table = 'Order';
        $this->order_model = new OrderModel();
        $this->order_sort_model = new OrderSortModel();
        $this->option_table = 'OrderOption';

        $this->sort_model[1] = '<div class="text_item form_options" data-validate="{validate}">
            <p class="text_tit"><span class=" _validate">{name}</span>{must}</p>
            <input type="text" name="" id="" value="{value}" class="baby_input" placeholder="请输入{name}" />
        </div>';
        $this->sort_model[2] = '<div class="text_item form_options" data-validate="{validate}">
            <p class="text_tit"><span class=" _validate">{name}</span>{must}</p>
            <input type="number" name="" id="" value="{value}" class="baby_input" placeholder="请输入{name}" />
        </div>';
        $this->sort_model[3] = '<div class="text_item form_options" data-validate="{validate}">
            <p class="text_tit"><span class=" _validate">{name}</span>{must}</p>
            <input type="number" maxlength="11" name="" id="" value="{value}" class="baby_input" placeholder="请输入{name}" />
        </div>';
        $this->sort_model[4] = '<div class="write_tit form_options" data-validate="{validate}">
            <p class="tit"><span class=" _validate">{name}</span></p>
            <div class="flex_style">
                {options}
            </div>
        </div>';
        $this->sort_model[5] = '<div class="text_item form_options" data-validate="{validate}">
            <p class="text_tit"><span class=" _validate">{name}</span>{must}</p>
            <input type="text" name="" id="" value="{value}" class="baby_input" placeholder="请输入{name}" />
        </div>';
        $this->sort_model[6] = '<div class="text_item form_options" data-validate="{validate}">
            <p class="text_tit"><span class=" _validate">{name}</span>{must}</p>
            <textarea class="baby_input">{value}</textarea>
        </div>';
        $this->sort_model[7] = '<div class="text_item form_options" data-validate="{validate}">
            <p class="text_tit"><span class=" _validate">{name}</span>{must}</p>
            <input type="text" name="" id="product" value="{value}" class="baby_input" placeholder="请选择{name}" />
            <img src="__TMPL__/public/mobile/images/youjiantou.png" class="jiantou" />
        </div>';
        $this->sort_model[8] = '<div class="write_wrap" style="margin: 0;" data-validate="{validate}">
					<p class="text_tit" style="line-height: 0.6rem;"><span class=" _validate">{name}</span>{must}</p>
				</div>
		<div class="up_wrap form_options">
            <div class="up_pic">
                <i class="iconfont icon-msnui-cloud-upload"></i>
                <p class="click_up">点击上传</p>
            </div>
        </div>';
        $this->sort_model[10] = '<div class="text_item no_margin form_options" data-validate="{validate}">
            <p class="text_tit"><span class=" _validate">{name}</span>{must}</p>
            <input type="text" name="" id="birthday" readonly="readonly" value="{value}" class="baby_input" placeholder="请选择{name}" />
            <img src="__TMPL__/public/mobile/images/youjiantou.png" class="jiantou" />
        </div>';
        $this->sort_model[11] = '<div class="text_item form_options" data-validate="{validate}">
            <p class="text_tit"><span class=" _validate">{name}</span>{must}</p>
            <weui-distpicker province="广东省" city="广州市" area="海珠区"></weui-distpicker>
            <input type="text" name="" id="address" readonly="readonly" value="{value}" class="baby_input" placeholder="请输入{name}" />
            <img src="__TMPL__/public/mobile/images/youjiantou.png" class="jiantou" />
        </div>';
    }

    // 我要支付页面
    public function index() {
        // 生成页面二维码(用户推广)
        $url = url('portal/Order/index','','',true);
        $qrcode = $this->createQRcode($url,'Q',9);
        $name = '我要支付';
        $this->qrcodePage($url,$name,$qrcode);
        $this->nav_bottom(0,1,0);

        // banner图
        $slide_model = new SlideItemModel();
        $slide_where = [
            'slide_id' => 2,
            'status' => 1
        ];
        $slide = $slide_model->where($slide_where)->order(['list_order'=>'ASC'])->find();
        $this->assign('slide',$slide);
        return $this->fetch();
    }

    // 去支付
    public function to_pay() {
        // 生成页面二维码(用户推广)
        $url = url('portal/Order/to_pay','','',true);
        $qrcode = $this->createQRcode($url,'Q',9);
        $name = '我要支付(订单确认码)';
        $this->qrcodePage($url,$name,$qrcode);

        // banner图
        $slide_model = new SlideItemModel();
        $slide_where = [
            'slide_id' => 3,
            'status' => 1
        ];
        $slide = $slide_model->where($slide_where)->order(['list_order'=>'ASC'])->find();
        $this->assign('slide',$slide);
        return $this->fetch();
    }

    // 订单确认
    public function order_confirm() {
        $id = $this->request->param('id');
        if(!$id) {
            $this->redirect(url('to_pay'));
        }
        $where = [
            'o.id' => $id,
            'o.delete_time' => 0
        ];
        $orderInfo = Db::name('Order')
            ->alias('o')
            ->field(['o.*,os.name'])
            ->join('__ORDER_SORT__ os','o.sort_id = os.id')
            ->where($where)
            ->find();
        if(!$orderInfo) {
            $this->redirect(url('to_pay'));
        }
        $orderInfo['options'] = json_decode($orderInfo['options'],true);
        foreach ($orderInfo['options'] as $k=>$v) {
            $optionsInfo = $this->singleData($this->option_table,['id'=>$v['id']]);
            $v['name'] = $optionsInfo['name'];
            $v['html'] = $this->form_model($v);
            if($k <= 5) {
                $orderInfo['groupA'][] = $v;
            } elseif ($k <= 11) {
                $orderInfo['groupB'][] = $v;
            } elseif ($k <= 17) {
                $orderInfo['groupC'][] = $v;
            } else {
                $orderInfo['groupD'][] = $v;
            }
        }
        $this->assign('orderInfo',$orderInfo);
        return $this->fetch();
    }

    /**
     * 提交订单确认码
     *
     * @param $number 订单确认码
     */
    public function check_num() {
        if($this->request->isAjax()) {
            $num = $this->request->param('number');
            $order = Db::name('Order')->where(['number'=>$num])->find();
            if(!$order) {
                $this->error('订单不存在',1);
            }
            $over_time = $order['over_time'];
            if($over_time < time()) {
                $this->error('您的订单确认码已失效',2);
            }
            $this->success('成功',url('order_confirm',['id'=>$order['id']]));
        }
    }

    /**
     * 修改订单修改状态为销售未修改
     *
     * @param $order_sn 订单号
     */
    public function update_change() {
        if($this->request->isAjax()) {
            $order_sn = $this->request->param('order_sn');
            $order = Db::name('Order')->where(['order_sn'=>$order_sn])->find();
            if(!$order) {
                $this->error('订单不存在',1);
            }
            $over_time = $order['over_time'];
            if($over_time < time()) {
                $this->error('您的订单确认码已失效',2);
            }
            $result = Db::name('Order')->where(['order_sn'=>$order_sn])->update(['is_change'=>0,'update_time'=>time()]);
            if(!$result) {
                $this->error('修改状态失败',1);
            }
            $this->success('成功',url('order_confirm',['id'=>$order['id']]));
        }
    }

    /**
     * 获取支付数据
     *
     * @param $order_sn 订单号
     * @param $pay_type 支付类型
     */
    public function pay_param() {
        if($this->request->isAjax()) {
            $data = $this->request->param();
            $order = Db::name('Order')->where(['order_sn'=>$data['order_sn']])->find();
            if(!$order) {
                $this->error('订单不存在','',1);
            }
            $over_time = $order['over_time'];
            if($over_time < time()) {
                $this->error('您的订单确认码已失效','',2);
            }
            // 获取订单金额
            $where = [
                'o.order_sn' => $data['order_sn'],
                'o.delete_time' => 0
            ];
            $orderInfo = Db::name('Order')
                ->alias('o')
                ->field(['o.*,os.name'])
                ->join('__ORDER_SORT__ os','o.sort_id = os.id')
                ->where($where)
                ->find();
            $orderInfo['options'] = json_decode($orderInfo['options'],true);
            $order_price = 0;
            foreach ($orderInfo['options'] as $k=>$v) {
                if($v['id'] == 25) {
                    $order_price = $v['user_choose'];
                }
            }
            if(!$order_price) {
                $this->error('订单无价格,请联系客服人员','',3);
            }
            if($this->is_weixin()) {
                $this->error('暂不支持微信浏览器支付','',4);
            }
            if($data['pay_type'] == 1) {
                require_once VENDOR_PATH.'WxpayAPI/WxpayH5.php';
                $h5 = new \WxpayH5('wx8f31a4eb6d72f174','1512102931','kgAFbJx2MpAxQI2iJBTffrzFwxrnqE4h',$order['order_sn'],
                    '测试支付',$order_price*100,'{"h5_info": {"type":"Wap","wap_url": "http://m.wanlin-edu.com","wap_name": "测试支付"}}' );
                $result = $h5->pay();
                $mweb_url = '';
                if(!empty($result['mweb_url'])) {
                    $mweb_url = $result['mweb_url'];
                }
                $this->success('成功',$mweb_url);
            }
            if($data['pay_type'] == 2) {
                $data = ['order_sn'=>$order['order_sn'],'name'=>'电子订单支付','total_amount'=>$order_price];
//                $alipay = controller('Alipaywap','controller');
//                $result = $alipay->alipay($data);
                $this->success('成功',url('portal/Alipaywap/alipay',$data));
            }
        }
    }

    // 订单确认页面
    public function confirm() {
        $id = $this->request->param('id');
        if(!$id) {
            $this->error('参数错误');
        }
        $order = Db::name('Order')->where(['id'=>$id])->find();
        $this->assign('orderInfo',$order);
        return $this->fetch();
    }

    //支付成功结果页
    public function pay_result() {
        $data = $this->request->param();
        if(empty($data['order_sn'])) {
            $this->error('订单不存在');
        }
        // 获取订单金额
        $where = [
            'order_sn' => $data['order_sn'],
            'delete_time' => 0
        ];
        $orderInfo = Db::name('Order')
            ->where($where)
            ->find();
        if(!$orderInfo) {
            $this->error('订单不存在');
        }
        // 查询订单金额(暂留,后续开发如需显示打开注释、前台直接渲染参数即可)
//        $orderInfo['options'] = json_decode($orderInfo['options'],true);
//        $order_price = 0;
//        foreach ($orderInfo['options'] as $k=>$v) {
//            if($v['id'] == 25) {
//                $order_price = $v['user_choose'];
//            }
//        }
//        $this->assign('orderPrice',$order_price);

        // banner图
        $slide_model = new SlideItemModel();
        $slide_where = [
            'slide_id' => 3,
            'status' => 1
        ];
        $slide = $slide_model->where($slide_where)->order(['list_order'=>'ASC'])->find();
        $this->assign('slide',$slide);
        return $this->fetch();
    }

    /**
     * 判断订单是否已经支付完成
     * @param $order_sn 订单号
     */
    public function check_order_status() {
        if($this->request->isAjax()) {
            $data = $this->request->param();
            $order = Db::name('Order')->where(['order_sn' => $data['order_sn']])->find();
            if ($order['status'] == 1) {
                $this->success('支付成功', url('portal/Order/pay_result',['order_sn'=>$data['order_sn']]));
            }
        }
    }

    // 去支付
    public function to_pay_submit() {
        if($this->request->isAjax()) {
            $id = $this->request->param('id');
            $order = Db::name('Order')->where(['id'=>$id])->find();
            if(!$order) {
                $this->error('订单不存在');
            }
            $over_time = $order['over_time'];
            if($over_time < time()) {
                $this->error('您的订单确认码已失效');
            }
            if($order['is_change'] == 1) {
                $type = 1;
            } else {
                $type = 0;
            }
            $this->success('成功','',$type);
        }
    }

    /**
     * 查询物流页面
     */
    public function order_see() {
        // 生成页面二维码(用户推广)
        $url = url('portal/Order/order_see','','',true);
        $qrcode = $this->createQRcode($url,'Q',9);
        $name = '物流单号查询';
        $this->qrcodePage($url,$name,$qrcode);
        $this->nav_bottom(0,0,1);

        // banner图
        $slide_model = new SlideItemModel();
        $slide_where = [
            'slide_id' => 4,
            'status' => 1
        ];
        $slide = $slide_model->where($slide_where)->order(['list_order'=>'ASC'])->find();
        $this->assign('slide',$slide);
        return $this->fetch();
    }

    /**
     * 查询订单物流
     */
    public function search() {
//        if($this->request->isAjax()) {
        $keyword = $this->request->param('keyword');
        if(!$keyword) {
            $this->error('请输入关键字');
        }
        $logistics_model = new LogisticsModel();
        $where = [
            'delete_time'=>0,
            'is_del'=>0,
            'mobile' => $keyword
        ];
        $list = $logistics_model->where($where)->order(['send_time'=>'DESC'])->limit(3)->select();
        $this->assign('list',$list);
        return $this->fetch();
//        }
    }

    // 处理订单模型数据
    private function form_model($formData) {
        $html = $this->sort_model[$formData['type']];
        $html = str_replace('{name}',$formData['name'],$html);
        if($formData['checked'] == 1) {
            $html = str_replace('{must}','*',$html);
            $html = str_replace('{validate}',1,$html);
        } else {
            $html = str_replace('{must}','',$html);
            $html = str_replace('{validate}',0,$html);
        }
        if(!empty($formData['values']) && $formData['values'] != null) {
            $array = explode(',',$formData['values']);
            $options = '';
            foreach ($array as $k=>$v) {
                $active = isset($formData['user_choose'])?($formData['user_choose']==$v?'active':''):($k==0?'active':'');
                $options .= '<p class="order_style '.$active.'">'.$v.'</p>';
            }
            $html = str_replace('{options}',$options,$html);
        }
        if(!empty($formData['user_choose'])) {
            $html = str_replace('{value}',$formData['user_choose'],$html);
        } else {
            $html = str_replace('{value}','',$html);
        }
        return $html;
    }
}