<?php
/**
 * Created by PhpStorm.
 * User: tandunzhao
 * Date: 2017/11/17
 * Time: 下午4:32
 */

namespace App\Modules\Finance\Models;


use App\Libs\PayHelper;
use App\Modules\Finance\Services\BankService;
use App\Modules\Finance\Services\BatchPaymentService;
use App\Modules\Finance\Services\CashAccountService;
use App\Modules\Finance\Services\PaymentService;
use App\Modules\Finance\Services\WithdrawCashService;
use App\Modules\Manage\Services\ManageService;
use Illuminate\Database\Eloquent\Model;
use DB;

/**
 * Class WithdrawCash 提现
 * @package App\Modules\Finance\Models
 */
class BatchPayments extends Model
{
    protected $table = 'batch_payments';
    protected $fillable = ['id','amount','amount_person', 'remark', 'pay_time','pay_merchant_source','trade_no', 'status',
        'is_company','pay_merchant_source_msg','pay_merchant_source_result','bank_account','account_name','account_bank',
        'channel_user_id','check_user_id','check_user_name','serial_number'];

    public static function addBatchPayment($param){
        return self::create($param);
    }

    public static function getBatchPayment($statusIn,$is_all){
        if(is_numeric($statusIn)) {
            $status = WithdrawCashService::getBatchWithdrawCashStatusStrList($statusIn);
        }
        $obj =  self::leftjoin('channel_users','channel_users.id','=','batch_payments.channel_user_id')
            ->leftjoin('companies','companies.id','=','channel_users.company_id')
            ->select([DB::raw('batch_payments.*'),'companies.name as company_name'])
            ->where('status',$status);
        if($is_all){
            return $obj->get();
        }
        return $obj->paginate();
    }

    public static function getById($id) {
        return self::where('id',$id)->first();
    }

