<?php
/**
 * Created by PhpStorm.
 * User: tandunzhao
 * Date: 2017/12/2
 * Time: 下午7:05
 */

namespace App\Modules\Finance\Services;


use App\Libs\PayHelper;
use App\Modules\Finance\Models\FinanceMerchantStat;
use App\Modules\Finance\Models\LiquidatedStat;
use App\Modules\Finance\Models\Payment;
use App\Modules\Finance\Models\WithdrawCash;
use DB;
use Log;

class PaymentService
{

    /**
     * 创建第三方支付渠道打款
     * @param $userId
     * @param $withdraw_cash_id
     * @param $amount
     * @param $remark
     * @param $liquidatedStat
     * @return bool
     */
    public static function makeThreeSourcePayment($userId, $withdraw_cash_id, $amount, $remark, LiquidatedStat $liquidatedStat) {
        if(empty($liquidatedStat)) {
            return false;
        }
        $withdrawCash = WithdrawCashService::getWithdrawCash($withdraw_cash_id);
        if(empty($withdrawCash)) {
            return false;
        }

        $payType = '';
        if($liquidatedStat['pay_merchant_source'] == config('common.tonglianpay')) {
            $payType = "ALLINPAY";
        }
        if($liquidatedStat['pay_merchant_source'] == config('common.lianlianpay')) {
            $payType = "LIANLIANPAY";
        }
        if($payType) {
            try {
                $channelId = $withdrawCash['distribution_channel_id'];
                $transactionSerialNumber = date('YmdHis')."_".$channelId;
                $cashAccount = CashAccountService::getCashAccountSingle($channelId);
                //$bank = BankService::getBankSingle($cashAccount['bank_id']);
                $bank = BankService::getBankSingleByNameSource($cashAccount['bank'], $payType);
                $bankCode = '';
                if(!empty($bank)) {
                    $bankCode = $bank['code'];
                }
                $bankName = $cashAccount['account_bank'];
                $bankAccountNO = $cashAccount['card_number'];
                $bankAccountName = $cashAccount['account_name'];
                $payAmount = $amount;
                $summaryPay = "summary";
                $remarkPay = "remark";

                $withdrawCash = WithdrawCashService::getWithdrawCash($withdraw_cash_id);
                //当前当条提现是对公还是对私
                $isCompany = $withdrawCash['is_company'];

                DB::beginTransaction();
                try{
                    $savePayment = PaymentService::addPayment($withdraw_cash_id, $amount, $remark, $liquidatedStat['pay_merchant_source'], $transactionSerialNumber, WithdrawCashService::getWithdrawCashStatusStr(21), "", $isCompany, 0);
                    if($savePayment) {
                        //更新单个第三方通道可打款金额
                        FinanceMerchantStatService::createOrUpdate($channelId, $liquidatedStat['pay_merchant_source'], -$amount);
                        //更新当前渠道当天当前支付通道可打款余额
                        LiquidatedStatService::updateAccountBalanceAmountDay($liquidatedStat['pay_merchant_source'], -$amount);
                        //修改状态打款中
                        WithdrawCashService::updateWithdrawCashStatus($withdraw_cash_id, $userId, 21, $remark, $transactionSerialNumber);

                        $resultPayData = PayHelper::pay($payType, $transactionSerialNumber, $bankCode, $bankName, $bankAccountNO, $bankAccountName, $payAmount, $summaryPay, $remarkPay, $channelId, $isCompany);
                        \Log::info('lianlianpay_ret:'.$transactionSerialNumber.':'.json_encode($resultPayData));
                        $resultDataMsg = $remark;
                        if(!empty($resultPayData) && !empty($resultPayData['msg'])) {
                            $resultDataMsg = $resultDataMsg."_【".$resultPayData['msg']."】";
                        }
                        if(!empty($resultPayData) && $resultPayData['code'] == 1) {

                            $resultDataHttpDataMsg = json_encode($resultPayData['http_result_data']);
                            PaymentService::updatePaymentStatus($savePayment['id'], '', $resultDataHttpDataMsg, $resultDataMsg);
                        } else {
                            $resultDataHttpDataMsg = json_encode($resultPayData['http_result_data']);

                            WithdrawCashService::updateWithdrawCashStatus($withdraw_cash_id, $userId, 41, $resultDataMsg, $transactionSerialNumber);
                            PaymentService::updatePaymentStatus($savePayment['id'], WithdrawCashService::getWithdrawCashStatusStr(41), $resultDataHttpDataMsg, $resultDataMsg);
                        }
                    }
                    DB::commit();
                } catch (\Exception $e){
                    Log::error($e->getMessage());
                    DB::rollback();
                    //WithdrawCashService::updateWithdrawCashStatus($withdraw_cash_id, $userId, -1, $remark, $transactionSerialNumber);
                }
            } catch (\Exception $e){
                //WithdrawCashService::updateWithdrawCashStatus($withdraw_cash_id, $userId, -1, $e->getMessage(), '');
            }
            return true;
        } else {
            return false;
        }
    }

