<?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\common\model\works;


use app\api\logic\PerformanceLogic;
use app\common\model\BaseModel;
use app\common\model\goods_category\GoodsCategory;
use app\common\model\master_commission\MasterWorkerCommissionConfig;
use app\common\model\master_commission\MasterWorkerCommissionRatio;
use app\common\model\master_worker\MasterWorker;
use app\common\model\orders\RechargeOrder;
use app\common\model\property\PropertyHead;


/**
 * ServiceWork模型
 * Class ServiceWork
 * @package app\common\model\works
 */
class ServiceWork extends BaseModel
{

    protected $name = 'service_work';
    protected $type = [
        'goods_category_ids' =>  'array',
    ];
    const WORK_STATUS_TXT  = [0=>'待派单',1=>'待领单',2=>'待联系',3=>'待上门',4=>'已上门',5=>'服务中',6=>'待结算',7=>'已完结',8=>'已评价',9=>'已退费'];
    public static function onAfterUpdate($model)
    {
        if($model->user_confirm_status == 5 and $model->work_status == 7 and $model->work_pay_status==1){
            //工单已完结，进行结算,结算完成后设置work_pay_status为2，已结算
            $ratio = 0;
            $commissionConfig = MasterWorkerCommissionConfig::where('master_worker_id',$model->master_worker_id)->where('voucher_status',2)->findOrEmpty();
            !$commissionConfig->isEmpty() && $ratio = MasterWorkerCommissionRatio::where('commission_config_id',$commissionConfig['id'])->where('goods_category_id',$model->goods_category_id)->value('ratio')?:0;
            if($commissionConfig->isEmpty() || empty($ratio)){
                PerformanceLogic::calculatePerformance($model);
            }else{
                // 存在服务分类比例进行结算
                PerformanceLogic::calculatePerformanceCommission($model);
            }
            //工单已完结， - 物业后续分成事件 $params['user_id']) || empty($params['sn']
            event('PropertyCommission',['id'=>$model->id]);
        }
    }
    //分配记录
    public function allocateWorkerLog()
    {
        return $this->hasMany(ServiceWorkAllocateWorkerLog::class,'work_id','id')->order(['id'=>'desc']);
    }
    //跟进记录
    public function serviceWorkLog()
    {
        return $this->hasMany(ServiceWorkLog::class,'work_id','id')->order(['id'=>'desc']);
    }
    public function serviceWorkCustomerLog()
    {
        return $this->hasMany(ServiceWorkCustomerLog::class,'work_id','id')->order(['id'=>'desc']);
    }
    public function rechargeOrder()
    {
        return $this->hasMany(RechargeOrder::class,'work_id','id');
    }
    public function worker()
    {
        return $this->belongsTo(MasterWorker::class, 'master_worker_id', 'id');
    }

    public function goodsCategory()
    {
        return $this->hasOne(GoodsCategory::class,'id','goods_category_id');
    }
    public function getWorkStatusTextAttr($value,$data)
    {
        //$status = [0=>'待派单',1=>'待领单',2=>'待联系',3=>'待上门',4=>'已上门',5=>'服务中',6=>'待结算',7=>'已完结',8=>'已评价',9=>'已退费'];
        return (isset($data['service_status']) && $data['service_status']===4)?'已取消':self::WORK_STATUS_TXT[$data['work_status']];
    }

    public function getUserConfirmStatusTextAttr($value,$data)
    {
        $status = [0=>'初始',1=>'待确认报价',2=>'已确认报价',3=>'待确认服务完成',4=>'待支付',5=>'已完结'];
        return $status[$data['user_confirm_status']];
    }

    public function getUserServiceStatusAttr($value,$work): int
    {
        $user_status = 0;
        //用户订单状态
        if($work['work_status']>=2 && $work['work_status']<4){
            $user_status = 1;//待上门，显示上门二维码
        }
        if($work['work_status']>=4 && $work['user_confirm_status'] == 0){
            $user_status = 2;//服务中
        }
        if($work['work_status']>=4 && $work['user_confirm_status'] == 1){
            $user_status = 3;//确认报价
        }
        if($work['work_status']==5 && $work['user_confirm_status'] == 2){
            $user_status = 4;//服务中
        }
        if($work['work_status']==5 && $work['user_confirm_status'] == 3){
            $user_status = 5;//确认服务完成
        }
        if($work['work_status']==6 && $work['user_confirm_status'] == 4){
            $user_status = 6;//待支付
        }
        if($work['work_status']==7 && $work['user_confirm_status'] == 5){
            $user_status = 7;//待评价
        }
        if($work['work_status']==8 && $work['user_confirm_status'] == 5){
            $user_status = 8;//已评价
        }
        //退款处理
        if($work['service_status']==5){
            $user_status = 9;
        }
        //已取消
        if($work['service_status'] == 4){
            $user_status = 10;
        }

        return $user_status;
    }

    public function getUserServiceStatusTextAttr($value,$work)
    {
        $user_status = '待联系';
        //用户订单状态
        if($work['work_status']>=2 && $work['work_status']<4){
            $user_status = '待上门';//待上门，显示上门二维码
        }
        if($work['work_status']>=4 && $work['user_confirm_status'] == 0){
            $user_status = '服务中';//服务中
        }
        if($work['work_status']>=4 && $work['user_confirm_status'] == 1){
            $user_status = '确认报价';//确认报价
        }
        if($work['work_status']==5 && $work['user_confirm_status'] == 2){
            $user_status = '服务中';//服务中
        }
        if($work['work_status']==5 && $work['user_confirm_status'] == 3){
            $user_status = '确认服务完成';//确认服务完成
        }
        if($work['work_status']==6 && $work['user_confirm_status'] == 4){
            $user_status = '待支付';//待支付
        }
        if($work['work_status']==7 && $work['user_confirm_status'] == 5){
            $user_status = '待评价';//待评价
        }
        if($work['work_status']==8 && $work['user_confirm_status'] == 5){
            $user_status = '已评价';//已评价
        }

        //退款处理
        if($work['service_status']==5){
            $user_status = '已退款';
        }
        if($work['service_status']==4){
            $user_status = '已取消';
        }
        return $user_status;
    }

    public function getServiceStatusTextAttr($value,$data)
    {
        $status = [0=>'已下单',1=>'服务中',2=>'部分完成',3=>'已完成',4=>'已取消',5=>'已退款'];
        if($data['work_pay_status']==0 and $data['service_status']!==4){
            return '待付款';
        }
        return $status[$data['service_status']];
    }
    public function getDispatchTimeAttr($value,$data)
    {
        return !empty($data['dispatch_time'])?date('Y/m/d H:i:s',$data['dispatch_time']):'';
    }
    public function getAppointmentTimeAttr($value,$data)
    {
        return !empty($data['appointment_time'])?date('Y/m/d H:i:s',$data['appointment_time']):'';
    }

    public function getReceiveTimeAttr($value,$data)
    {
        return !empty($data['receive_time'])?date('Y-m-d H:i:s',$data['receive_time']):'';
    }

    public function getFinishedTimeAttr($value,$data)
    {
        return !empty($data['finished_time'])?date('Y-m-d H:i:s',$data['finished_time']):'';
    }

    public function getWorkImagesAttr($value)
    {
        return !empty($value)?json_decode($value,true):'';
    }

    public function getFinishedImagesAttr($value)
    {
        return !empty($value)?json_decode($value,true):'';
    }
    public function propertyHead()
    {
        return $this->hasOne(PropertyHead::class,'user_id','user_id');
    }

}