<?php
/**
 * Created by PhpStorm.
 * User: 思维定制
 * Date: 2018/9/5
 * Time: 18:03
 */

namespace App\Http\Controllers\Web;


use App\Models\MedicalComboModel;
use App\Models\MedicalOrderModel;
use App\Models\MedicalSingleCateModel;
use App\Models\MedicalSingleProjectModel;
use Illuminate\Support\Facades\Cache;
use App\Models\MedicalSmsConfModel;
use Illuminate\Http\Request;
use Auth, Validator;
use Carbon\Carbon;
use GuzzleHttp\Client as GuzzleHttpClient;
use GuzzleHttp\Exception\RequestException;

class OrderController extends Controller
{
    public $keySmsCodeExist = 'keySmsCodeExist';

    public $expireTimeExist = '';

    public $keySmsCode = 'keySmsCode';

    public $expireTime = '';

    public function index(Request $request)
    {
        if($request->method() == 'POST') {
            $data = $request->input();
            $key = $this->keySmsCode . $data['mobile'];
            $code = Cache::store('file')->get($key);
           /* if ($code !== $data['verify']) {
                $res['state'] = 0;
                $res['err'] = '验证码错误！';
                return $this->api($res);
            }*/
            $check = MedicalOrderModel::where('mobile',$data['mobile'])->first();

            if($check&&!empty($check->pdf)){
                $res['state'] = 2;
                $res['err'] = '您已提交';
                $res['redirect_url'] = url('web/Index/post').'?id='.$check->id;
                $res['download_url'] = url('web/Index/download').'?id='.$check->id;
                $res['pdf_url'] = $check->pdf;
            }elseif($check&&empty($check->pdf)){
                $res['state'] = 1;
                $res['err'] = '您已提交,请耐心等待结果';
                $res['redirect_url'] = url('web/Index/post').'?id='.$check->id;
            }elseif(!$check){
                $res['state'] = 1;
                $res['err'] = '请您先填写基本资料';
                $res['redirect_url'] = url('web/Index/sms').'?mob='.$data['mobile'];
            }
            return $this->api($res);
        }else{
            return view('web.order.sms');
        }
    }

    public function download(Request $request)
    {
        $id = $request->get('id');
        $check = MedicalOrderModel::find($id);
        if(!empty($check)&&!empty($check->pdf)){
            $url = str_replace(env('APP_URL'),public_path(),$check->pdf);
            return response()->download($url);
        }

    }

