<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\logic\works;


use app\common\model\dict\DictData;
use app\common\model\master_worker\MasterWorker;
use app\common\model\master_worker\MasterWorkerAccountLog;
use app\common\model\recharge\RechargeOrder;
use app\common\model\works\ServiceWork;
use app\common\logic\BaseLogic;
use app\workerapi\logic\ServiceWorkerAllocateWorkerLogic;
use app\workerapi\logic\ServiceWorkLogLogic;
use think\db\Query;
use think\Exception;
use think\facade\Db;


/**
 * ServiceWork逻辑
 * Class ServiceWorkLogic
 * @package app\adminapi\logic\works
 */
class ServiceWorkLogic extends BaseLogic
{

    /**
     *
     * @return false|void
     */
    public static function pickWork($params)
    {
        Db::startTrans();
        try {
            $work = ServiceWork::where(['master_worker_id'=>$params['user_id'],'work_sn'=>$params['work_sn']])->findOrEmpty();
            if($work->isEmpty()){
                throw new Exception('工单不存在');
            }
            $receive_time = time();
            $work->work_status = 2;//待联系
            $work->service_status = 1;//服务中
            $work->receive_time = $receive_time;
            $work->save();

            //添加变更日志
            $work_log = [
                'work_id'=>$work->id,
                'master_worker_id'=>$work->master_worker_id,
                'opera_log'=>'编号['.$params['user_info']['worker_number'].']'.$params['user_info']['real_name'].'于'.date('y-m-d H:i:s',$receive_time).'领取了工单',
            ];
            ServiceWorkLogLogic::add($work_log);
            Db::commit();
        }
        catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }

    /**
     * 预约成功，等待上门
     * @return false|void
     */
    public static function appointWork($params)
    {
        Db::startTrans();
        try {
            $work = ServiceWork::where(['master_worker_id'=>$params['user_id'],'work_sn'=>$params['work_sn']])->findOrEmpty();
            if($work->isEmpty()){
                throw new Exception('工单不存在');
            }

            if($work->work_status != 2){
                throw new Exception('请勿重复点击');
            }

            //验证更改的预约时间必须是在领单时间内的半小内修改，否则不允许修改
            if(strtotime($work->appointment_time) != strtotime($params['appointment_time']) && (time()-$work->receive_time)>1800){
                throw new Exception('距离领单时间已超过半小时，无法修改预约时间，请联系客服');
            }

            $work->work_status = 3;//待上门
            $work->appointment_time = strtotime($params['appointment_time']);
            $work->save();

            //添加变更日志
            $work_log = [
                'work_id'=>$work->id,
                'master_worker_id'=>$work->master_worker_id,
                'opera_log'=>'编号['.$params['user_info']['worker_number'].']'.$params['user_info']['real_name'].'于'.date('y-m-d H:i:s',time()).'联系了客户,确认了于'.$params['appointment_time'].$params['address'].'预约上门',
            ];
            ServiceWorkLogLogic::add($work_log);
            Db::commit();
        }
        catch (\Exception $e) {
            self::setError($e->getMessage());
            return false;
        }
    }

    /**
     * 师傅确认上门
     * @param $params
     * @return false|void
     */
    public static function confirmDoor($params)
    {
        Db::startTrans();
        try {
            $work = ServiceWork::where(['master_worker_id'=>$params['user_id'],'work_sn'=>$params['work_sn']])->findOrEmpty();
            if($work->isEmpty()){
                throw new Exception('工单不存在');
            }

            $order = RechargeOrder::where(['sn'=>$params['order_sn'],'work_id'=>$work['id']])->findOrEmpty();
            if($order->isEmpty()){
                throw new Exception('订单不存在');
            }

            if($work->work_status != 3){
                throw new Exception('请勿重复点击');
            }

            $work->work_status = 4;//已上门
            $work->save();

            //添加变更日志
            $work_log = [
                'work_id'=>$work->id,
                'master_worker_id'=>$work->master_worker_id,
                'opera_log'=>'编号['.$params['user_info']['worker_number'].']'.$params['user_info']['real_name'].'于'.date('y-m-d H:i:s',time()).'于'.date('Y-m-d H:i:s',time()).'已上门',
            ];
            ServiceWorkLogLogic::add($work_log);
            Db::commit();
        }
        catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }

