<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 小程序公共API服务
 */
namespace app\bestbao\controller\api\v1;
use app\bestbao\controller\api\Base;
use app\bestbao\model\BestbaoEngineer;
use app\bestbao\model\BestbaoProcess;
use app\bestbao\model\BestbaoOrder;

class Engineer extends Base{

    public function initialize() {
        parent::initialize();
        $this->isUserAuth();
    }
 
     /**
     * 判断是否维修工程师
     **/
    public function isEngineer(){
        $param['signkey'] = $this->request->param('signkey');
        $param['sign']    = $this->request->param('sign');
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson($rel['code'],'签名验证失败');
        }
        $rel = BestbaoEngineer::where(['uid' => $this->user->id])->count();
        return enjson(200,'成功', $rel);
    }
    
    /**
     * 读取工程师的订单
     */
    public function index(){
        $param = [
            'page'  => $this->request->param('page/d',1),
            'types' => $this->request->param('types/d',0),
            'sign'  => $this->request->param('sign/s'),
        ];
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson($rel['code'],'签名验证失败');
        }
        //我的工单
        $engineer = BestbaoEngineer::where(['uid' => $this->user->id])->field('id')->find();
        if(empty($engineer)){
            return enjson($rel['code'],'我不是工程师');
        }
        $condition[] = ['member_miniapp_id','=',$this->miniapp_id];
        switch ($param['types']) {
            case 1:
                $condition[] = ['state','=',0];
                $condition[] = ['engineer_id','=',$engineer->id];
                break;
            case 2:
                $condition[] = ['state','>=',1];
                $condition[] = ['state','<=',2];
                $condition[] = ['engineer_id','=',$engineer->id];
                break;
            case 3:
                $condition[] = ['state','=',3];
                $condition[] = ['engineer_id','=',$engineer->id];
                break;
            default:
                $condition[] = ['state','=',0];
                $condition[] = ['engineer_id','=',0];
                break;
        }
        $order = BestbaoOrder::where($condition)->field('id,title,update_time,state,urgent,engineer_id,phone,realname,address,engineer_id')->order('id desc')->page($param['page'],10)->select();
        if($order->isEmpty()){
            return enjson(204);
        }
        $data = $order->toArray();
        foreach ($data as $key => $value) {
            $data[$key]['update_time'] = date('Y-m-d H:i',$value['update_time']);
            $data[$key]['state_text']  = BestbaoOrder::stateText($value['state'],$value['engineer_id']);
            $data[$key]['urgent_text'] = BestbaoOrder::urgentText($value['urgent']);
        }
        return enjson(200,'操作成功',$data);
    }
    
    /**
     * 订单详情
     * @return void
     */
    public function reView(){
        $param = [
            'id'   => $this->request->param('id/d',0),
            'sign' => $this->request->param('sign/s'),
        ];
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson($rel['code'],'签名验证失败');
        }
        //查询用户的工程师
        $engineer = BestbaoEngineer::where(['uid' => $this->user->id])->field('id,level,title')->find();
        if(empty($engineer)){
            return enjson(403,'你不是工程师');
        }
        $condition['member_miniapp_id'] = $this->miniapp_id;
        $condition['id']                = $param['id'];
        $order = BestbaoOrder::with(['user' => function($query){
            $query->field('nickname,phone_uid,id,face');
        }])->where($condition)->find();
        if(empty($order)){
            return enjson(403,'未找到当前工单');
        }
        if($order->engineer_id > 0){
            if($order->engineer_id != $engineer->id){
                return enjson(403,'不是您的工单');
            }
        }
        $order['update_time'] = date('Y-m-d H:i',$order['update_time']);
        $order['state_text']  = BestbaoOrder::stateText($order['state'],$order['engineer_id']);
        $order['urgent_text'] = BestbaoOrder::urgentText($order['urgent']);
        $order['imgs']        = json_decode($order['imgs'],true);
        $order['solve_time']  = empty($order['solve_time'])?'':date('Y-m-d H:i',$order['solve_time']);
        $info = BestbaoProcess::where(['order_id' => $param['id']])->select();
        $process = [];
        foreach ($info as $key => $value) {
            $process[$key]['text'] = $value['remarks'];
            $process[$key]['desc'] = date('Y-m-d H:i',$value['create_time']);
        }
        return enjson(200,'操作成功',['order'=>$order,'process' =>$process]);
    }

    /**
     * 接受工单*
     * @return void
     */
    public function doOrder(){
        $param = [
            'id'         => $this->request->param('id/d',0),
            'solve_time' => $this->request->param('solve_time'),
            'sign'       => $this->request->param('sign/s'),
        ];
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson($rel['code'],'签名验证失败');
        }
        $validate = $this->validate($param,'Order.doOrder');
        if(true !== $validate){
            return json(['code'=>403,'msg'=>$validate]);
        }
        //我的工单
        $engineer = BestbaoEngineer::where(['uid' => $this->user->id])->field('id,level,title')->find();
        if(empty($engineer)){
            return enjson($rel['code'],'我不是工程师');
        }
        $condition['member_miniapp_id'] = $this->miniapp_id;
        $condition['id']                = $param['id'];
        $condition['state']             = 0;
        $condition['engineer_id']       = 0;
        $order = BestbaoOrder::where($condition)->find();
        if(empty($order)){
            return enjson(403,'当前工单已有其它工程师服务中');
        }
        switch ($engineer->level) {
            case 1:
                $level = '中级工程师:';
                break;
            case 2:
                $level = '高级工程师:';
                break;
            default:
                $level = '初级工程师:';
                break;
        }
        $remarks = $level.'['.$engineer->title.']电话:['.$this->user->phone_uid.']预计服务时间:['.$param['solve_time'].']';
        BestbaoProcess::create(['member_miniapp_id' => $this->miniapp_id,'order_id' => $order->id,'engineer_id'  => $engineer->id,'remarks' =>$remarks]);
        $order->engineer_id = $engineer->id;
        $order->save();
        return enjson(200,'工单接受成功,请注意服务时间,不要超时。');
    }

    /**
     * 工单流转
     * @return void
     */
    public function changeOrder(){
        $param = [
            'id'              => $this->request->param('id/d'),
            'change_id'       => $this->request->param('change_id/d',0),
            'change_engineer' => $this->request->param('change_engineer/s'),
            'sign'       => $this->request->param('sign/s'),
        ];
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson($rel['code'],'签名验证失败');
        }
        $validate = $this->validate($param,'Order.changeOrder');
        if(true !== $validate){
            return json(['code'=>403,'msg'=>$validate]);
        }
        //查询其它工程师
        $engineer = BestbaoEngineer::where(['uid' => $this->user->id])->field('id,level,title,uid')->find();
        if(empty($engineer)){
            return enjson($rel['code'],'你不是工程师');
        }
        //我的订单
        $condition['id']                = $param['id'];  //工单ID
        $condition['member_miniapp_id'] = $this->miniapp_id; //所属应用ID
        $condition['engineer_id']       = $engineer->id; //工程师ID
        $condition['state']             = 0; //状态
        $order = BestbaoOrder::where($condition)->find();
        if(empty($order)){
            return enjson(403,'未找到工单');
        }
        //转出工程师
        $change_engineer = BestbaoEngineer::where(['id' => $param['change_id']])->field('id,level,title,uid')->find();
        if(empty($change_engineer)){
            return enjson($rel['code'],'未找不流转对象');
        }
        switch ($change_engineer->level) {
            case 1:
                $level = '中级工程师:';
                break;
            case 2:
                $level = '高级工程师:';
                break;
            default:
                $level = '初级工程师:';
                break;
        }
        $remarks = $level.'['.$change_engineer->title.']为你服务,电话:'.$change_engineer->user->phone_uid;       
        BestbaoProcess::create(['member_miniapp_id' => $this->miniapp_id,'order_id' => $order->id,'engineer_id'  => $engineer->id,'remarks' =>$remarks]);
        $order->engineer_id = $change_engineer->id;
        $order->save();
        return enjson(200,'工单已转给其它工程师');
    }

    /**
     * 工单完结
     * @return void
     */
    public function orderEnd(){
        $param = [
            'id'                => $this->request->param('id/d',0),
            'servertypes'       => $this->request->param('servertypes/s'),
            'buytypes'          => $this->request->param('buytypes/s'),
            'question'          => $this->request->param('question/s'),
            'answer'            => $this->request->param('answer/s'),
            'accessories'       => $this->request->param('accessories/s'),
            'accessories_price' => $this->request->param('accessories_price/f',0),
            'service_price'     => $this->request->param('service_price/f',0),
            'discount_price'    => $this->request->param('discount_price/f',0),
            'price'             => money($this->request->param('price/f',0)),
            'sign'              => $this->request->param('sign/s'),
        ];
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson($rel['code'],'签名验证失败');
        }
        //费用
        $price  = money($param['accessories_price']+$param['service_price']-$param['discount_price']);
        if($price < 0){
            return enjson(403,'应付金额禁止小于0元');
        }
        if($param['price'] != $price){
            return enjson(403,'应付金额金额有误');
        }
        //查询其它工程师
        $engineer = BestbaoEngineer::where(['uid' => $this->user->id])->field('id,level,title')->find();
        if(empty($engineer)){
            return enjson($rel['code'],'你不是工程师');
        }
        //我的订单
        $condition['member_miniapp_id'] = $this->miniapp_id;
        $condition['id']                = $param['id'];
        $condition['state']             = 0;
        $condition['engineer_id']       = $engineer->id;
        $order = BestbaoOrder::where($condition)->find();
        if(empty($order)){
            return enjson(403,'不是你的的服务工单');
        }
        $order->server_types      = $param['servertypes'];
        $order->buy_types         = $param['buytypes'];
        $order->real_question     = $param['question'];
        $order->answer            = $param['answer'];
        $order->accessories       = $param['accessories'];
        $order->accessories_price = $param['accessories_price'];
        $order->service_price     = $param['service_price'];
        $order->discount_price    = $param['discount_price'];
        if($price > 0){
            if($param['buytypes'] == '在线支付'){
                $order->state = 1;
                $remarks = '完成服务,请客户确认工单,并支付费用';
            }else{
                $order->state = 2;
                $remarks = '工单完成服务,请评价';
            }
        }else{
            $order->state = 2;;
            $remarks = '工单完成服务,请评价';
        }
        $order->price = $price;
        $order->solve_time = time();
        $order->save();
        BestbaoProcess::create(['member_miniapp_id' => $this->miniapp_id,'order_id' => $order->id,'engineer_id'  => $engineer->id,'remarks' => $remarks]);
        return enjson(200,'确认工单成功');
    }
}