    public function sms(Request $request){

        $conf['nationality'] = '民族';
        $conf['name'] = '姓名';
        $conf['native_place'] = '籍贯';
        $conf['email'] = '邮件';
        $conf['work'] = '工作';
        $conf['address'] = '通讯地址';


        if($request->method() == 'POST') {
            $data = $request->input();

            $style = explode(',',$data['sample_type']);
            $str = '';
            foreach ($style as $key=>$val){
                if($val==1){
                    $str.= 'EDTA抗凝静脉血';
                }
                if($val==2){
                    $str.= '口腔拭子';
                }
                if($val==3){
                    $str.= '宫颈刷';
                }
            }
            //dd($style);
            $data['sample_type'] = $str;
            foreach ($data as $key=>$val){
                if(empty($val)&&$key!='sample_type'&&$key!='sex'){
                    $res['state'] = 0;
                    $res['err'] = $conf[$key].'不能为空！';
                    return $this->api($res);
                }
            }

            $query = MedicalOrderModel::create($data);
            if($query){
                $res['state'] = 1;
                $res['err'] = '提交成功';
                $res['redirect_url'] = url('web/Index/post').'?id='.$query->id;
            }else{
                $res['state'] = 0;
                $res['err'] ='网络错误';
            }

          //  dd($res);
            return $this->api($res);
        }else{
            $mobile = $request->input();

            return view('web.order.index',compact('mobile'));
        }
    }
    public function post(Request $request){
        if($request->method() == 'POST'){
            $data = $request->input();
            if(!empty($data['tcan'])){
                foreach ($data['tcan'] as $key_all=>$val_all){
                    $tcan[] = MedicalComboModel::find($val_all);
                }
                $Update['combo'] = serialize($tcan);
            }

            if(!empty($data['xiangmu'])){
                foreach ($data['xiangmu'] as $key_single=>$val_single){
                    $single[] = MedicalSingleProjectModel::find($val_single);
                }
                $Update['single'] = serialize($single);
            }



            $Update['total_price'] = $data['total_price'];
            $res = MedicalOrderModel::where('id',$data['id'])->update($Update);
            if($res){
                $q['msg'] = '提交成功';
            }else{
                $q['msg'] = '提交失败';
            }
           // dd($q);
            return view('web.order.complete',compact('q'));
        }
        $id = $request->get('id');
        if(empty($id)){
            return redirect('web/Index/index');
        }
        $checkorder = MedicalOrderModel::find($id);

        if($checkorder&&(!empty($checkorder['single'])||!empty($checkorder['combo']))){
            $single = unserialize($checkorder['single']);
            $combo = unserialize($checkorder['combo']);
            foreach ($single as $k_s=>$v_s){
                $singles[]=(object)[
                    'id'=>$v_s['id'],
                    'name'=>$v_s['name'],
                    'price'=>$v_s['oldPrice'],
                    'youhui'=>$v_s['realPrice']
                ];
            }
            foreach ($combo as $k_c=> $v_c){
                $combos[]=(object)[
                    'id'=>$v_c['id'],
                    'name'=>$v_c['name'],
                    'neirong'=>$v_c['content'],
                    'jiage'=>$v_c['oldPrice'],
                    'youhui'=>$v_c['realPrice']
                ];
            }
            $data_single = json_encode($single);
            $data_combo = json_encode($combo);
//        dd($data_single);
            return view('web.order.result',compact('data_single','data_combo'));
        }
        $cat = MedicalSingleCateModel::all();
        $data_single=array();
        foreach ($cat as $key=>$val){
            $projects = MedicalSingleProjectModel::where('cate_id',$val['id'])->get();
            $project = array();
            foreach($projects as $k=>$v){
                $project[]=(object)[
                    'id'=>$v['id'],
                    'name'=>$v['name'],
                    'price'=>$v['oldPrice'],
                    'youhui'=>$v['realPrice']
                ];
            }
            $data_single[]=(object)[
                'name'=>$val['name'],
                'data'=>$project
            ];
        }
        $data_combos = MedicalComboModel::all();
        $data_combo = array();
        foreach ($data_combos as $k_c=>$v_c){
            $data_combo[]=(object)[
                'id'=>$v_c['id'],
                'name'=>$v_c['name'],
                'neirong'=>$v_c['content'],
                'jiage'=>$v_c['oldPrice'],
                'youhui'=>$v_c['realPrice']
            ];
        }
        $data_single = json_encode($data_single);
        $data_combo = json_encode($data_combo);
//        dd($data_single);
        return view('web.order.post',compact('data_single','data_combo','id'));
    }

    /**
     ***聚合数据
     ***DATE:2015-05-25
     */
    public function smsJuHe(Request $request)
    {
        $data = $request->input();
        $conf = MedicalSmsConfModel::find(1);
        header('content-type:text/html;charset=utf-8');

        $sendUrl = 'http://v.juhe.cn/sms/send'; //短信接口的URL
        $num = rand(1000,9999);
        Cache::put($data['mobile'].'post',$num,10000);
        $smsConf = array(
            'key'   => $conf->apikey, //您申请的APPKEY
            'mobile'    => $data['mobile'], //接受短信的用户手机号码
            'tpl_id'    => $conf->temp_id, //您申请的短信模板ID，根据实际情况修改
            'tpl_value' =>'#code#=1234&#company#='.$conf->sign //您设置的模板变量，根据实际情况修改
        );

        $content = $this->juhecurl($sendUrl,$smsConf,1); //请求发送短信
        //$content=false;
        if($content){
            $result = json_decode($content,true);
            $error_code = $result['error_code'];
            if($error_code == 0){
                //状态为0，说明短信发送成功
                $res['state'] = 1;
            }else{
                //状态非0，说明失败
                $msg = $result['reason'];
                $res['err'] = "短信发送失败(".$error_code.")：".$msg;
                $res['state'] = 0;
            }
        }else{
            $res['state'] = 0;
            $res['err'] = '发送失败';
        }
        return $this->api($res);
    }

