<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Message;
use think\Db;
use app\common\library\Sms as Smslib;
/**
 * 派单接口
 */
class Dispatch extends Common
{
    protected $noNeedLogin = ['getSkillList','getReciveList'];
    protected $noNeedRight = ['*'];

    /**
     * 添加技能认证
     */
    public function addSkillAuth() {
        $skill_id = $this->request->request('skill_id',0,"intval"); // 技能ID
        $leaver_id = $this->request->request('leaver_id',0,"intval"); // 技能等级ID
        $area_id = $this->request->request('area_id',0,"intval"); // 区服ID
        $image = $this->request->request('image'); // 图片说明
        $voice = $this->request->request('voice'); // 语音说明
        $voice_time = $this->request->request('voice_time'); // 声音时长
        $price = $this->request->request('price'); // 价格说明
        $remarks = $this->request->request('remarks'); // 技能介绍
        if (!$skill_id || !$image || !$voice || !$remarks || !$price) {
            $this->error(__('Invalid parameters'));
        }

        $is_main = 0;
        // 获取技能信息
        $skillModel = new \app\common\model\DispatchSkill();
        $skillInfo = $skillModel->getSkillInfo($skill_id);
        if(!$skillInfo) {
            $this->error(__('未找到技能信息!'));
        }

        $authModel = new \app\common\model\DispatchAuth();
        // 是否已经认证过
        $where = [];
        $where["user_id"] = $this->auth->id;
        $where["skill_id"] = $skill_id;
        $authInfo = $authModel->where($where)->find();
        if($authInfo) {
            if($authInfo["status"] == 0) $this->error(__('您已提交过认证申请,请耐心等待审核!'));
            if($authInfo["status"] == 1) $this->error(__('您已经认证过了'));
        }
       if($authModel->where(["user_id"=>$this->auth->id])->count()<=0) {
           $is_main = 1;
       }
        // 添加认证信息
        $data = [];
        $data["user_id"] = $this->auth->id;
        $data["skill_id"] = $skill_id;
        $data["leaver_id"] = $leaver_id;
        $data["area_id"] = $area_id;
        $data["image"] = $image;
        $data["voice"] = $voice;
        $data["voice_time"] = $voice_time;
        $data["price"] = $price;
        $data["is_main"] = $is_main;
        $data["image"] = $image;
        $data["remarks"] = $remarks;
        $data["createtime"] = time();
        $res = $authModel->insertGetId($data);
        if($res) {
            $this->success('申请发送成功,请耐心等待审核!');
        } else {
            $this->error(__('网络错误,请稍后重试!'));
        }
    }