    /**
     * 师傅确认报价单
     * @param $params
     * @return false|void
     */
    public static function confirmPrice($params)
    {
        Db::startTrans();
        try {
            $work = ServiceWork::where(['master_worker_id'=>$params['user_id'],'work_sn'=>$params['work_sn']])->findOrEmpty();
            if($work->isEmpty()){
                throw new Exception('工单不存在');
            }
            //搜索待支付订单
            $paid_order = RechargeOrder::where(['work_id'=>$work['id'],'pay_status'=>1])->findOrEmpty()->toArray();
            if(empty($paid_order)){
                throw new Exception('订单错误');
            }

            if($work->work_status != 4){
                throw new Exception('请勿重复操作');
            }

            //定金存在尾款结算功能，全款直接提交
            if($paid_order['payment_type']==1){
                $un_order = RechargeOrder::where(['work_id'=>$work['id'],'pay_status'=>0])->findOrEmpty();
                if($un_order->isEmpty()){
                    //新增待支付尾款
                    $order_data = [
                        'order_type'=>$paid_order['order_type'],
                        'sn'=>generate_sn(\app\common\model\orders\RechargeOrder::class, 'sn'),
                        'work_id'=>$paid_order['work_id'],
                        'user_id'=>$paid_order['user_id'],
                        'payment_type'=>2,
                        'order_total'=>$params['amount'],
                        'order_amount'=>$params['amount'],
                        'order_terminal'=>$paid_order['order_terminal']
                    ];
                    RechargeOrder::create($order_data);
                }

                //修改尾款信息
                $un_order->order_total = $params['amount'];
                $un_order->order_amount = $params['amount'];
                $un_order->save();
            }

            $work->work_images = $params['work_images'];
            $work->user_confirm_status = 1;//待确认报价
            $work->save();

            //添加变更日志
            $work_log = [
                'work_id'=>$work->id,
                'master_worker_id'=>$work->master_worker_id,
                'opera_log'=>'编号['.$params['user_info']['worker_number'].']'.$params['user_info']['real_name'].'于'.date('y-m-d H:i:s',time()).'于'.date('Y-m-d H:i:s',time()).'提交了报价单',
            ];
            ServiceWorkLogLogic::add($work_log);
            Db::commit();
        }
        catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }

    /**
     * 师傅确认服务完成
     * @param $params
     * @return false|void
     */
    public static function confirmServiceFinish($params)
    {
        Db::startTrans();
        try {
            $work = ServiceWork::where(['master_worker_id'=>$params['user_id'],'work_sn'=>$params['work_sn']])->findOrEmpty();
            if($work->isEmpty()){
                throw new Exception('工单不存在');
            }

            if($work->user_confirm_status !=2){
                throw new Exception('请勿重复操作');
            }

            $work->finished_images = $params['finished_images'];
            $work->user_confirm_status = 3;//待确认服务完成
            $work->save();

            //添加变更日志
            $work_log = [
                'work_id'=>$work->id,
                'master_worker_id'=>$work->master_worker_id,
                'opera_log'=>'编号['.$params['user_info']['worker_number'].']'.$params['user_info']['real_name'].'于'.date('y-m-d H:i:s',time()).'于'.date('Y-m-d H:i:s',time()).'提交了待用户确认服务完成',
            ];
            ServiceWorkLogLogic::add($work_log);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }

    public static function allocateWorker($params,$userInfo){
        Db::startTrans();
        try {
            $work = ServiceWork::findOrEmpty($params['id']);
            if($work->isEmpty()){
                throw new Exception('工单不存在');
            }
            if($work->work_status !== 0 ){
                throw new \Exception('工单状态不是待确认');
            }
            if($work->master_worker_id == $params['master_worker_id']){
                throw new \Exception('分配的师傅相同');
            }
            $worker = MasterWorker::where(['id'=>$params['master_worker_id'],'is_disable' =>0])->findOrEmpty();
            if($worker->isEmpty()){
                throw new \Exception('师傅不存在或被禁用');
            }
            $work->master_worker_id = $params['master_worker_id'];
            $work->work_status = 1;
            $work->dispatch_time = time();
            $work->save();
            $work_log = [
                'work_id'=>$work->id,
                'master_worker_id'=>$work->master_worker_id,
                'opera_log'=>'后台用户['.$userInfo['admin_id'].']'.$userInfo['name'].'于'.date('Y-m-d H:i:s',time()).'分配了师傅'.'编号['.$worker->worker_number.']'.$worker->real_name
            ];
            ServiceWorkerAllocateWorkerLogic::add($work_log);
            Db::commit();
            return true;
        }catch(\Exception $e){
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }

    /**
     * 工单详情
     * @param $params
     * @return array|false
     */
    public static function detail($params){
        try {
            $result = ServiceWork::with([
                'worker'=> function(Query $query) {
                    $query->field('id,worker_number,real_name');
                },
                'allocateWorkerLog' =>function(Query $query){
                    $query->field('id,work_id,opera_log,create_time');
                },
                'serviceWorkLog' =>function(Query $query){
                    $query->field('id,work_id,opera_log,create_time');
                }

            ])->append(['id','work_status_text','service_status_text'])
                ->findOrEmpty($params['id'])->toArray();

            //师傅工单按钮状态
            $work_service_status = 0;
            $work_service_status_text = '待派单';
            //工单状态
            if($result['work_status'] == 2){
                $work_service_status = 2;
                $work_service_status_text = '预约上门';
            }
            if($result['work_status'] == 3){
                $work_service_status = 3;
                $work_service_status_text = '等待上门';
                if(date('Y-m-d') === date('Y-m-d',strtotime($result['appointment_time']))){
                    $work_service_status = 4;
                    $work_service_status_text = '确认上门';
                }
            }
            if($result['work_status'] == 4 and $result['user_confirm_status']==0){
                $work_service_status = 5;
                $work_service_status_text = '确认报价';
            }
            if($result['work_status'] == 4 and $result['user_confirm_status']==1){
                $work_service_status = 6;
                $work_service_status_text = '用户确认报价中';
            }
            if($result['work_status'] == 5 and $result['user_confirm_status']==2){
                $work_service_status = 7;
                $work_service_status_text = '完成服务';
            }
            if($result['work_status'] == 5 and $result['user_confirm_status']==3){
                $work_service_status = 8;
                $work_service_status_text = '用户确认完成服务中';
            }
            if($result['work_status'] ==6){
                $work_service_status = 9;
                $work_service_status_text = '待结算';
            }
            if($result['work_status'] ==7){
                $work_service_status = 10;
                $work_service_status_text = '已完结';
            }
            if($result['work_status'] ==8){
                $work_service_status = 11;
                $work_service_status_text = '已评价';
            }

            $result['work_service_status'] = $work_service_status;
            $result['work_service_status_text'] = $work_service_status_text;


            //搜索当前工单下的所有订单记录
            $result['pay_orders'] = RechargeOrder::where(['work_id'=>$result['id']])->field('id as order_id, pay_status,payment_type,pay_way,pay_time,order_amount,coupon_price')->order('id asc')->select()->toArray();
            $pay_status_data = DictData::where('type_value','pay_status')->column('name','value');
            $payment_type_data = DictData::where('type_value','payment_type')->column('name','value');
            $pay_way_data = DictData::where('type_value','pay_way')->column('name','value');
            $coupon_price = 0;
            foreach ($result['pay_orders'] as $k=>&$v){
                $v['pay_status_name'] = $pay_status_data[$v['pay_status']];
                $v['payment_type_name'] = $payment_type_data[$v['payment_type']];
                $v['pay_way_name'] = $pay_way_data[$v['pay_way']];
                $coupon_price += $v['coupon_price'];
            }

            //汇总优惠卷额度
            $result['coupon_price'] = $coupon_price;

            //工单总支付金额
            $result['worker_account'] = MasterWorkerAccountLog::where(['work_sn'=>$result['id']])->sum('change_amount');

            return  $result;
        }catch(\Exception $e){
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }

    }
}