    public static function makeThreeSourcePayment($userId, $batch_payment_id, $amount, $remark) {

        //$withdrawCash = WithdrawCashService::getWithdrawCash($withdraw_cash_id);
        $batch_payment = self::getById($batch_payment_id);
        if(empty($batch_payment)) {
            return false;
        }

        $payType = '';
        /*if($liquidatedStat['pay_merchant_source'] == config('common.tonglianpay')) {
            $payType = "ALLINPAY";
        }
        if($liquidatedStat['pay_merchant_source'] == config('common.lianlianpay')) {
            $payType = "LIANLIANPAY";
        }*/
        $payType = "LIANLIANPAY";
        if($payType) {
            try {
                //$channelId = $withdrawCash['distribution_channel_id'];
                $transactionSerialNumber = date('YmdHis')."_".($batch_payment->channel_user_id);
                //$cashAccount = CashAccountService::getCashAccountSingle($channelId);
                //$bank = BankService::getBankSingle($cashAccount['bank_id']);
                $bankCode = '';

                $bankName = $batch_payment->account_bank;       //$cashAccount['account_bank'];
                $bankAccountNO = $batch_payment->bank_account;  //$cashAccount['card_number'];
                $bankAccountName = $batch_payment->account_name;//$cashAccount['account_name'];
                $payAmount = $amount;
                $summaryPay = "summary";
                $remarkPay = "remark";

               // $withdrawCash = WithdrawCashService::getWithdrawCash($withdraw_cash_id);
                //当前当条提现是对公还是对私
                $isCompany = $batch_payment->is_company;
                $pay_id = $batch_payment->id;
                DB::beginTransaction();
                try{
                    //$savePayment = PaymentService::addPayment($withdraw_cash_id, $amount, $remark, $liquidatedStat['pay_merchant_source'], $transactionSerialNumber, WithdrawCashService::getWithdrawCashStatusStr(21), "", $isCompany, 0);
                    $batch_payment->serial_number=$transactionSerialNumber;
                    $batch_payment->status=WithdrawCashService::getWithdrawCashStatusStr(21);
                    $savePayment=$batch_payment->save();
                    if($savePayment) {
                        //更新单个第三方通道可打款金额
                        //FinanceMerchantStatService::createOrUpdate($channelId, $liquidatedStat['pay_merchant_source'], -$amount);
                        //更新当前渠道当天当前支付通道可打款余额
                        //LiquidatedStatService::updateAccountBalanceAmountDay($liquidatedStat['pay_merchant_source'], -$amount);
                        //修改状态打款中
                        $withdraws = WithdrawCashService::getByBatchPaymentId($pay_id);
                        \Log::info($withdraws);
                        foreach ($withdraws as $withdraw){
                            WithdrawCashService::updateWithdrawCashStatus($withdraw->id, $userId, 21, $remark, $transactionSerialNumber);
                        }
                        //

                        $resultPayData = ['code'=>1,'http_result_data'=>['123']];//PayHelper::pay($payType, $transactionSerialNumber, $bankCode, $bankName, $bankAccountNO, $bankAccountName, $payAmount, $summaryPay, $remarkPay, '', $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']);
                            self::updatePaymentStatus($pay_id, WithdrawCashService::getWithdrawCashStatusStr(21), $resultDataHttpDataMsg, $resultDataMsg);
                        } else {
                            $resultDataHttpDataMsg = json_encode($resultPayData['http_result_data']);
                            foreach ($withdraws as $withdraw) {
                                WithdrawCashService::updateWithdrawCashStatus($withdraw->id, $userId, 41, $resultDataMsg, $transactionSerialNumber);
                            }
                            self::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;
        }
    }

    public static function updatePaymentStatus($id, $status = '', $pay_merchant_source_msg, $pay_merchant_source_result) {
        $dataPayment = self::find($id);
        if(!empty($dataPayment)) {
            if($status) {
                $dataPayment['status'] = $status;
            }
            $dataPayment['pay_merchant_source_msg'] = $pay_merchant_source_msg;
            $dataPayment['pay_merchant_source_result'] = $pay_merchant_source_result;
            $dataPayment = $dataPayment->save();
        }

        return $dataPayment;
    }

    public static function getBatchPaymentPaying(){
        $res = self::where('status',WithdrawCashService::getWithdrawCashStatusStr(21))->get();
        return $res;
    }

    public static function updateWithdrawCashStatus($id, $userId = '', $statusIn, $remark='', $serialNumber='') {
        //TODO 对于一个提现记录只有一条打款是没有Bug的。
        //TODO 一个提现记录对应多个支付通道打款，存在逻辑bug
        $withdrawCashs = WithdrawCash::where('batch_payment_id', $id)->get();
        //\DB::beginTransaction();
        try{
        //print_r($withdrawCashs);
            foreach ($withdrawCashs as $withdrawCash){
                if(!empty($withdrawCash) && is_numeric($statusIn)) {

                    if(WithdrawCashService::isWithdrawCashStatusPaymentIngStr($withdrawCash->status)) {
                        //当前状态是 打款中 可以修改状态
                    } else {
                        if(WithdrawCashService::isEditWithdrawCashStatus($id)) {
                            return $withdrawCash;
                        }
                    }
                    $userName = "";
                    if($userId) {
                        $manage = ManageService::getById($userId);
                        if(!empty($manage)) {
                            $userName = $manage['nickname'];
                        }
                    }

                    $statusStr = WithdrawCashService::getWithdrawCashStatusStr($statusIn);
                    if(empty($statusStr)) {
                    } else {
                        if($statusStr) {
                            $withdrawCash->status = $statusStr;
                        }
                    }
                    if(WithdrawCashService::isWithdrawCashStatusCodeSuccess($statusIn)) {
                        //成功提现

                        $financialStat = FinancialStat::getByDistributionChannel($withdrawCash->distribution_channel_id);
                        //修改累计提现金额
                        $financialStat->accumulative_withdrawal_amount = (float)($financialStat->accumulative_withdrawal_amount) + (float)($withdrawCash->amount);
                        //修改提现中金额
                        $financialStat->withdraw_pending_amount = (float)($financialStat->withdraw_pending_amount) - (float)$withdrawCash->amount;
                        $financialStat->save();
                        //
                       // $financePayMerchantBalanceInfo = FinancialPayMerchantBalance::getOne($withdrawCash->distribution_channel_id,$withdrawCash->pay_merchant_company_id);
                        //\Log::info('financePayMerchantBalanceInfo:channel_id:'.$withdrawCash['distribution_channel_id'].'pay_merchant_company_id:'.$withdrawCash['pay_merchant_company_id'].json_encode($financePayMerchantBalanceInfo));
                        //修改累计提现金额
                       // $financePayMerchantBalanceInfo->accumulative_withdrawal_amount = (float)$financePayMerchantBalanceInfo->accumulative_withdrawal_amount + (float)($withdrawCash->amount);
                        //修改提现中金额
                       // $financePayMerchantBalanceInfo->withdraw_pending_amount = (float)$financePayMerchantBalanceInfo->withdraw_pending_amount - (float)($withdrawCash->amount);
                        //$financialStat->save();

                    }
                    if($userId) {
                        $withdrawCash->check_user_id = $userId;
                    }
                    if($userName) {
                        $withdrawCash->check_user_name = $userName;
                    }
                    if($remark) {
                        $withdrawCash->remark = $remark;
                    }
                    if($serialNumber) {
                        if(strpos($withdrawCash->serial_number, $serialNumber) !== false) {
                            //包含
                        } else {
                            $serialNumber = ($withdrawCash->serial_number).",".$serialNumber;
                        }
                        $withdrawCash->serial_number = $serialNumber;
                    }
                    $withdrawCash->save();
                }
            }
            //\DB::commit();
            print_r('commited');
        }catch (\Exception $exception){
            //DB::rollBack();
            \Log::error('pay_query_failed:'.($exception->getMessege()));
            //throw new \Exception($exception->getMessage(),$exception->getCode());
            print_r('pay_query_failed:'.($exception->getMessage()));
        }
    }
}