    /**
     * 判断当前技能是否已认证
     */
    public function skillIsAuth() {
        $skill_id = $this->request->request('skill_id',0,"intval"); // 技能ID
        if (!$skill_id) {
            $this->error(__('Invalid parameters'));
        }
        $authModel = new \app\common\model\DispatchAuth();
        // 是否已经认证过
        $where = [];
        $where["user_id"] = $this->auth->id;
        $where["skill_id"] = $skill_id;
        $authInfo = $authModel->field("status")->where($where)->find();
        if($authInfo) {
            if($authInfo["status"] == 0) $this->error(__('当前技能已提交过认证申请,请耐心等待审核!'));
            if($authInfo["status"] == 1) $this->error(__('当前技能已经认证过了'));
        }

        $skillLevelInfo = \app\common\model\DispatchSkillLeaver::where(["skill_id"=>$skill_id])->find();
        $skillAreaInfo = \app\common\model\DispatchSkillArea::where(["skill_id"=>$skill_id])->find();
        $res = [];
        $res["level"] = $skillLevelInfo?1:0;
        $res["area"] = $skillAreaInfo?1:0;
        $this->success("没有认证过,可以去认证!", $res);
    }

//    /**
//     * 创建接单信息
//     */
//    public function addRecive() {
//        $skill_id = $this->request->request('skill_id',0,"intval"); // 技能ID
//        $back_image = $this->request->request('back_image'); // 背景图
//        $price = $this->request->request('price'); // 服务价格
//        $describe = $this->request->request('describe'); // 一句话描述
////        $tags = $this->request->request('tags'); // 标签列表(中文半角逗号隔开)
//        if (!$skill_id || !$back_image || !$describe) {
//            $this->error(__('Invalid parameters'));
//        }
//        $reciveModel = new \app\common\model\DispatchRecive();
//        $where = [];
//        $where["user_id"] = $this->auth->id;
//        $where["skill_id"] = $skill_id;
//        $where["status"] = 1;
//        $reciveInfo = $reciveModel->where($where)->find();
//        if($reciveInfo) {
//            $this->error(__('您已存在当前技能的接单信息,请勿重复提单'));
//        }
//
//        // 获取技能信息
//        $skillModel = new \app\common\model\DispatchSkill();
//        $skillInfo = $skillModel->getSkillInfo($skill_id);
//        if(!$skillInfo) {
//            $this->error(__('未找到技能信息!'));
//        }
//
//        // 添加接单信息
//        $data = [];
//        $data["user_id"] = $this->auth->id;
//        $data["skill_id"] = $skill_id;
//        $data["back_image"] = $back_image;
//        $data["price"] = $price;
//        $data["unit"] = $skillInfo["unit"];
//        $data["describe"] = $describe;
////        $data["tags"] = $tags;
//        $data["createtime"] = time();
//        $res = $reciveModel->insertGetId($data);
//        if($res) {
//            $this->success('恭喜,接单信息已发送!');
//        } else {
//            $this->error(__('网络错误,请稍后重试!'));
//        }
//    }

//    /**
//     * 创建订单
//     */
//    public function addOrder() {
//        $recive_id = $this->request->request('recive_id',0,"intval"); // 接单ID
//        $num = $this->request->request('num',0,"intval"); // 数量
//        $describe = $this->request->request('describe'); // 备注要求
//        if (!$recive_id || !$num || !$describe) {
//            $this->error(__('Invalid parameters'));
//        }
//
//        // 获取接单信息
//        $reciveModel = new \app\common\model\DispatchRecive();
//        $where = [];
//        $where["id"] = $recive_id;
//        $reciveInfo = $reciveModel->where($where)->find();
//        if(!$reciveInfo) {
//            $this->error(__('接单信息不存在!'));
//        }
//        if($reciveInfo["status"] == 2) {
//            $this->error(__('订单已关闭!'));
//        }
//        // 判断用户余额
//        $userModel = new \app\common\model\User();
//        $where = [];
//        $where["id"] = $this->auth->id;
//        $jewel = $userModel->where($where)->value("jewel");
//        $price = 0;
//        $reciveInfo["price"] >= 0 || $price = 0;
//        $reciveInfo["price"] >= 0 && $price = $reciveInfo["price"];
//        if($price * $num >= $jewel) {
//            $this->error(__('钻石余额不足,请先充值!'));
//        }
//        // 添加订单信息
//        $orderModel = new \app\common\model\DispatchOrder();
//        $data = [];
//        $data["user_id"] = $this->auth->id;
//        $data["recive_id"] = $recive_id;
//        $data["price"] = $reciveInfo["price"];
//        $data["num"] = $num;
//        $data["describe"] = $describe;
//        $data["createtime"] = time();
//        $res = $orderModel->insertGetId($data);
//        if($res) {
//            $this->success('订单创建成功!');
//        } else {
//            $this->error(__('订单创建失败!'));
//        }
//
//    }

//    /**
//     * 获取接单信息
//     */
//    public function getReciveInfo() {
//        $recive_id = $this->request->request('recive_id',0,"intval"); // 接单ID
//        if (!$recive_id) {
//            $this->error(__('Invalid parameters'));
//        }
//        // 获取接单信息
//        $reciveModel = new \app\common\model\DispatchRecive();
//        $where = [];
//        $where["r.id"] = $recive_id;
//        $reciveInfo = $reciveModel->alias("r")
//            ->field("r.id,u.id as user_id,r.back_image,a.voice,u.avatar,u.nickname,s.name as skill_name,r.price,s.unit,r.service_time,r.describe,r.tags")
//            ->join("hx_user u","u.id = r.user_id")
//            ->join("hx_dispatch_skill s","s.id = r.skill_id")
//            ->join("hx_dispatch_auth a","a.skill_id = s.id")
//            ->where($where)
//            ->find();
//        if(!$reciveInfo) {
//            $this->error(__('数据为空!'));
//        }
//        // 在线状态和ID
//        $reciveInfo["is_online"] = 1;
//        $reciveInfo["line_id"] = 234224;
//        // 已服务人数
//        $where = [];
//        $where["user_id"] = $reciveInfo["user_id"];
//        $where["status"] = 2;
//        $reciveInfo["service_num"] = \app\common\model\DispatchOrder::where(["user_id"])->count();
//        // 主播认证通过的所有技能标签
//        $authModel = new \app\common\model\DispatchAuth();
//        $where = [];
//        $where["a.user_id"] = $reciveInfo["user_id"];
//        $where["a.status"] = $reciveInfo["user_id"];
//        $skillArr = $authModel->alias("a")
//            ->field("s.id,s.name")
//            ->join("hx_dispatch_skill s","s.id = a.skill_id")
//            ->where(["user_id"])->select();
//
//        $reciveInfo["skills"] = $skillArr;
//
//        $this->success('获取成功!',$reciveInfo);
//    }

