<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use app\common\library\Email;
/**
 * 售课预约订单
 *
 * @icon fa fa-circle-o
 */
class Lessonorder extends Backend
{

    /**
     * Lessonorder模型对象
     * @var \app\admin\model\Lessonorder
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Lessonorder;
        $this->view->assign("orderStatusList", $this->model->getOrderStatusList());
        $this->view->assign("paytypeList", $this->model->getPaytypeList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage,则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['user','slot','lesson','coach'])
                    ->where($where)
                    ->where('lessonorder.order_status','NEQ',0)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('user')->visible(['firstname','lastname']);
				$row->getRelation('slot')->visible(['starttime','endtime']);
				$row->getRelation('lesson')->visible(['name','name_en']);
				$row->getRelation('coach')->visible(['nickname']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 取消
     */
    public function cancel(){
        $id = input('id');
        $info = Db::name('lesson_order')->where('id',$id)->where('order_status',10)->find();
        if(!$info){
            $this->error('请刷新重试');
        }

        if($this->request->isPost()){
            $cancel_reason = input('cancel_reason','');
            $cancel_time   = strtotime(input('cancel_time',''));

            Db::startTrans();

            //找到所有的已报名订单
            $info = Db::name('lesson_order')->where('id',$id)->where('order_status',10)->lock(true)->find();
            if(empty($info)){
                Db::rollback();
                $this->error('请刷新重试');
            }

            //套餐给加回去
            if($info['paytype'] == 1){
                $package_order = Db::name('package_order')->where('id',$info['package_order_id'])->lock(true)->find();
                $update = [
                    'remain' => bcadd($package_order['remain'],$info['usernumber_hours'],1),
                    'updatetime' => time(),
                ];
                $rs_remain = Db::name('package_order')->where('id',$info['package_order_id'])->update($update);
                if($rs_remain === false){
                    Db::rollback();
                    $this->error('取消失败');
                }
            }
            //试课给改回去
            if($info['paytype'] == 4){
                $update = [
                    'order_status' => 10,
                    'updatetime' => time(),
                    'lesson_order_id' => 0,
                ];
                $rs_remain = Db::name('trylesson_order')->where('id',$info['trylesson_order_id'])->update($update);
                if($rs_remain === false){
                    Db::rollback();
                    $this->error('取消失败');
                }
            }

            //现金支付不给退,线下处理

            //取消预约单
            $update2 = [
                'order_status' => 30,
                'cancel_time' => $cancel_time,
                'cancel_reason' => $cancel_reason,
            ];
            if($info['paytype'] == 1 || $info['paytype'] == 4){
                $update2['order_status'] = 40;
            }


            $rs = Db::name('lesson_order')->where('id',$info['id'])->update($update2);
            if($rs === false){
                Db::rollback();
                $this->error('取消失败');
            }

            Db::commit();

            $slot_info = Db::name('lesson_slot')->where('id',$info['slot_id'])->find();
            $lesson_info = Db::name('lesson')->where('id',$slot_info['lesson_id'])->find();

            //给用户发通知
            $user_info = Db::name('user')->where('id',$info['user_id'])->find();
            if(!empty($user_info['email'])){

                try {
                    $obj = new Email();
                    $result = $obj
                        ->to($user_info['email'])
                        ->subject('Class is Cancelled!')
                        ->message('Hi,'.$user_info['firstname']. ' ' .$user_info['lastname'].',您预约的'.$lesson_info['name'].'已取消')
                        ->send();

                    $coach_name = Db::name('coach')->where('id',$slot_info['coach_ids'])->value('nickname');

                    //发whatsapp
                    $parameters = [
                        [
                            'type' => 'text',
                            'text' => $user_info['firstname'].' '.$user_info['lastname'],
                        ],
                        [
                            'type' => 'text',
                            'text' => $lesson_info['name_en'],
                        ],
                        [
                            'type' => 'text',
                            'text' => $coach_name,
                        ],
                        [
                            'type' => 'text',
                            'text' => date('Y-m-d H:i',$slot_info['starttime']),
                        ],
                    ];
                    $this->whatapp($user_info['whatsapp'],'class_cancelled','en_US',$parameters);

                } catch (Exception $e) {

                }
            }


            $this->success('取消完成');

        }

        $this->view->assign('row',$info);
        return $this->view->fetch();
    }

    private function whatapp($receive_mobile,$template,$code,$parameters){
        if(empty($receive_mobile)){return true;}

        $token = config('site.whatsapp_token');

        //发送者
        $mobile_id = '337736419413019'; //Elin Dance Stuido 2:+65 8015 4154  ,  WhatsApp Business Account ID: 336509229537586

        //发送
        $url = 'https://graph.facebook.com/v19.0/'.$mobile_id.'/messages';
        $header = [
            'Authorization: Bearer ' . $token,
            'Content-Type: application/json',
        ];
        $body = [
            'messaging_product' => 'whatsapp',
            'recipient_type' => 'individual',
            'to' => $receive_mobile,
            'type' => 'template',
            'template' => [
                'name' => $template,
                'language' => [
                    'code' => $code
                ],
                'components' => [
                    [
                        'type' => 'body',
                        'parameters' => $parameters
                    ]

                ],
            ],
        ];
        $body = json_encode($body);

        $rs = curl_post($url,$body,$header);
        return true;
    }



}