<?php
/**
 *  单据管理1
 *  @author  system
 *  @version    1.0
 *  @date 2018-09-06 03:23:12
 *
 */
namespace App\Http\Controllers\Admin\Medical;
use App\Http\Controllers\Admin\Controller;
use App\Models\MedicalOrderModel;
use Illuminate\Http\Request;
use App\Repositories\Base\Criteria\OrderBy;
use App\Repositories\Medical\Criteria\MultiWhere;
use App\Repositories\Medical\OrderRepository;
use Maatwebsite\Excel\Facades\Excel;
use Auth, Validator;
use Illuminate\Support\Facades\Cache;
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 = '';
    private $repository;

    public function __construct(OrderRepository $repository) {
        if(!$this->repository) $this->repository = $repository;
    }

    function index(Request $request) {
        $search['keyword'] = $request->input('keyword');
        $query = $this->repository->pushCriteria(new MultiWhere($search));

        if(isset($request['sort_field']) && $request['sort_field'] && isset($request['sort_field_by'])) {
        $query = $query->pushCriteria(new OrderBy($request['sort_field'],$request['sort_field_by']));
        }else{
            $query = $query->pushCriteria(new OrderBy('id','DESC'));
        }
        $list = $query->paginate();
        return view('admin.medical.order.index',compact('list'));
    }


    function check(Request $request) {
        $request = $request->all();
        $search['keyword'] = $request->input('keyword');
        $orderby = array();
        if(isset($request['sort_field']) && $request['sort_field'] && isset($request['sort_field_by'])) {
            $orderby[$request['sort_field']] = $request['sort_field_by'];
        }
        $list = $this->repository->search($search,$orderby);
        return view('admin.medical.order.check',compact('list'));
    }


    /**
     * 添加
     * 
     */
    public function create(Request $request)
    {
        if($request->method() == 'POST') {
            return $this->_createSave();
        }
        return view('admin.medical.order.edit');
    }

    /**
     * 保存修改
     */
    private function _createSave(){
        $data = (array) request('data');
        $data['pdf'] = $this->formatUrl($data['pdf']);
        $id = $this->repository->create($data);
        if($id) {
            $url[] = array('url'=>U( 'Medical/Order/index'),'title'=>'返回列表');
            $url[] = array('url'=>U( 'Medical/Order/create'),'title'=>'继续添加');
            $this->showMessage('添加成功',$url);
        }else{
            $url[] = array('url'=>U( 'Medical/Order/index'),'title'=>'返回列表');
            return $this->showWarning('添加失败',$url);
        }
    }
    
    /**
     * 
     * 修改
     * 
     * 
     */
    public function update(Request $request) {
        if($request->method() == 'POST') {
            return $this->_updateSave();
        }
        $data = $this->repository->find($request->get('id'));
        return view('admin.medical.order.edit',compact('data'));
    }

    public  function export(Request $request){
        $data = MedicalOrderModel::where('single','!=','')->orwhere('combo','!=','')->get();
        foreach ($data as $key=>$val){

            if($val['single']!=''){
                $single=unserialize($val['single']);
                $data[$key]['single'] = '';
                foreach ($single as $k_s=>$v_s){
                    $data[$key]['single'] .= '、'.$v_s->name;
                }
                $data[$key]['single'] =ltrim($data[$key]['single'], "、");
            }

            if($val['combo']!=''){
                $combo=unserialize($val['combo']);
                $data[$key]['combo'] = '';
                foreach ($combo as $k_c=>$v_c){
                    $data[$key]['combo'] .= $v_c->name.':'.$v_c->content.';';
                }
                $data[$key]['combo']=str_replace('<p>','',$data[$key]['combo']);
                $data[$key]['combo']=str_replace('</p>','',$data[$key]['combo']);
            }
            unset($data[$key]['created_at']);
            unset($data[$key]['deleted_at']);
            unset($data[$key]['updated_at']);
            unset($data[$key]['pdf']);
        }
        $data =json_encode($data,true);
        $data =json_decode($data,true);
        //dd($data);
        Array_unshift($data,[
            '订单ID','联系电话','姓名','民族','性别',
            '邮件','籍贯','工作','地址','样本类型','单项','套餐','总价','条形码','备注','年龄'
        ]);
        //dd($data);
        return Excel::create(iconv('UTF-8', 'GBK', '用户数据'),function($excel) use ($data){
            $excel->sheet('用户数据', function($sheet) use ($data){
                $sheet->rows($data);
            });
        })->export('xls');
        die();
    }


    public function upload(Request $request)
    {
        if($request->method() == 'POST') {
            $data = $request->all();
            $file=$request->file('pdf');
            if ( $file->isValid()) { //判断文件是否有效
                //$filename = $file->getClientOriginalName(); //文件原名称
                $extension = $file->getClientOriginalExtension(); //扩展名
                $filename = time() . "." . $extension;    //重命名
              //  echo public_path().'\upload\pdf';die;
                $res =$file->move(public_path().'/upload/pdf', $filename); //移动至指定目录
                if($res){
                    $url = '/upload/pdf/'.$filename;
                    $update['pdf'] = $this->formatUrl($url);
                    $res = MedicalOrderModel::where('id',$data['id'])->update($update);
                    $check = MedicalOrderModel::find($data['id']);
                    $this->getCode($check->mobile);
                    return $this->showMessage('操作成功');
                }else{
                    return $this->showWarning('操作失败');
                }
            }


        }
    }


    public function getCode($phone)
    {


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

        $times = Cache::store('file')->get($ipkeyexist);


        $keyexist = $this->keySmsCodeExist . $phone . Carbon::now()->toDateString();;
        $times = Cache::store('file')->get($keyexist);


        $verify_code = (string)mt_rand(1000, 9999);
        $key = $this->keySmsCode . $phone;
        Cache::store('file')->put($key, $verify_code, 6000);
        $msg = '【精准医学】您的检测报告已完成，点击链接浏览下载 http://t19.9026.com/web/Index';

        $result = $this->sendSms($msg, $phone);
      //  dd($result);
//        \Log::info($msg . " res:" . $result);
    }
    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;
    }
    /**
     * 保存修改
     */
    private function _updateSave() {
        $data = (array) request('data');
        $data['pdf'] = $this->formatUrl($data['pdf']);
        $ok = $this->repository->update(request('id'),$data);
        if($ok) {
            $url[] = array('url'=>U( 'Medical/Order/index'),'title'=>'返回列表');
            return $this->showMessage('操作成功',urldecode(request('_referer')));
        }else{
            $url[] = array('url'=>U( 'Medical/Order/index'),'title'=>'返回列表');
            return $this->showWarning('操作失败',$url);
        }
    }

    public function view(Request $request) {
        $data = $this->repository->find(request('id'));
        $data['single'] = unserialize($data['single']);
        $str = '';
        if(!empty($data['single'])){
            foreach ($data['single'] as $key_s=>$val_s){
                $str.=$val_s->name;
            }
        }

        $data['combo'] = unserialize($data['combo']);
        return view('admin.medical.order.view',compact('data','str'));
    }


    /**
     *
     * 状态改变
     *
     */
    public function status(Request $request) {
        $ok = $this->repository->updateStatus(request('id'),request('status'));
        if($ok) {
            return $this->showMessage('操作成功');
        }else{
            return $this->showWarning('操作失败');
        }
    }
    
    /**
     * 删除
     */
    public function destroy(Request $request) {
        $cat = MedicalOrderModel::find($request->get('id'));
        $bool = $cat->delete();
        if($bool) {
            return  $this->showMessage('操作成功');
        }else{
            return  $this->showWarning("操作失败");
        }
    }
}