    /**
     * 获取接单列表
     */
    public function getReciveList() {
        $skill_id = $this->request->request('skill_id',0,"intval"); // 技能ID
        $is_recommend = $this->request->request('is_recommend'); // 是否推荐:1=是,0=否
        $gender = $this->request->request('gender',-1); // 性别:1=男,0=女,-1=全部
        $page = $this->request->request('page',1); // 分页
        $pageNum = $this->request->request('pageNum',10); // 分页
        // 分页搜索构建
        $pageStart = ($page-1)*$pageNum;

        if(!in_array($gender,[-1,0,1])) {
            $gender = -1;
        }

        $authModel = new \app\common\model\DispatchAuth();
        $where = [];
        if ($skill_id > 0) {
            $where["a.skill_id"] = $skill_id;
        } else if($is_recommend == 1) {
            $where["a.is_recommend"] = $is_recommend;
            $where["a.is_main"] = 1;
        }
        $where["a.status"] = 1;
        $gender == -1 || $where["u.gender"] = $gender;
        $authList = $authModel->alias("a")
            ->field("a.id,u.avatar,ds.name as skill_name,a.voice,a.voice_time,a.price,ds.unit,u.nickname,u.gender")
            ->join("hx_user u","u.id = a.user_id")
            ->join("hx_dispatch_skill ds","ds.id = a.skill_id")
            ->limit($pageStart,$pageNum)
            ->where($where)
            ->select();

        $this->success('获取成功!',$authList);

    }

    /**
     * 获取推荐列表
     */
    public function getReciveCommentList() {
        $page = $this->request->request('page',1); // 分页
        $pageNum = $this->request->request('pageNum',10); // 分页
        // 分页搜索构建
        $pageStart = ($page-1)*$pageNum;

        $authModel = new \app\common\model\DispatchAuth();
        $where = [];
        $where["a.is_main"] = 1;
        $where["a.status"] = 1;
        $where["a.is_recommend"] = 1;
        $authList = $authModel->alias("a")
            ->field("a.id,u.avatar,ds.name as skill_name,a.voice,a.voice_time,a.price,ds.unit,u.nickname,u.gender")
            ->join("hx_user u","u.id = a.user_id")
            ->join("hx_dispatch_skill ds","ds.id = a.skill_id")
            ->limit($pageStart,$pageNum)
            ->where($where)
            ->select();

        $this->success('获取成功!',$authList);

    }