    /**
     * 创建人工打款
     * @param $userId
     * @param $withdrawCashId
     * @param $amount
     * @param $remark
     * @param $tradeNo
     * @param int $amount_person
     * @return bool
     */
    public static function makePersonMadePayment($userId, $withdrawCashId, $amount, $remark, $tradeNo, $amount_person = 0) {
        $withdrawCash = WithdrawCashService::getWithdrawCash($withdrawCashId);
        if(empty($withdrawCash)) {
            return false;
        }
        $channelId = $withdrawCash['distribution_channel_id'];
        $isCompany = $withdrawCash['is_company'];
        $isCompanyName = "";
        if($isCompany == 0) {
            $isCompanyName = "对私";
        } else if($isCompany == 1) {
            $isCompanyName = "对公";
        }
        $remark = "[".$isCompanyName."]".$remark;

        DB::beginTransaction();
        try {
            //插入人工打款记录
            $payment = PaymentService::addPayment($withdrawCashId, $amount, $remark, "人工", $tradeNo, WithdrawCashService::getWithdrawCashStatusStr(32), "", $isCompany, $amount_person);
            if(!empty($payment)) {
                //更新当然提现记录为 人工打款成功状态
                WithdrawCashService::updateWithdrawCashStatus($withdrawCashId, $userId, 32, $remark);

                $IgnoreSources = [config('common.officialpay'), config('common.tonglianpay')];
                //优先 官方支付  通联支付 --[支付通道自动清算]
                foreach ($IgnoreSources as $IgnoreSource) {
                    if($amount > 0) {
                        $tempForeach = FinanceMerchantStatService::getFinanceMerchantStatSingle($channelId, $IgnoreSource);

                        if($tempForeach && isset($tempForeach['distribution_channel_id']) && $tempForeach['distribution_channel_id']) {
                            if($tempForeach['enable_withdrawal_amount'] >= $amount) {
                                //当前通道可提现的余额 打款总额，
                                FinanceMerchantStatService::createOrUpdate($tempForeach['distribution_channel_id'], $tempForeach['pay_merchant_source'], -$amount);
                                $amount = 0;
                            } else {
                                //当前通道可提现的余额变为 0
                                FinanceMerchantStatService::createOrUpdate($tempForeach['distribution_channel_id'], $tempForeach['pay_merchant_source'], -$tempForeach['enable_withdrawal_amount']);

                                $amount = $amount - $tempForeach['enable_withdrawal_amount'];
                            }
                        }
                    } else {
                        break;
                    }
                }

                if($amount > 0) {
                    //更新第三方 支付通道的可提现金额
                    $financeMerchantStats = FinanceMerchantStatService::getFinanceMerchantStatListIgnoreSourceArray($channelId, $IgnoreSources);
                    if($financeMerchantStats && !empty($financeMerchantStats) && sizeof($financeMerchantStats) > 0) {
                        //钱少的支付渠道优先
                        $payAmount = $amount;//总打款金额
                        if(is_array($financeMerchantStats) && !emptyempty($financeMerchantStats)){
                            foreach ($financeMerchantStats as $financeMerchantStat) {
                                if($financeMerchantStat && isset($financeMerchantStat['distribution_channel_id']) && $financeMerchantStat['distribution_channel_id']) {
                                    $tempAmount = $financeMerchantStat['enable_withdrawal_amount'] - $payAmount;
                                    if($tempAmount < 0) {
                                        //更新 FinanceMerchantStat
                                        FinanceMerchantStatService::createOrUpdate($financeMerchantStat['distribution_channel_id'], $financeMerchantStat['pay_merchant_source'], -$payAmount);
                                        //更新 LiquidatedStat
                                        LiquidatedStatService::createOrUpdate($financeMerchantStat['pay_merchant_source'], $payAmount);
                                        //更新 Liquidation
                                        LiquidationService::addLiquidation($channelId, $financeMerchantStat['pay_merchant_source'], $payAmount, $payment['id'], $remark);

                                        $payAmount = -$tempAmount;
                                    } else {
                                        //更新 FinanceMerchantStat
                                        FinanceMerchantStatService::createOrUpdate($financeMerchantStat['distribution_channel_id'], $financeMerchantStat['pay_merchant_source'], -$payAmount);
                                        //更新 LiquidatedStat
                                        LiquidatedStatService::createOrUpdate($financeMerchantStat['pay_merchant_source'], $payAmount);
                                        //更新 Liquidation
                                        LiquidationService::addLiquidation($channelId, $financeMerchantStat['pay_merchant_source'], $payAmount, $payment['id'], $remark);
                                        break;
                                    }

                                }
                            }
                        }
                    }
                }
            }
            DB::commit();
        } catch (\Exception $e){
            Log::error("人工打款失败日志" . $e->getMessage());
            DB::rollback();
            return false;
        }
        return true;
    }

