<?php

namespace app\api\logic;

use app\common\enum\GoodsEnum;
use app\common\enum\PayEnum;
use app\common\enum\WorkEnum;
use app\common\logic\BaseLogic;
use app\common\model\coupon\UserCoupon;
use app\common\model\dict\DictData;
use app\common\model\goods\Goods;
use app\common\model\master_worker\MasterWorker;
use app\common\model\orders\RechargeOrder;
use app\common\model\property\PropertyCommission;
use app\common\model\property\PropertyHead;
use app\common\model\property\PropertyOrder;
use app\common\model\property\PropertySurplusLog;
use app\common\model\property\PropertyUser;
use app\common\model\recharge\OrderGoods;
use app\common\model\works\ServiceWork;
use app\workerapi\logic\ServiceWorkLogLogic;
use think\Exception;
use think\facade\Db;


/**
 *  物业分成收益逻辑
 * Class PropertyCommissionLogic
 * @package app\api\logic
 */
class PropertyCommissionLogic extends BaseLogic
{

    /**
     * 确认服务完成物业分成
     * @param $params
     * @return false|true
     */
    public static function commissionSurplus($params)
    {
        Db::startTrans();
        try {
            $work_id = $params['id'];
            // 判断工单是否用户已完结
            $service_work = ServiceWork::find($work_id);
            if($service_work->user_confirm_status!=5){
                throw new Exception('未完结订单，无法完成分成');
            }
            $propertyUserId = PropertyUser::where('user_id',$service_work->user_id)->value('id');
            // 非物业负责人-无需分成
            if(empty($propertyUserId)){
                throw new Exception("非物业负责人,该工单无需物业分成:".json_encode($service_work->toArray()));
            }
            $isPropertyOrder = PropertyOrder::where(['property_user_id' => $propertyUserId,'work_id'=>$work_id])->findOrEmpty();
            if($isPropertyOrder->isEmpty()){
                throw new Exception("非物业单:".json_encode(['property_user_id' => $propertyUserId,'work_id'=>$work_id]));
            }
            // 以工单服务费-优惠费 为基准，计算物业分成金额
            $coupon_price = RechargeOrder::where('work_id',$work_id)->sum('coupon_price');
            $work_amount = $service_work->service_fee - $coupon_price;
            $propertyOrderInfo = PropertyOrder::where(['property_user_id' => $propertyUserId,'order_status' => 1,'work_id'=>$work_id])->findOrEmpty();
            if($propertyOrderInfo->isEmpty()){
                throw new Exception("未接单不存在:".json_encode(['property_user_id' => $propertyUserId,'work_id'=>$work_id]));
            }
            $propertyOrderInfo = $propertyOrderInfo->toArray();
            //计算分成金额
            $ratio = PropertyHead::where('id',$propertyOrderInfo['property_head_id'])->value('ratio');
            $commission_amount = bcmul($work_amount, bcdiv($ratio, 100, 4),2);
            // 添加分成记录
            $propertyCommissionInfo = PropertyCommission::create([
                    'property_head_id' => $propertyOrderInfo['property_head_id'],
                    'property_user_id' => $propertyUserId,
                    'property_order_id' => $propertyOrderInfo['id'],
                    'work_id' => $work_id,
                    'order_amount' => $work_amount,
                    'ratio' => $ratio,
                    'commission_amount' => $commission_amount,
            ]);
            // 更新物业收益/订单状态已完结
            PropertyHead::where(['id' => $propertyOrderInfo['property_head_id']])->update([
                'all_profit_amount' => Db::raw('all_profit_amount+'.$commission_amount),
                'surplus_profit_amount' => Db::raw('surplus_profit_amount+'.$commission_amount)
            ]);
            PropertyOrder::where(['id' => $propertyOrderInfo['id']])->update(['order_status' => 3]);
            // 进出账记录
            PropertySurplusLog::create([
                'in_out' => 1,
                'property_head_id' => $propertyOrderInfo['property_head_id'],
                'property_commission_id' => $propertyCommissionInfo['id'],
                'amount' => $commission_amount,
                'status' => 1,
                'remark' => '订单完成，分成金额入账'
            ]);

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

    /**
     * 物业负责人用户申请提现
     * @param $params
     * @return false|true
     */
    public static function withdrawCash($params)
    {
        Db::startTrans();
        try {
            //提现状态0无申请中 1有申请中
            $isId = PropertySurplusLog::where(['in_out' => 2,'status' => 0])->value('id');
            if($isId){
                throw new Exception('存在申请中订单，不可重复申请提现');
            }
            $propertyHeadInfo = PropertyHead::where('user_id',$params['user_id'])->findOrEmpty();
            if($propertyHeadInfo->isEmpty()){
                throw new Exception('物业负责人不存在');
            }
            $propertyHeadInfo = $propertyHeadInfo->toArray();
            $propertyHeadId = $propertyHeadInfo['id'];
            $surplusProfitAmount = $propertyHeadInfo['surplus_profit_amount'];
            if(($surplusProfitAmount - $params['amount']) < 0){
                throw new Exception('余额不足');
            }
            // 出账记录 - 提现
            PropertySurplusLog::create([
                'in_out' => 2,
                'property_head_id' => $propertyHeadId,
                'amount' => $params['amount'],
                'status' => 0
            ]);
            // 更新 物业负责人余额收益
            PropertyHead::where(['id' => $propertyHeadId])->update([
                'surplus_profit_amount' => Db::raw('surplus_profit_amount-'.$params['amount'])
            ]);

            Db::commit();
            return true;
        }catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }
    /**
     * 物业负责人用户申请提现
     * @param $params
     * @return false|true
     */
    public static function assetAccount($params) : array
    {
        $propertyHeadInfo = PropertyHead::where('user_id',$params['user_id'])->findOrEmpty();
        if($propertyHeadInfo->isEmpty()){
            self::setError('物业负责人不存在');
            return [];
        }
        $resData = $propertyHeadInfo->toArray();
        $resData['surplus_status'] = 0;//提现状态0无申请中 1有申请中
        $isId = PropertySurplusLog::where(['in_out' => 2,'status' => 0])->value('id');
        if($isId){
            $resData['surplus_status'] = 1;
        }
        return $resData;
    }
}