    /**
     * 获取接单信息
     */
    public function getReciveInfo() {
        $auth_id = $this->request->request('auth_id',0,"intval"); // 技能认证ID
        if (!$auth_id) {
            $this->error(__('Invalid parameters'));
        }
        // 获取接单信息
        $authModel = new \app\common\model\DispatchAuth();
        $where = [];
        $where["a.id"] = $auth_id;
        $authInfo = $authModel->alias("a")
            ->field("a.id,a.user_id,a.image,a.voice,a.voice_time,u.avatar,u.nickname,u.u_id,u.is_online,s.id as skill_id,s.name as skill_name,s.image as skill_icon, a.price,s.unit,a.remarks")
            ->join("hx_user u","u.id = a.user_id")
            ->join("hx_dispatch_skill s","s.id = a.skill_id")
            ->where($where)
            ->find();
        if(!$authInfo) {
            $this->error(__('数据为空!'));
        }
        // 已服务人数
        $where = [];
        $where["recive_id"] = $authInfo["user_id"];
        $where["status"] = 3;
        $authInfo["service_num"] = \app\common\model\DispatchOrder::where($where)->count();
        // 主播认证通过的所有技能标签
        $viewuserskillModel = new \app\common\model\ViewUserSkill();
        $skillArr = $viewuserskillModel->getSkillInfoId($authInfo["user_id"]);
        // 查看者是否已关注
        $followid = \app\common\model\UserFansFollow::where(["fans_id"=>$this->auth->id,"user_id"=>$authInfo["user_id"]])->value("id");
        $authInfo["is_follow"] = $followid>0?1:0;

        $authInfo["skills"] = $skillArr;

        $this->success('获取成功!',$authInfo);
    }

    /**
     * 创建订单
     */
    public function addOrder() {
        $user_id = $this->request->request('user_id',0,"intval"); // 主播用户ID
        $skill_id = $this->request->request('skill_id',0,"intval"); // 技能ID
        $num = $this->request->request('num',0,"intval"); // 数量
        $make_time = $this->request->request('make_time'); // 预约时间 格式:时间戳。
        $describe = $this->request->request('describe'); // 备注要求
        $makeTimeLen = strlen($make_time);
        if (!empty($make_time) && $makeTimeLen > 10) {//处理时间戳位数问题
            $make_time = substr($make_time,0,10);
        }
        if (!$skill_id || !$num) {
            $this->error(__('Invalid parameters'));
        }
        if ($this->auth->power->payorder == 1) {
            $this->error('您已被禁止下单');
        }
        $orderModel = new \app\common\model\DispatchOrder();

        // 获取接单信息
        $authModel = new \app\common\model\DispatchAuth();
        $where = [];
        $where["user_id"] = $user_id;
        $where["skill_id"] = $skill_id;
        $where["status"] = 1;
        $authInfo = $authModel->where($where)->find();
        if(!$authInfo) {
            $this->error(__('技能认证信息不存在,或认证未通过!'),[],103);
        }

        // 获取技能信息
        $skillModel = new \app\common\model\DispatchSkill();
        $where = [];
        $where["id"] = $skill_id;
        $skillInfo = $skillModel->where($where)->find();
        if(!$skillInfo) {
            $this->error(__('技能信息未找到,请稍后重试!'));
        }

        // 判断用户余额
        $userModel = new \app\common\model\User();
        $where = [];
        $where["id"] = $this->auth->id;
        $jewel = $userModel->where($where)->value("jewel");
        $price = 0;
        $authInfo["price"] >= 0 || $price = 0;
        $authInfo["price"] >= 0 && $price = $authInfo["price"];
        $money = $price * $num;
        if($money > $jewel) {
            $this->error(__('钻石余额不足,请先充值!'),[],100);
        }

        // 禁止自己下单
        if($this->auth->id == $authInfo["user_id"]) {
            $this->error(__('禁止自己下单!'),[],101);
        }

        // 查看当前用户是否有未支付订单
        $where = [];
        $where["user_id"] = $this->auth->id;
        $where["status"] = 0;
        $orderInfo = $orderModel->where($where)->find();
//        $orderInfo && $this->error(__('您有未支付订单,请先支付!'),[],102);

        Db::startTrans();
        try{
            // 添加订单信息
            $out_trade_no = date("YmdHis").rand(100000,999999);// 产生订单号
            $data = [];
            $data["user_id"] = $this->auth->id;
            $data["order_no"] = $out_trade_no;
            $data["recive_id"] = $authInfo["user_id"];
            $data["auth_id"] = $authInfo["id"];
            $data["price"] = $authInfo["price"];
            $data["num"] = $num;
            $data["skill_image"] = $skillInfo["image"];
            $data["skill_name"] = $skillInfo["name"];
            $data["skill_unit"] = $skillInfo["unit"];
            $data["make_time"] = $make_time;
            $data["describe"] = $describe;
            $data["status"] = 0;
            $data["createtime"] = time();
            $res = $orderModel->insertGetId($data);
            if($res) {
                //冻结用户钻石
                /*$userWhere['id'] = $this->auth->id;
                $money = bcmul($authInfo["price"],$num);
                $res1 = model('User')->where($userWhere)->setDec("jewel",$money);//用户扣减金额
                $res2 = model('User')->where($userWhere)->setInc("frozen",$money);//用户冻结金额
                if (!$res1 || !$res2) {
                    throw new Exception('用户扣减金额失败');
                }*/
                \app\common\model\Message::addMessage($authInfo["user_id"],"派单通知","您的技能:".$skillInfo["name"]."有人下单啦,请注意查看!");
                Db::commit();
                $this->success('订单创建成功!',["order_no"=>$out_trade_no]);
            } else {
                $this->error(__('订单创建失败!'));
            }
        }catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

    }