    /**
     * 保存打款信息
     * @param $withdraw_cash_id
     * @param $amount
     * @param $remark
     * @param $pay_merchant_source 支付渠道
     * @param $trade_no 交易流水号
     * @param $status 打款状态
     * @param $pay_merchant_source_msg 支付通道返回信息
     * @param int $is_company 0:私人； 1:公司
     * @param int $amount_person 人工打款金额
     * @return mixed
     */
    public static function addPayment($withdraw_cash_id, $amount, $remark, $pay_merchant_source, $trade_no, $status, $pay_merchant_source_msg, $is_company = 0, $amount_person = 0) {
        return Payment::addPayment($withdraw_cash_id, $amount, $remark, $pay_merchant_source, $trade_no, $status, $pay_merchant_source_msg, $is_company, $amount_person);
    }

    /**
     * 更新打款状态
     * @param $id
     * @param String $status
     * @param $pay_merchant_source_msg
     * @param $pay_merchant_source_result
     * @return mixed
     */
    public static function updatePaymentStatus($id, $status = '', $pay_merchant_source_msg, $pay_merchant_source_result) {
        return Payment::updatePaymentStatus($id, $status, $pay_merchant_source_msg, $pay_merchant_source_result);
    }

    /**
     * 获取打款信息列表
     * @param string $withdraw_cash_id 可不传
     * @param string $start_time 可不传
     * @param string $end_time 可不传
     * @param string $status 状态 可不传
     * @param bool $is_all
     * @return mixed
     */
    public static function getPaymentList($withdraw_cash_id = '', $start_time = '', $end_time = '', $status = '', $is_all=false) {
        $payments = Payment::getList($withdraw_cash_id, $start_time, $end_time, $status, $is_all);
        return $payments;
    }

    /**
     * 财务对账
     * @param array $params[]
     *                  withdraw_cash_id : 提现ID 可选
     *                  channel_id:渠道ID 可选
     *                  channel_name:渠道名称 可选
     *                  account_name: 打款人姓名
     *                  start_date:开始时间 可选
     *                  end_date:结束时间 可选
     *                  search_name: 搜索名称
     *                  is_company: 0:私人； 1:公司
     * @param string $statusIn $statusIn 状态 查看接口 WithdrawCashService::getWithdrawCashStatusList  可不传
     * @return mixed
     */
    public static function getPaymentDetailList($params=[], $statusIn = '') {
        if(is_numeric($statusIn)) {
            $params['status'] = WithdrawCashService::getWithdrawCashStatusStrList($statusIn);
        }
        $payments = Payment::getListDetail($params);
        return $payments;
    }

    /**
     * 更新打款状态
     * @param $id id
     * @param $status
     * @return mixed
     */
    public static function updateSimplePaymentStatus($id, $status) {
        return Payment::updateSimplePaymentStatus($id,$status);
    }
}