<?php

namespace app\admin\controller\school\classes\hourorder;

use app\common\controller\Backend;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 课时订单
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\school\classes\hourorder\Order
     */
    protected $model = null;

    protected $qSwitch = true;
    protected $qFields = ["classes_order_id","classes_lib_spec_id","user_id","classes_order_detail_id","classes_lib_id"];

    public function _initialize()
    {
        $this->model = new \app\admin\model\school\classes\hourorder\Order;
        parent::_initialize();

        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("authStatusList", $this->model->getAuthStatusList());
        $this->getAuthMsg();
//        $this->setUrlLock();
    }



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


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        $this->searchFields = ["id","order_no","classesorder.order_no","classesorder.pay_no","user_id","spec.name","detail.title","user.nickname","user.realname","user.mobile"];


        //设置过滤方法
        $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(['classesorder','spec','user','detail','lib'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('classesorder')->visible(['order_no']);
				$row->getRelation('spec')->visible(['name']);
				$row->getRelation('user')->visible(['nickname','realname','mobile','avatar']);
				$row->getRelation('detail')->visible(['title','headimage','feel']);
				$row->getRelation('lib')->visible(['title']);
            }

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

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








    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;

        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }

            //记录代下单人信息
            $param  =  [
                "type" =>'2',
                "help_user_id" =>$this->auth->id,
                "help_type" => 'admin',
            ];
       //确认订单
            $res = (new \app\common\model\school\classes\hourorder\Order)->confirm($this->auth->id,$params['classes_order_id'],null, $params['classes_lib_spec_id'],$param, true);
            $remark = "总后台管理员帮忙下课时预约";
       //创建订单
            $result = (new \app\common\model\school\classes\hourorder\Order)->cacheCreateOrder($res['order_no'], $this->auth->id,$remark, true);



        } catch (ValidateException|PDOException|\Exception $e) {

            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;

        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }




            //记录代下单人信息

            //修改订单课时
            $result = (new \app\common\model\school\classes\hourorder\Order)->updateClassesSpec($row["id"],$params["classes_lib_spec_id"],0,true,'admin',$this->auth->id,true);



        } catch (ValidateException|PDOException|\Exception $e) {

            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }




    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;

        try {
            foreach ($list as $item) {
                $res = (new \app\common\model\school\classes\hourorder\Order)->cancel($item["id"],0,true,'admin',$this->auth->id,true);
                $count++;
            }

        } catch (PDOException|\Exception $e) {

            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }




    /**预约审核
     * @return string
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function examine($ids = ""){

        if($this->request->isPost())
        {
            try{
                $params = $this->request->post("row/a");


                $auth_status = $params["auth_status"];
                $reason = $params["reason"];
                $model = (new \app\common\model\school\classes\hourorder\Order);
                $model->examine($params["id"],$auth_status,$reason,0,true,'admin',$this->auth->id,true);

            }catch (\Exception $e){
                $this->error($e->getMessage());
            }

            $this->success("已完成审核");
        }

        $row = $this->model->where(array('id'=>$ids))->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }

//        $row = $this->model->get($param['ids']);
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }





    /**
     * 后台核销
     * @return string
     * @throws \think\Exception
     * @throws \think\db\exception\BindParamException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function verification($ids = ''){
        $param = $this->request->param();
        if($this->request->isPost()){
            try{
                if(isset($param['ids']))$ids = $param['ids'];
                //设置模拟资格
                $model = (new \app\common\model\school\classes\hourorder\Order);
                $model->verification($ids,0,true,'admin',$this->auth->id,true);


            }catch (\Exception $e){
                $this->error($e->getMessage());
            }
            $this->success('核销成功!');
        }
        $row = $this->model->get($ids);
        $this->view->assign('vo', $row);
        return $this->view->fetch();
    }





}
