<?php
namespace App\Http\Models\Api;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

class ReceivableCredit extends Model
{
    /**
     * [queryClientPrice 查询客户的金额]
     * @param  [type]  $user_info       [用户信息]
     * @param  [type]  $print_type      [打印类型：1订单打印2工单打印]
     * @param  [type]  $client_type     [客户类型]
     * @param  [type]  $client_id       [客户id]
     * @param  [type]  $item_type       [单据类型：1系统工单2外派工单3速电派单4虚拟加盟店]
     * @param  integer $service_shop_id [服务门店id，实体加盟店id/虚拟加盟店id]
     * @return [type]                   [description]
     */
    public static function queryClientPrice(
        $user_info,
        $print_type,
        $client_type,
        $client_id,
        $item_type,
        $service_shop_id = 0
    ) {
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
        if ($print_type == 1) { //订单打印，单据类型：1系统工单 2外派工单3速电派单 4虚拟加盟店
            if ($item_type == 1) {
                $search_data['recr_client_type'] = $client_type;
                $search_data['recr_client_id'] = $client_id;
            } else if ($item_type == 2) { //外派工单
                $search_data['recr_client_type'] = 5;
                $search_data['recr_client_id'] = $service_shop_id;
            } elseif ($item_type == 3) { //速电派单
                $search_data['recr_client_type'] = 6;
                $search_data['recr_client_id'] = 0;
            } elseif ($item_type == 4) {
                $search_data['recr_client_type'] = $client_type;
                $search_data['recr_client_id'] = $client_id;
            } else {
                return 0;
            }
        } else { // 工单打印，单据类型：1系统工单 2外派工单3速电派单 4虚拟加盟店
            // recr_client_type 客户类型：1.会员零售 2.来往单位 3.外派门店（加盟店或总店） 4会员零售(工单代收）5接单门店（总店或加盟店）6速电派单7虚拟加盟店
            if ($item_type == 1) {
                $search_data['recr_client_type'] = $client_type;
                $search_data['recr_client_id'] = $client_id;
            } else if ($item_type == 2) {
                // 外派工单
                $search_data['recr_client_type'] = 5;
                $search_data['recr_client_id'] = $service_shop_id;
            } elseif ($item_type == 3) {
                // 速电派单
                $search_data['recr_client_type'] = 6;
                $search_data['recr_client_id'] = 0;
            } elseif ($item_type == 4) {
                $search_data['recr_client_type'] = 7;
                $search_data['recr_client_id'] = $service_shop_id;
            } else {
                return 0;
            }
        }
        $find_price = DB::table('receivable_credit')
            ->where('recr_cid', $user_info->adm_cid)
            ->where('recr_shop_superior_id', $shop_id)
            ->whereRaw('`recr_settle_price` <> `recr_yet_receipt`')
            ->where('recr_belongs_id', '=', 0)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['recr_client_type'])) {
                    if ($search_data['recr_client_type'] == 1) {
                        $query->whereIn('recr_client_type', [1, 4]);
                    } else {
                        $query->where('recr_client_type', $search_data['recr_client_type']);
                    }
                }
            }) //客户类型
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['recr_client_id'])) {
                    $query->where('recr_client_id', $search_data['recr_client_id']);
                }
            }) //客户单位id
            ->select('recr_state', 'recr_settle_price', 'recr_actual_price', 'recr_yet_receipt', 'recr_zero_price', 'recr_plus_minus', 'recr_zero_plus_minus')
            ->get();

        $recr_settle_price = 0; //结算金额
        $recr_yet_receipt = 0; //已收金额
        $recr_zero_price = 0; //抹零金额
        foreach ($find_price as $key => $value) {
            // recr_state 状态：1未确认2已确认3已收款4采购已付款
            if ($value->recr_state == 2) {
                continue;
            }
            // 欠收 = 结算金额 - 已收 - 抹零
            if ($value->recr_plus_minus == 1) {
                $recr_settle_price += $value->recr_settle_price; //结算金额
                $recr_yet_receipt += $value->recr_yet_receipt; //已收金额
            } else {
                $recr_settle_price -= $value->recr_settle_price;
                $recr_yet_receipt -= $value->recr_yet_receipt;
            }
            if ($value->recr_zero_plus_minus == 1) {
                $recr_zero_price += $value->recr_zero_price; //抹零金额
            } else {
                $recr_zero_price -= $value->recr_zero_price;
            }
        }
        // 铺货金额-正值
        $distribution_positive = self::clientUnitTimeBucketDistributionPrice($user_info, 1, $client_id, null);
        // 铺货金额-负值
        $distribution_minus = self::clientUnitTimeBucketDistributionPrice($user_info, 2, $client_id, null);
        // 铺货金额
        $distribution_price = self::clientUnitCalculatePrice($distribution_positive, $distribution_minus, $client_id);
        // 欠收 = 结算金额 - 已收 - 抹零 - 铺货金额
        $total_client_price = ($recr_settle_price - $recr_yet_receipt - $recr_zero_price - $distribution_price) / 100; //客户欠收总金额总计
        return $total_client_price;
    }

    /**
     * [clientUnitTimeBucketDistributionPrice 统计客户单位时间段应收应付的铺货金额]
     * @param  [type] $user_info       [用户信息]
     * @param  [type] $recr_plus_minus [金额正负：1正值2负值]
     * @param  [type] $chun_id         [客户单位id，数组]
     * @param  [type] $start_time      [开始时间]
     * @param  [type] $end_time        [结束时间]
     * @return [type]                  [description]
     */
    public static function clientUnitTimeBucketDistributionPrice(
        $user_info,
        $recr_plus_minus,
        $chun_id,
        $start_time = null,
        $end_time = null
    ) {
        $time_bucket_price  = collect(DB::table('receivable_credit as rc')
            ->leftjoin('order_client as oc', 'oc.orcl_ord_id', '=', 'rc.recr_original_id')
            ->where('recr_cid', $user_info->adm_cid)
            ->where('recr_shop_id', $user_info->adm_shop_id)
            ->where('recr_plus_minus', $recr_plus_minus) //金额正负：1正值2负值
            ->where('recr_client_type', 2) //客户类型：1会员零售2来往单位
            ->where('recr_belongs_id', '=', 0)
            ->where('recr_state', '!=', 2) //状态：1未确认2已确认3已收款4已付款
            ->where('recr_type', 3) //类型：1销售订单2预收款3订单账单
            ->where('recr_account_type', '!=', 5) //5订单账单
            ->where('orcl_chin_type', 1) //订单是否铺货：1是2否
            ->where('recr_client_id', $chun_id)
            ->where(function ($query) use ($start_time, $end_time) {
                if (!empty($start_time) && !empty($end_time)) {
                    $query->whereBetween('recr_order_time', [$start_time, $end_time]);
                } elseif (!empty($start_time)) {
                    // 180天以上
                    $query->where('recr_order_time', '<', $start_time);
                }
            })
            ->select(DB::Raw('sum(recr_settle_price) as recr_settle_price,sum(recr_yet_receipt) as recr_yet_receipt,sum(recr_zero_price) as recr_zero_price,recr_client_id'))
            ->groupBy('recr_client_id')
            ->get())->keyBy('recr_client_id')->toArray();
        // dump($time_bucket_price);exit;
        return $time_bucket_price;
    }

    /**
     * [clientUnitCalculatePrice 客户单位计算金额]
     * @param  [type] $positive_price [正数金额]
     * @param  [type] $minus_price    [负数金额]
     * @return [type]                 [description]
     */
    public static function clientUnitCalculatePrice($positive_price, $minus_price, $chun_id)
    {
        // recr_settle_price 结算金额
        $positive_settle_price = isset($positive_price[$chun_id]->recr_settle_price) ? $positive_price[$chun_id]->recr_settle_price : 0;
        $minus_settle_price = isset($minus_price[$chun_id]->recr_settle_price) ? $minus_price[$chun_id]->recr_settle_price : 0;
        $settle_price = $positive_settle_price - $minus_settle_price; //当前的结算金额

        // recr_yet_receipt 已收金额
        $positive_yet_receipt = isset($positive_price[$chun_id]->recr_yet_receipt) ? $positive_price[$chun_id]->recr_yet_receipt : 0;
        $minus_yet_receipt = isset($minus_price[$chun_id]->recr_yet_receipt) ? $minus_price[$chun_id]->recr_yet_receipt : 0;
        $yet_receipt  =  $positive_yet_receipt - $minus_yet_receipt;

        // recr_zero_price 抹零金额
        $positive_zero_price = isset($positive_price[$chun_id]->recr_zero_price) ? $positive_price[$chun_id]->recr_zero_price : 0;
        $minus_zero_price = isset($minus_price[$chun_id]->recr_zero_price) ? $minus_price[$chun_id]->recr_zero_price : 0;
        $zero_price = $positive_zero_price - $minus_zero_price;

        // 当前的欠收金额 = 结算金额 - 已收金额 - 抹零金额
        $bad_crop_price = $settle_price - $yet_receipt - $zero_price;
        return $bad_crop_price;
    }
}
