<?php
/**
 * Created by PhpStorm.
 * User: 29925
 * Date: 2018/9/10
 * Time: 18:02
 */

namespace app\portal\controller;

use app\admin\model\OrderModel;
use app\admin\model\OrderSortModel;
use cmf\controller\HomeBaseController;
use cmf\lib\Upload;
use think\Cache;
use think\Db;
use think\Session;
use traits\controller\Jump;

class MemberSalesController extends HomeBaseController
{
    protected $beforeActionList = [
        'check_login' => ['except' => 'index'],
    ];
    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="" readonly 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" data-validate="{validate}">
			<input type="hidden" name="" value="{value}" id="up_wrap"/>
			<input type="file" class="my_upload"/>
            <div class="up_pic" style="{img_height}">
                {img}
            </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>';
    }
    // 前置方法(判断是否登录销售账号)
    protected function check_login()
    {
        if(!cmf_is_user_sale_login()) {
            $this->redirect(url('portal/MemberSales/index'));
        }
    }

    // 登录
    public function index() {
        if(cmf_is_user_sale_login()) {
            $this->redirect(url('portal/MemberSales/order_type'));
        }
        // 生成页面二维码(用户推广)
        $url = url('portal/MemberSales/index','','',true);
        $qrcode = $this->createQRcode($url,'Q',9);
        $name = '销售人员';
        $this->qrcodePage($url,$name,$qrcode);
        return $this->fetch();
    }

    // 选择类型
    public function order_type() {
        $typeList = $this->singleData($this->table,['delete_time'=>0],1);
        $this->assign('typeList',$typeList);
        return $this->fetch();
    }

    // 填写电子订单
    public function write() {
        $id = $this->request->param('id',0,'intval');
        if(!$id) {
            $this->redirect(url('portal/MemberSales/order_type'));
        }
        // 生成订单确认码
        $this->create_order_sn();
        $where = [
            'id' => $id,
            'delete_time' => 0
        ];
        $typeInfo = $this->singleData($this->table,$where);
        $typeInfo['options'] = json_decode($typeInfo['options'],true);
        $goodsList = [];
        $default = 0;
        foreach ($typeInfo['options'] as $k=>$v) {
            // 获取商品选项,用于前台渲染
            if($v['id'] == 19) {
                $list = explode(',',$v['values']);
                foreach ($list as $kg=>$vg) {
                    $goodsInfo = [
                        'label' => $vg,
                        'value' => $kg
                    ];
                    if(!empty($v['user_choose']) && $v['user_choose'] == $vg) {
                        $default = $kg;
                    }
                    $goodsList[] = $goodsInfo;
                }
            }
            $optionsInfo = $this->singleData($this->option_table,['id'=>$v['id']]);
            $v['name'] = $optionsInfo['name'];
            $v['html'] = $this->form_model($v);
            if($k <= 5) {
                $typeInfo['groupA'][] = $v;
            } elseif ($k <= 11) {
                $typeInfo['groupB'][] = $v;
            } elseif ($k <= 17) {
                $typeInfo['groupC'][] = $v;
            } else {
                $typeInfo['groupD'][] = $v;
            }
        }
        $this->assign('default',$default);
        $this->assign('goodsList',json_encode($goodsList));
        $this->assign('myOrderUrl',url('portal/MemberSales/deal',['id'=>$id]));
        $this->assign('typeInfo',$typeInfo);
        return $this->fetch();
    }

    // 生成订单确认码存入session,并判断是否属于已生效订单
    private function create_order_sn() {
        $order_sn = $this->generate_code(8);
        if(Cache::get('number')) {
            if(in_array($order_sn,Cache::get('number'))) {
                $this->create_order_sn();
            }
        }
        Session::set('user_sale.number',$order_sn);
        return $order_sn;
    }

    // 提交电子订单
    public function submit_form() {
        if($this->request->isAjax()) {
            $id = $this->request->param('id',0,'intval');
            $type = $this->request->param('_type');
            $data = explode(',',$this->request->param('param'));
            if(!$id) {
                $this->error('请选择电子订单类型');
            }
            $order_sort_where = [
                'id' => $id,
                'delete_time' => 0
            ];
            $typeInfo = $this->singleData($this->table,$order_sort_where);
            if(!$typeInfo) {
                $this->error('电子订单类型错误');
            }
            $mobile = '';
            $typeInfo['options'] = json_decode($typeInfo['options'],true);
            foreach ($typeInfo['options'] as $k=>$v) {
                if($v['id'] == 10) {
                    $mobile = $data[$k];
                }
                $typeInfo['options'][$k]['user_choose'] = $data[$k];
            }
            $order_insert = [
                'user_id'   => cmf_get_current_user_sale_id(),
                'sort_id'   => $typeInfo['id'],
                'options'   => json_encode($typeInfo['options']),
                'order_sn'  => cmf_get_order_sn(),
                'number'    => Session::get('user_sale.number'),
                'over_time' => time() + 60*60*24*2
            ];
            $validate = $this->validate($order_insert, 'admin/'.$this->order_table,'.add');
            if ($validate !== true) {
                $this->error($validate);
            }
            $result = $this->order_model->addOrder($order_insert);
            if(!$result) {
                $this->error('电子订单生成失败');
            }
            $order_where = [
                'status' => 0,
                'over_time' => ['egt',time()],
                'delete_time' => 0
            ];
            $url = url('portal/Order/to_pay',[],true,true);
            $short_url = json_decode(file_get_contents('http://suo.im/api.php?format=json&url='.urlencode($url)),true)['url'];
            $text = '订单确认码:'.Session::get('user_sale.number').'.点击 '.$short_url.' 或关注【宛林游乐】完成支付.详询4001107575.';
            $this->sendSMSS($mobile,$text);
            $numberList = $this->order_model->where($order_where)->column('number');
            Cache::set('number',$numberList);
            $this->success('订单生成成功','',Session::get('user_sale.number'));
        }
    }

    // 查看已提交订单
    public function deal() {
        $id = $this->request->param('id',0,'intval');
        if(!$id) {
            $this->redirect(url('portal/MemberSales/order_type'));
        }
        $user_id = cmf_get_current_user_sale_id();
        $order_where = [
            'o.user_id' => $user_id,
            'o.is_stop' => 0,
            'o.delete_time' => 0
        ];
        $orderList = $this->order_model
            ->alias('o')
            ->field(['o.id,o.order_sn,o.status,o.create_time,o.over_time,os.name'])
            ->join('__ORDER_SORT__ os','o.sort_id = os.id')
            ->where($order_where)
            ->order(['create_time'=>'DESC'])
            ->select();
        $this->assign('sort_id',$id);
        $this->assign('orderUrl',url('portal/MemberSales/write',['id'=>$id]));
        $this->assign('orderList',$orderList);
        return $this->fetch();
    }

    /**
     * 订单选择提交时间接口
     * @param date
     */
    public function choosetime_detail() {
        if($this->request->isAjax()) {
            $date = $this->request->param('date');
            $sort_id = $this->request->param('sort_id');
            $user_id = cmf_get_current_user_sale_id();
            $order_where = [
                'o.user_id' => $user_id,
                'o.create_time' => ['between',strtotime($date).','.strtotime("$date +1 day")],
                'o.is_stop' => 0,
                'o.delete_time' => 0
            ];
            $orderList = $this->order_model
                ->alias('o')
                ->field(['o.id,o.order_sn,o.status,o.create_time,o.over_time,os.name'])
                ->join('__ORDER_SORT__ os','o.sort_id = os.id')
                ->where($order_where)
                ->select();
            foreach ($orderList as $k=>$v) {
                $orderList[$k]['detail_url'] = url('detail',['id'=>$sort_id,'order_id'=>$v['id']]);
                $orderList[$k]['edit_url'] = url('edit',['id'=>$sort_id,'order_id'=>$v['id']]);
                $orderList[$k]['create_time'] = date('Y-m-d',$v['create_time']);
            }
            $this->success('成功',strtotime($date),$orderList);
        }
    }

    // 订单详情
    public function detail() {
        $id = $this->request->param('id',0,'intval');
        if(!$id) {
            $this->redirect(url('portal/MemberSales/order_type'));
        }
        $order_id = $this->request->param('order_id',0,'intval');
        if(!$order_id) {
            $this->redirect(url('portal/MemberSales/deal'));
        }
        $where = [
            'id' => $order_id,
            'delete_time' => 0
        ];
        $orderInfo = $this->singleData($this->order_table,$where);
        $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'];
            if($k <= 5) {
                $orderInfo['groupA'][] = $v;
            } elseif ($k <= 11) {
                $orderInfo['groupB'][] = $v;
            } elseif ($k <= 17) {
                $orderInfo['groupC'][] = $v;
            } else {
                $orderInfo['groupD'][] = $v;
            }
        }
        $this->assign('order_id',$order_id);
        $this->assign('orderInfo',$orderInfo);
        return $this->fetch();
    }

    // 修改订单
    public function edit() {
        $id = $this->request->param('id',0,'intval');
        if(!$id) {
            $this->redirect(url('portal/MemberSales/order_type'));
        }
        $order_id = $this->request->param('order_id',0,'intval');
        if(!$order_id) {
            $this->redirect(url('portal/MemberSales/deal'));
        }
        $where = [
            'o.id' => $order_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();
        $orderInfo['options'] = json_decode($orderInfo['options'],true);
        $goodsList = [];
        foreach ($orderInfo['options'] as $k=>$v) {
            // 获取商品选项,用于前台渲染
            if($v['id'] == 19) {
                $list = explode(',',$v['values']);
                foreach ($list as $kg=>$vg) {
                    $goodsInfo = [
                        'label' => $vg,
                        'value' => $kg
                    ];
                    if(!empty($v['user_choose']) && $v['user_choose'] == $vg) {
                        $goodsInfo['disabled'] = true;
                    }
                    $goodsList[] = $goodsInfo;
                }
            }
            // 处理表单数据
            $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('goodsList',json_encode($goodsList));
        $this->assign('order_id',$order_id);
        $this->assign('myOrderUrl',url('portal/MemberSales/deal',['id'=>$id]));
        $this->assign('orderInfo',$orderInfo);
        return $this->fetch();
    }

    // 编辑提交电子订单
    public function submit_form_edit() {
        if($this->request->isAjax()) {
            $id = $this->request->param('id',0,'intval');
            $data = explode(',',$this->request->param('param'));
            if(!$id) {
                $this->error('请选择电子订单类型');
            }
            $order_where = [
                'id' => $id,
                'delete_time' => 0
            ];
            $orderInfo = $this->singleData($this->order_table,$order_where);
            if(!$orderInfo) {
                $this->error('电子订单错误');
            }
            if($orderInfo['status'] == 1) {
                $this->success('用户已支付订单','',2);
            }
            if($orderInfo['is_stop'] == 1) {
                $this->success('当前功能已暂停','',3);
            }
            $orderInfo['options'] = json_decode($orderInfo['options'],true);
            foreach ($orderInfo['options'] as $k=>$v) {
                $orderInfo['options'][$k]['user_choose'] = $data[$k];
            }
            $order_update = [
                'id'        => $id,
                'options'   => json_encode($orderInfo['options']),
                'is_change' => 1
            ];
            $validate = $this->validate($order_update, 'admin/'.$this->order_table.'.edit');
            if ($validate !== true) {
                $this->error($validate);
            }
            $result = $this->order_model->editOrder($order_update);
            if(!$result) {
                $this->error('电子订单修改失败');
            }
            $this->success('订单修改成功','',1);
        }
    }

    // 处理订单模型数据
    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'])) {
            if($formData['type'] == 8) {
                $img = '<img src="'.cmf_get_asset_url($formData['user_choose']).'" width="100%" height="100%"/>';
                $html = str_replace('{img}',$img,$html);
                $html = str_replace('{img_height}','height:auto;',$html);
            }
            $html = str_replace('{value}',$formData['user_choose'],$html);
        } else {
            if($formData['type'] == 8) {
                $img = '<i class="iconfont icon-msnui-cloud-upload"></i>
                <p class="click_up">点击上传</p>';
                $html = str_replace('{img}',$img,$html);
                $html = str_replace('{img_height}','',$html);
            }
            $html = str_replace('{value}','',$html);
        }
        return $html;
    }

    /**
     * 上传素材
     * @method POST

     * @param name:file type:varchar require:1 default: other: desc:素材内容
     * @param name:filetype type:varchar require:1 default: other: desc:素材类型
     * @param name:app type:varchar require:1 default: other: desc:素材存储路径
     *
     * @return title:标题
     *
     */
    public function upload() {
        if ($this->request->isPost()) {
            $uploader = new Upload();
//            return ["code"=>40004, "msg"=>$this->request->param(), "data"=>[$this->request->file()]];

            $result = $uploader->upload();

            if ($result === false) {
                echo json_encode(["code"=>40004, "msg"=>$uploader->getError(), "data"=>[]]);exit;
            } else {
                echo json_encode(["code"=>1, "msg"=>"上传成功!", "data"=>[$result]]);exit;
            }
        }
    }
}