    /*
         * 获取验证码
         */
    public function getCode(Request $request)
    {
        //对手机号码进行验证
        $validator = Validator::make($request->all(),
            [
                'mobile' => 'required|regex:/^1[34578]\d{9}$/',
            ],
            [
                'mobile.required' => '手机号码必填',
                'mobile.regex' => '手机号码格式不正确',
            ]
        );


        if ($validator->fails()) {
            $msgs = $validator->errors()->first();
            return json_encode(['code' => 0, 'msg' => $msgs]);
        }
        $phone = $request->get('mobile');

        $ipkeyexist = $this->keySmsCodeExist . $_SERVER["REMOTE_ADDR"] . Carbon::now()->toDateString();

        $times = Cache::store('file')->get($ipkeyexist);
        if($times>10) {
            return json_encode(['state' => 0, 'msg' => '一天内一个ip最多发送十次验证码']);
        }else{
            $times++;
            Cache::store('file')->put($ipkeyexist, $times, 60 * 24);
        }

        $keyexist = $this->keySmsCodeExist . $phone . Carbon::now()->toDateString();;
        $times = Cache::store('file')->get($keyexist);
        if($times>8) {
            return json_encode(['state' => 0, 'msg' => '一天内最多发送八次验证码']);
        }else{
            $times++;
            Cache::store('file')->put($keyexist, $times, 60 * 24);
        }

        $verify_code = (string)mt_rand(1000, 9999);
        $key = $this->keySmsCode . $phone;
        Cache::store('file')->put($key, $verify_code, 6000);
        $msg = '【精准医疗】您的验证码是：' . $verify_code;

        $result = $this->sendSms($msg, $phone);
//        \Log::info($msg . " res:" . $result);
        if (!$result) return json_encode(['state' => 0, 'msg' => '短信发送失败']);

        return json_encode(['state' => 1, 'msg' => '短信发送成功']);
    }

    /*
         * 发送短信
         */
    public function sendSms($msg, $mobile) {
        $url = "http://api.106txt.com/smsGBK.aspx?";
        $account = "swufecredit2017";
        $password = "mask751002";
        $password = strtoupper(md5($password));
        $gwid = 53;
        $message = iconv("UTF-8", "GB2312", $msg);

        try {
            $client = new GuzzleHttpClient();
            $data = [
                'action'      => 'Send',
                'username'        => $account,
                'password'       => $password,
                'gwid'      => $gwid,
                'mobile'    => $mobile,
                'message'       => $message,
            ];
            $apiRequest = $client->post($url, [
                'form_params'      => $data,
            ]);
            $resp = $apiRequest->getBody()->getContents();
            $res = iconv("GB2312", "UTF-8", $resp);
            $re = json_decode($res, true);
            \Log::info("发送短信 到手机:$mobile 内容:$msg RESULT:".$re['RESULT']);
            if (trim($re['CODE']) == '1') {
                return true;
            }
        } catch (RequestException $re) {
            \Log::info("发送短信错误:".$re->getMessage());
            return false;
        }
        return false;
    }

    /**
     * 请求接口返回内容
     * @param  string $url [请求的URL地址]
     * @param  string $params [请求的参数]
     * @param  int $ipost [是否采用POST形式]
     * @return  string
     */
    function juhecurl($url,$params=false,$ispost=0){
        $httpInfo = array();
        $ch = curl_init();
        curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
        curl_setopt( $ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22' );
        curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 );
        curl_setopt( $ch, CURLOPT_TIMEOUT , 30);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
        if( $ispost )
        {
            curl_setopt( $ch , CURLOPT_POST , true );
            curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
            curl_setopt( $ch , CURLOPT_URL , $url );
        }
        else
        {
            if($params){
                curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
            }else{
                curl_setopt( $ch , CURLOPT_URL , $url);
            }
        }
        $response = curl_exec( $ch );
        if ($response === FALSE) {
            //echo "cURL Error: " . curl_error($ch);
            return false;
        }
        $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
        $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
        curl_close( $ch );
        return $response;
    }
}