    /**
     * 添加订单评价内容
     */
    public function addOrderComment() {
        $order_no = $this->request->request('order_no'); // 订单编号
        $content = $this->request->request('content'); // 评价内容
        if (!$order_no && !$content) {
            $this->error(__('Invalid parameters'));
        }

        Db::startTrans();
        try{
            $ordercommentModel = new \app\common\model\DispatchOrderComment();
            $orderModel = new \app\common\model\DispatchOrder();
            $orderInfo = $orderModel->where(["order_no"=>$order_no])->find();
            if(!$orderInfo) $this->error(__('未查询到订单信息!'));
            if($orderInfo["status"] != 3) $this->error(__('当前订单状态不允许评价!'));
            $data= [];
            $data["user_id"] = $this->auth->id;
            $data["order_id"] = $orderInfo["id"];
            $data["content"] = $content;
            $data["createtime"] = time();
            $res1 = $ordercommentModel->insert($data);
            $res2 = $orderModel->update(["is_comment"=>1],["order_no"=>$order_no]);
            if($res1 && $res2) {
                Db::commit();
                $this->success('评价成功!');
            } else {
                $this->error(__('订单创建失败!'));
            }
        }catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }



    /**
     * 钻石余额支付订单
     */
    public function jewelPay() {
        $order_no = $this->request->request('order_no'); // 订单号
        if (!$order_no) {
            $this->error(__('Invalid parameters'));
        }
        // 获取订单信息
        $orderModel = new \app\common\model\DispatchOrder();
        $where = [];
        $where["order_no"] = $order_no;
        $orderInfo = $orderModel->where($where)->find();
        if(!$orderInfo) {
            $this->error(__('订单信息获取失败!'));
        }
        if($orderInfo["status"] != 0) {
            $this->error(__('订单状态有误!'),[],104);
        }
        // 判断用户余额
        $userModel = new \app\common\model\User();
        $where = [];
        $where["id"] = $this->auth->id;
        $jewel = $userModel->where($where)->value("jewel");
        $money = $orderInfo["price"] * $orderInfo["num"];
        if($money > $jewel) {
            $this->error(__('钻石余额不足,请先充值!'),[],100);
        }
        // 去支付
        Db::startTrans();
        try{
            // 扣除用户余额
            $where = [];
            $where["id"] = $this->auth->id;
            $userInfo = $userModel->where($where)->find();
            $res1 = $userModel->where($where)->setDec("jewel",$money);
            $res2 = $userModel->where($where)->setInc("frozen",$money);
            // 添加用户余额变动记录
            $userjewellogModel = new \app\common\model\UserJewelLog();
            $data = [];
            $data["user_id"] = $this->auth->id;
            $data["value"] = $money;
            $data["mode"] = "-";
            $data["before"] = $userInfo["jewel"];
            $data["balance"] = $userInfo["jewel"]-$money;
            $data["detail"] = "下单扣除余额";
            $data["createtime"] = time();
            $res3 = $userjewellogModel->insertGetId($data);
            // 添加订单信息
            $orderModel = new \app\common\model\DispatchOrder();
            // 修改订单状态
            $where = [];
            $where["order_no"] = $order_no;
            $data = [];
            $data["status"] = 1;
            $res4 = $orderModel->update($data,$where);
            if($res1 && $res2 && $res3 && $res4) {
                Db::commit();
                // 短信通知
                $reciveuserInfo = $userModel->where(["id"=>$orderInfo["recive_id"]])->find();
                //Smslib::notice($reciveuserInfo->mobile, $orderInfo["skill_name"],"有人接单啦",'orderNotice');
                // 系统消息通知
                \app\common\model\Message::addMessage($orderInfo["recive_id"],"派单通知","您的派单,技能:".$orderInfo["skill_name"]."有人下单啦,请注意查看!");

                $this->success('支付成功!');
            } else {
                $this->error(__('订单创建失败!'));
            }
        }catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 更新订单状态
     */
    public function changeOrder() {
        $order_no = $this->request->request('order_no'); // 订单号
        $status = $this->request->request('status'); // 状态:-2=已取消,-1=拒绝接单,2=进行中,3=已完成
        if (!$order_no || !$status) {
            $this->error(__('Invalid parameters'));
        }
        if(!in_array($status,["-2","-1","2","3"])) {
            $this->error("非法的订单状态参数");
        }
        // 获取订单信息
        $orderModel = new \app\common\model\DispatchOrder();
        $where = [];
        $where["order_no"] = $order_no;
        $orderInfo = $orderModel->where($where)->find();
        if(!$orderInfo) {
            $this->error(__('订单信息获取失败!'));
        }
        if($orderInfo["status"] == $status) {
            $this->error(__('当前订单状态无变更要求!'),[],104);
        }
        // 验证用户权限
        if($status == -1 && $orderInfo["recive_id"] != $this->auth->id) {
            $this->error(__('无权限操作!'),[],103);
        }

        // 验证用户权限
        if(($status == -2 || $status == 3) && $orderInfo["user_id"] != $this->auth->id) {
            $this->error(__('无权限操作!'),[],103);
        }

        if($status == -1) { // 拒绝订单
            if($orderInfo["status"] != 1) {
                $this->error(__('当前订单状态不支持拒绝订单!'),[],104);
            }
            // 完成订单操作需要更新余额记录
            Db::startTrans();
            try{
                $userModel = new \app\common\model\User();
                $money = $orderInfo["price"] * $orderInfo["num"];
                // 解冻用户余额
                $where = [];
                $where["id"] = $orderInfo["user_id"];
                $userInfo = $userModel->where($where)->find();
                if($userInfo["frozen"] - $money < 0) {
                    $this->error(__('账户资金异常,请联系管理员!'),[],105);
                }
                $res1 = $userModel->where($where)->setDec("frozen",$money);//下单用户
                $res2 = $userModel->where($where)->setInc("jewel",$money);//下单用户
                // 添加用户余额变动记录
                $userjewellogModel = new \app\common\model\UserJewelLog();
                $res3 = $userjewellogModel->addUserJewelLog($orderInfo["user_id"], $money, "+", $userInfo["jewel"], "拒绝订单返还余额", 7);
                // 更新订单状态
                $data = [];
                $data["status"] = $status;
                $where = [];
                $where["order_no"] = $order_no;
                $res4 = $orderModel->update($data,$where);

                if($res1 && $res2 && $res3 && $res4) {
                    Db::commit();
                    // 短信通知
                    //$reciveuserInfo = $userModel->where(["id"=>$orderInfo["user_id"]])->find();
                    //Smslib::notice($reciveuserInfo->mobile, $orderInfo["skill_name"],"被拒绝接单",'orderNotice');
                    // 系统消息通知
                    \app\common\model\Message::addMessage($orderInfo["user_id"],"派单通知","您的订单,技能:".$orderInfo["skill_name"]."已被拒绝接单,请注意查看!");

                    $this->success('订单已拒绝。');
                } else {
                    $this->error(__('订单更新失败!请稍后重试'));
                }
            }catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        } elseif($status == 3) { // 订单完成
            if($orderInfo["status"] != 2) {
                $this->error(__('当前订单状态不支持直接变更为已完成!'),[],104);
            }
            // 完成订单操作需要更新余额记录
            Db::startTrans();
            try{
                $userModel = new \app\common\model\User();
                $money = $orderInfo["price"] * $orderInfo["num"];
                // 增加用户余额
                $where = [];
                $where["id"] = $orderInfo["recive_id"];
                $userInfo = $userModel->where($where)->find();
                //$res1 = $userModel->where($where)->setInc("jewel",$money);
                $jewelMoneyRate = config('site.money_to_jewel');//1人民币兑换钻石数
                $moneyRmb = bcdiv($money,$jewelMoneyRate);
                $res1 = $userModel->where($where)->setInc("money",$moneyRmb);
                $where = [];
                $where["id"] = $this->auth->id;
                $res2 = $userModel->where($where)->setDec("frozen",$money);
                // 添加用户余额变动记录
                /*$userjewellogModel = new \app\common\model\UserJewelLog();
                $res3 = $userjewellogModel->addUserJewelLog($orderInfo["recive_id"], $money, "+", $userInfo["jewel"], "完成用户订单获得收益", 8);*/
                $remark = $orderInfo['skill_name'].'服务';
                $rs_wallet = model('wallet')->lockChangeAccountRemain($orderInfo["recive_id"],$moneyRmb,'+',$userInfo['money'],$remark,106,'money');
                $res3 = false;
                if($rs_wallet['status'] == false){
                    $this->error($rs_wallet['msg']);
                    Db::rollback();
                } else {
                    $res3 = true;
                }
                // 更新订单状态
                $data = [];
                $data["status"] = $status;
                $data["is_comment"] = 1;//要求直接自动已评价,为了前端不显示立即评价按钮
                $where = [];
                $where["order_no"] = $order_no;
                $res4 = $orderModel->update($data,$where);

                if($res1 && $res2 && $res3 && $res4) {
                    Db::commit();
                    // 短信通知
                    //$reciveuserInfo = $userModel->where(["id"=>$orderInfo["recive_id"]])->find();
                    //Smslib::send($reciveuserInfo->mobile, $orderInfo["skill_name"], "顺利完成啦!",'orderNotice');

                    // 系统消息通知
                    \app\common\model\Message::addMessage($orderInfo["recive_id"],"派单通知","您的派单,技能:".$orderInfo["skill_name"]." 完成啦!,请注意查看!");

                    $this->success('恭喜!订单完成。');
                } else {
                    $this->error(__('订单更新失败!请稍后重试'));
                }
            }catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }if($status == -2) { // 取消订单
            if($orderInfo["status"] != 1) {
                $this->error(__('当前订单状态不支持拒绝订单!'),[],104);
            }
            // 完成订单操作需要更新余额记录
            Db::startTrans();
            try{
                $userModel = new \app\common\model\User();
                $money = $orderInfo["price"] * $orderInfo["num"];
                // 解冻用户余额
                $where = [];
                $where["id"] = $this->auth->id;
                $userInfo = $userModel->where($where)->find();
                if($userInfo["frozen"] - $money < 0) {
                    $this->error(__('账户资金异常,请联系管理员!'),[],105);
                }
                $res1 = $userModel->where($where)->setDec("frozen",$money);
                $res2 = $userModel->where($where)->setInc("jewel",$money);
                // 添加用户余额变动记录
                $userjewellogModel = new \app\common\model\UserJewelLog();
                $res3 = $userjewellogModel->addUserJewelLog($orderInfo["user_id"], $money, "+", $userInfo["jewel"], "取消订单返还余额", 7);
                // 更新订单状态
                $data = [];
                $data["status"] = $status;
                $where = [];
                $where["order_no"] = $order_no;
                $res4 = $orderModel->update($data,$where);

                if($res1 && $res2 && $res3 && $res4) {
                    Db::commit();
                    // 短信通知
                    //$reciveuserInfo = $userModel->where(["id"=>$orderInfo["user_id"]])->find();
                    //Smslib::notice($reciveuserInfo->mobile, $orderInfo["skill_name"],"被拒绝接单",'orderNotice');
                    // 系统消息通知
                    \app\common\model\Message::addMessage($orderInfo["recive_id"],"派单通知","您的订单,技能:".$orderInfo["skill_name"]."已被取消,请登录查看!");

                    $this->success('订单取消成功。');
                } else {
                    $this->error(__('订单更新失败!请稍后重试'));
                }
            }catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        } else {
            $data = [];
            $data["status"] = $status;
            $where = [];
            $where["order_no"] = $order_no;
            $res = $orderModel->update($data,$where);
            if($res) {
                if ($status == 2) {//接单发
                    \app\common\model\Message::addMessage($orderInfo['user_id'],"订单单通知","您的订单:".$order_no."已被接单,请登录查看!");
                }
                $this->success('更新成功!');
            } else {
                $this->error(__('订单创建失败!'));
            }
        }
    }

    /**
     * 获取技能列表
     */
    public function getSkillList() {
        $skillModel = new \app\common\model\DispatchSkill();
        $skillList = $skillModel->select();
        if ($skillList) {
            $this->success(__('获取成功!'), $skillList);
        } else {
            $this->success(__('数据为空!'));
        }
    }

    /**
     * 获取技能等级列表
     */
    public function getSkillLevelList() {
        $skill_id = $this->request->request('skill_id'); // 技能ID
        if (!$skill_id) {
            $this->error(__('Invalid parameters'));
        }
        $skilllevelModel = new \app\common\model\DispatchSkillLeaver();
        $where = [];
        $where["skill_id"] = $skill_id;
        $skilllevelList = $skilllevelModel->where($where)->select();
        if ($skilllevelList) {
            $this->success(__('获取成功!'), $skilllevelList);
        } else {
            $this->success(__('数据为空!'));
        }
    }

    /**
     * 获取技能区域列表
     */
    public function getSkillAreaList() {
        $skill_id = $this->request->request('skill_id'); // 技能ID
        if (!$skill_id) {
            $this->error(__('Invalid parameters'));
        }
        $skillareaModel = new \app\common\model\DispatchSkillArea();
        $where = [];
        $where["skill_id"] = $skill_id;
        $skillareaList = $skillareaModel->where($where)->select();
        if ($skillareaList) {
            $this->success(__('获取成功!'), $skillareaList);
        } else {
            $this->success(__('数据为空!'));
        }
    }


    /**
     * 获取订单列表
     */
    public function getOrderList() {
        $type = $this->request->request('type',1); // 订单类型:1=我的下单,2=我的接单
        $status = $this->request->request('status',999); // 订单状态:999=全部,-2=已取消,-1=拒绝接单,0=待付款,1=待确定,2=进行中,3=已完成
        $page = $this->request->request('page',1); // 分页
        $pageNum = $this->request->request('pageNum',10); // 分页
        // 分页搜索构建
        $pageStart = ($page-1)*$pageNum;
        $user = "o.recive_id";
        $type == 1 && $user = "o.recive_id";
        $type == 2 && $user = "o.user_id";
        // 主体列表信息
        $orderModel = new \app\common\model\DispatchOrder();
        $where = [];
        $type == 1 && $where["o.user_id"] = $this->auth->id;
        $type == 2 && $where["o.recive_id"] = $this->auth->id;
        $status != 999 && $where["o.status"] = $status;
        $orderList = $orderModel->alias("o")
            ->field("o.id,".$user." as user_id,o.make_time,o.describe,o.order_no,u.avatar,u.nickname,o.skill_image,o.skill_name,o.price,o.skill_unit,o.num,o.status,o.is_comment,o.createtime")
            ->join("hx_user u","u.id = ".$user)
            ->where($where)
            ->order("createtime","desc")
            ->limit($pageStart,$pageNum)
            ->select();
        if(!$orderList) {
            $this->success(__('数据为空!'),[]);
        }
        foreach($orderList as $k => &$v) {
            $v["make_time"] = date("Y-m-d H:i",$v["make_time"]);
            $v["createtime"] = date("Y-m-d",$v["createtime"]);
            $v["status_text"] = $orderModel->getStateAttr($v["status"]);
        }
        $this->success(__('获取成功!'), $orderList);
    }

}