<?php
/**
 * Created by PhpStorm.
 * User: tandunzhao
 * Date: 2017/11/22
 * Time: 下午3:23
 */

namespace App\Http\Controllers\Manage\Finance;


use App\Http\Controllers\Manage\Finance\Transformers\PaymentDetailTransformer;
use App\Http\Controllers\Manage\Finance\Transformers\PaymentTransformer;
use App\Libs\PayHelper;
use App\Modules\Channel\Services\ChannelService;
use App\Modules\Finance\Models\FinanceMerchantStat;
use App\Modules\Finance\Models\LiquidatedStat;
use App\Modules\Finance\Services\CashAccountService;
use App\Modules\Finance\Services\FinanceMerchantStatService;
use App\Modules\Finance\Services\FinancialConfigService;
use App\Modules\Finance\Services\LiquidatedStatService;
use App\Modules\Finance\Services\PaymentService;
use App\Modules\Finance\Services\WithdrawCashService;
use Illuminate\Http\Request;
use DB;

class PaymentController extends BaseController
{

    /**
     * @apiDefine Finance 结算提现模块
     */


    /**
     * @apiVersion 1.0.0
     * @apiDescription 创建打款信息
     * @api {POST} addPayment 创建打款信息
     * @apiGroup Finance
     * @apiName addPayment
     * @apiParam   {Number}  withdraw_cash_id 提现id.
     * @apiParam   {Number}  amount 打款金额.
     * @apiParam   {String}  [remark] 备注说明.
     * @apiParam   {String}  [source] 打款通道[tl, ll].
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data":{
     *              }
     *     }
     */
    function add_payment(Request $request) {
        $withdraw_cash_id = $request->has('withdraw_cash_id') ? $request->input('withdraw_cash_id') : '';
        if(!is_numeric($withdraw_cash_id)) {
            return response()->error("PARAM_ERROR");
        }
        $amount = $request->has('amount') ? $request->input('amount') : '';
        if(!is_numeric($amount) || (float)$amount <= 0) {
            return response()->error("PARAM_ERROR");
        }
//        $userId = $request->has('user_id') ? $request->input('user_id') : '';
//        if(!is_numeric($userId)) {
//            return response()->error("PARAM_ERROR");
//        }
        $userId = $this->getLoginUserId();

        $remark = $request->has('remark') ? $request->input('remark') : '';

        $withdrawCash = WithdrawCashService::getWithdrawCash($withdraw_cash_id);
        if(empty($withdrawCash)) {
            return response()->error("PARAM_ERROR");
        }
        //对公 走手动打款
        if($withdrawCash['is_company'] == 1) {
            return response()->error("PAYMENT_AUTO_NOT_OPEN");
        }
        //已打款,判断
        if(WithdrawCashService::isEditWithdrawCashStatus($withdraw_cash_id)) {
            return response()->error("PAYMENT_WITHDRAW_MONEY_TOO");
        }


        //判断打款钱核对   提现金额 - 手续费 = 实际打款金额
        $money = (float)$withdrawCash['amount'] - (float)$withdrawCash['tallage'];
        if($amount != $money) {
            return response()->error("PAYMENT_WITHDRAW_MONEY");
        }

        $channelId = $withdrawCash['distribution_channel_id'];
        //判断渠道是否冻结
        if(FinancialConfigService::isFrozenDistributionChannel($channelId)) {
            return response()->error("WITHDRAW_CASH_AMOUNT_FROZEN");
        }
        //判断账户是否已经设置
        if(!CashAccountService::isCashAccountExits($channelId)) {
            return response()->error("WITHDRAW_CASH_AMOUNT_ACCOUNT");
        }

        //TODO 先关闭自动打款
        if(!env('PAYMENT_AUTO_PAY_ON')) {
            return response()->error("PAYMENT_AUTO_NOT_OPEN");
        }

        $isTD = 0;

        $source = $request->has('source') ? $request->input('source') : '';
        if ("tl" == $source || "ll" == $source) {
            if("tl" == $source) {
                //通联支付通道账户
                $tonglianpayLiquidatedStatData = LiquidatedStatService::getLiquidatedStatSingleBySource(config('common.tonglianpay'));
                if(!empty($tonglianpayLiquidatedStatData) && $tonglianpayLiquidatedStatData['account_balance_amount_day'] > ($money - 1)) {
                    //判断通联支付通道钱余额大于 提现金额    需要算上每次 手续费 【1块钱】
                    $isTD = 2;
                }
            }
            if("ll" == $source) {
                //连连支付通道账户
                $lianlianpayLiquidatedStatData = LiquidatedStatService::getLiquidatedStatSingleBySource(config('common.lianlianpay'));
                if(!empty($lianlianpayLiquidatedStatData) && $lianlianpayLiquidatedStatData['account_balance_amount_day'] > ($money - 1)) {
                    //判断连连支付通道钱余额大于 提现金额    需要算上每次 手续费 【1块钱】
                    $isTD = 1;
                }
            }
        } else {
            //通联支付通道账户
            $tonglianpayLiquidatedStatData = LiquidatedStatService::getLiquidatedStatSingleBySource(config('common.tonglianpay'));
            if($isTD == 0) {
                //连连通道钱余额不走,判断通联
                if(!empty($tonglianpayLiquidatedStatData) && $tonglianpayLiquidatedStatData['account_balance_amount_day'] > ($money - 1)) {
                    //判断通联支付通道钱余额大于 提现金额    需要算上每次 手续费 【1块钱】
                    $isTD = 2;
                }
            }

            //连连支付通道账户
            $lianlianpayLiquidatedStatData = LiquidatedStatService::getLiquidatedStatSingleBySource(config('common.lianlianpay'));
            if($isTD == 0) {
                //默认看连连通道余额
                if(!empty($lianlianpayLiquidatedStatData) && $lianlianpayLiquidatedStatData['account_balance_amount_day'] > ($money - 1)) {
                    //判断连连支付通道钱余额大于 提现金额    需要算上每次 手续费 【1块钱】
                    $isTD = 1;
                }
            }
        }

        if($isTD == 0) {
            //连连支付通道,余额不足
            //通联支付通道,余额不足
            // 返回,支付通道余额不足,请走人工打款
            return response()->error("PAYMENT_CHANNEL_AMOUNT_WITHOUT");
        }

        //正式环境,线上为 2
        if(env('PAYMENT_AUTO_PAY_TEST') == 2) {
            if($isTD == 1) {
                //连连支付通道打款
                PaymentService::makeThreeSourcePayment($userId, $withdraw_cash_id, (float)$amount, $remark, $lianlianpayLiquidatedStatData);
                return response()->success();
            }
            if($isTD == 2) {
                //通连支付通道打款
                PaymentService::makeThreeSourcePayment($userId, $withdraw_cash_id, (float)$amount, $remark, $tonglianpayLiquidatedStatData);
                return response()->success();
            }
        } else {
            //测试环境直接修改状态为 成功
            $tradeNo = "测试_".$channelId;
            $pay_merchant_source = "测试";
            if($isTD == 1) {
                $pay_merchant_source = $lianlianpayLiquidatedStatData['pay_merchant_source'];
            }
            if($isTD == 2) {
                $pay_merchant_source = $tonglianpayLiquidatedStatData['pay_merchant_source'];
            }
            //测试环境,直接走逻辑打款成功
            $payment = PaymentService::addPayment($withdraw_cash_id, $amount, $remark, $pay_merchant_source, $tradeNo, WithdrawCashService::getWithdrawCashStatusStr(32), "测试", $withdrawCash['is_company'], 0);
            //更新单个第三方通道可打款金额
            FinanceMerchantStatService::createOrUpdate($channelId, $pay_merchant_source, -$amount);
            //更新当前渠道当天当前支付通道可打款余额
            LiquidatedStatService::updateAccountBalanceAmountDay($pay_merchant_source, -$amount);
            //修改状态
            WithdrawCashService::updateWithdrawCashStatus($withdraw_cash_id, $userId, 32, $remark, $tradeNo);

            return response()->success();
        }
        //其他,走人工打款
        return response()->error("PAYMENT_CHANNEL_AMOUNT_WITHOUT");
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 创建人工打款信息
     * @api {POST} addPaymentPersonMade 创建人工打款信息
     * @apiGroup Finance
     * @apiName addPaymentPersonMade
     * @apiParam   {Number}  withdraw_cash_id 提现id.
     * @apiParam   {Number}  amount_person 人工打款金额
     * @apiParam   {String}  trade_no 银行交易流水号.
     * @apiParam   {String}  [remark] 备注说明.
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data":{
     *              }
     *     }
     */
    function add_paymentPersonMade(Request $request) {
        $withdraw_cash_id = $request->has('withdraw_cash_id') ? $request->input('withdraw_cash_id') : '';
        if(!is_numeric($withdraw_cash_id)) {
            return response()->error("PARAM_ERROR");
        }
//        $userId = $request->has('user_id') ? $request->input('user_id') : '';
//        if(!is_numeric($userId)) {
//            return response()->error("PARAM_ERROR");
//        }
        $userId = $this->getLoginUserId();

        $amount_person = $request->has('amount_person') ? $request->input('amount_person') : '';
        if(!is_numeric($amount_person)) {
            return response()->error("PARAM_ERROR");
        }

        $trade_no = $request->has('trade_no') ? $request->input('trade_no') : '';
        if(empty($trade_no)) {
            return response()->error("PARAM_ERROR");
        }
        $remark = $request->has('remark') ? $request->input('remark') : '';
        $remark = "[人工打款]{".$remark."}";

        $withdrawCash = WithdrawCashService::getWithdrawCash($withdraw_cash_id);
        if(empty($withdrawCash)) {
            return response()->error("PARAM_ERROR");
        }
        //已打款,判断
        if(WithdrawCashService::isWithdrawCashStatusSuccess($withdraw_cash_id)) {
            return response()->error("PAYMENT_WITHDRAW_MONEY_TOO");
        }
        $channelId = $withdrawCash['distribution_channel_id'];
        //判断渠道是否冻结
        if(FinancialConfigService::isFrozenDistributionChannel($channelId)) {
            return response()->error("ACCOUNT_FRONZEN");
        }

        //判断打款钱核对   提现金额 - 手续费 = 实际打款金额
        $amount = (float)$withdrawCash['amount'] - (float)$withdrawCash['tallage'];

        //人工打款成功
        //Payment 插入人工
        // WithdrawCashStatus
        // Liquidation 人工 判断渠道支付通道余额,分别生成
        // LiquidatedStat
        PaymentService::makePersonMadePayment($userId, $withdraw_cash_id, $amount, $remark, $trade_no, $amount_person);
        return response()->success();
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 打款列表
     * @api {GET} payments 打款列表
     * @apiGroup Finance
     * @apiName payments
     * @apiParam   {Number}  [withdraw_cash_id] 提现id.
     * @apiParam   {String}  [start_time] 开始时间(可不传)
     * @apiParam   {String}  [end_time] 结束时间(可不传)
     * @apiSuccess {Number}  id 打款 id.
     * @apiSuccess {Number}  withdraw_cash_id 提现 id.
     * @apiSuccess {Number}  amount 打款金额.
     * @apiSuccess {String}  remark 备注
     * @apiSuccess {String}  pay_time 打款时间
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data":{
     *              "list": [
     *                      {
     *                          "id": 1,
     *                          "withdraw_cash_id": 1,
     *                          "amount": "1000.0000",
     *                          "remark": "dfsdfssd",
     *                          "pay_time": "2017-11-20 14:28:28"
     *                      }
     *                   ],
     *                     "meta": {
     *                           "total": 1,
     *                           "per_page": 15,
     *                           "current_page": 1,
     *                          "last_page": 1,
     *                          "next_page_url": "",
     *                          "prev_page_url": ""
     *                   }
     *              }
     *     }
     */
    function get_list(Request $request) {
        $withdraw_cash_id = $request->has('withdraw_cash_id') ? $request->input('withdraw_cash_id') : '';
        $start_time = $request->has('start_time') && !empty($request->input('start_time')) ? date('Ymd',strtotime($request->input('start_time'))) : '';
        $end_time = $request->has('end_time') && !empty($request->input('end_time')) ? date('Ymd',strtotime($request->input('end_time'))) : '';
        $end_time = self::getMaxDay($end_time);

        $payments = PaymentService::getPaymentList($withdraw_cash_id, $start_time, $end_time);

        return response()->pagination(new PaymentTransformer(), $payments);
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 打款列表详情
     * @api {GET} listPayments 打款列表详情
     * @apiGroup Finance
     * @apiName listPayments
     * @apiParam   {Number}  [withdraw_cash_id] 提现id.
     * @apiParam   {String}  [start_time] 开始时间(可不传)
     * @apiParam   {String}  [end_time] 结束时间(可不传)
     * @apiParam   {Number}  [distribution_channel_id] 渠道id.(可不传,获取所有渠道)
     * @apiParam   {String}  [distribution_channel_name] 渠道名称.(可不传,获取所有渠道)
     * @apiParam   {String}  [account_name] 账户名称
     * @apiParam   {String}  [search_name] 搜索名称
     * @apiParam   {Number}  [status] 状态 查看接口 api/getWithdrawCashStatus (可不传,获取所有状态)
     * @apiParam   {Number}  [is_company] 0:对私, 1:对公司.(可不传,获取所有渠道)
     * @apiSuccess {Number}  id 打款 id.
     * @apiSuccess {Number}  withdraw_cash_id 提现 id.
     * @apiSuccess {Number}  amount 打款金额.
     * @apiSuccess {String}  remark 备注
     * @apiSuccess {String}  pay_time 打款时间
     * @apiSuccess {Number}  channel_id 渠道ID
     * @apiSuccess {String}  channel_name 渠道名称
     * @apiSuccess {String}  status 打款状态
     * @apiSuccess {Number}  check_user_id 审核人ID
     * @apiSuccess {String}  check_user_name 审核人名称
     * @apiSuccess {String}  account_name 银行卡户主名称
     * @apiSuccess {String}  identity_card 银行卡户主身份证
     * @apiSuccess {String}  card_number 银行卡账号
     * @apiSuccess {String}  account_bank 银行支行
     * @apiSuccess {String}  bank 银行名称
     * @apiSuccess {String}  province 银行地址
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data":{
     *              "list": [
     *                      {
     *                           "id": 1,
     *                           "withdraw_cash_id": 1,
     *                           "amount": "1000.0000",
     *                           "pay_time": "2017-11-20 14:28:28",
     *                           "channel_id": 1,
     *                           "channel_name": "渠道一",
     *                           "status": "已打款",
     *                           "remark": "哈哈哈,有钱",
     *                           "check_user_id": 1,
     *                           "check_user_name": "张大妈",
     *                           "account_name": "宋晓",
     *                           "identity_card": "33038119930901821X",
     *                           "card_number": "6222520177654916",
     *                           "account_bank": "钱江支行",
     *                           "bank": "杭州银行",
     *                           "province": "北京市"
     *                      }
     *                   ],
     *                     "meta": {
     *                           "total": 1,
     *                           "per_page": 15,
     *                           "current_page": 1,
     *                          "last_page": 1,
     *                          "next_page_url": "",
     *                          "prev_page_url": ""
     *                   }
     *              }
     *     }
     */
    function get_listDetail(Request $request) {
        $distribution_channel_id = $request->has('distribution_channel_id') ? $request->input('distribution_channel_id') : '';
        $distribution_channel_name = $request->has('distribution_channel_name') ? $request->input('distribution_channel_name') : '';

        $withdraw_cash_id = $request->has('withdraw_cash_id') ? $request->input('withdraw_cash_id') : '';
        $start_time = $request->has('start_time') && !empty($request->input('start_time')) ? date('Ymd',strtotime($request->input('start_time'))) : '';
        $end_time = $request->has('end_time') && !empty($request->input('end_time')) ? date('Ymd',strtotime($request->input('end_time'))) : '';
        $end_time = self::getMaxDay($end_time);

        $account_name = $request->has('account_name') ? $request->input('account_name') : '';
        $search_name = $request->has('search_name') ? $request->input('search_name') : '';
        $status = $request->has('status') ? $request->input('status') : '';
        $is_company = $request->has('is_company') ? $request->input('is_company') : '';

        $params = [
            'withdraw_cash_id'=>$withdraw_cash_id,
            'channel_id'=>$distribution_channel_id,
            'channel_name'=>$distribution_channel_name,
            'start_date'=>$start_time,
            'end_date'=>$end_time,
            'account_name'=>$account_name,
            'search_name'=>$search_name,
            'is_company'=>$is_company,
        ];
        $payments = PaymentService::getPaymentDetailList($params, $status);

        return response()->pagination(new PaymentDetailTransformer(), $payments);
    }

    /**
     * 更新打款状态
     * id 条目id
     * status 状态(10:待打款)
     * @param Request $request
     * @return mixed
     */
    function updatePaymentStatus(Request $request)
    {
        $id = $request->has('id') ? $request->input('id') : '';
        // $status = $request->has('status') ? $request->input('status') : '';

        if (!$id) {
            return response()->error("PARAM_EMPTY");
        }

        $status = WithdrawCashService::getWithdrawCashStatusStr(10);
        $result = PaymentService::updateSimplePaymentStatus($id, $status);
        if ($result) {
            return response()->success();
        } else {
            return response()->error("HANDLE_FAILED");
        }
    }


    function test_add_payment(Request $request)
    {
        $payType = "ALLINPAY";




//        $transactionSerialNumber = date('YmdHis').mt_rand(10,99)."_1";
//        $bankCode = "102";
//        $bankName = '';
//        $bankAccountNO = "6222031202001646388";
//        $bankAccountName = "宋栋波";
//        $amount = 0.01;
//        $summary = "summary";
//        $remark = "remark";
//        $channelId = 1;
//        $isCompany = 0;
//        $resultPayData = PayHelper::pay($payType, $transactionSerialNumber, $bankCode, $bankName, $bankAccountNO, $bankAccountName, $amount, $summary, $remark, $channelId, $isCompany);
//        $resultDataMsg = $remark;
//        if(!empty($resultPayData) && !empty($resultPayData['msg'])) {
//            $resultDataMsg = $resultDataMsg."_【".$resultPayData['msg']."】";
//        }
//        dd($transactionSerialNumber);
////        dd($resultPayData);
//        if(!empty($resultPayData) && $resultPayData['code'] == 1) {
//            $reqSn = date('YmdHis').mt_rand(100000,999999);
//            $resultQueryData = PayHelper::payQuery($payType, $transactionSerialNumber, $reqSn);
//            if(!empty($resultQueryData) && !empty($resultQueryData['msg'])) {
//                $resultDataMsg = $resultDataMsg."_【".$resultQueryData['msg']."】";
//            }
//            if(!empty($resultQueryData) && $resultQueryData['code'] == 1) {
//            }
//        }
//        dd($resultDataMsg);


//        $transactionSerialNumber = '2017122511504564_1';
//        $resultDataMsg = '';
//        $reqSn = date('YmdHis').mt_rand(100000,999999);
//        $resultQueryData = PayHelper::payQuery($payType, $transactionSerialNumber, $reqSn);
//        if(!empty($resultQueryData) && !empty($resultQueryData['msg'])) {
//            $resultDataMsg = $resultDataMsg."_【".$resultQueryData['msg']."】";
//        }
//        if(!empty($resultQueryData) && $resultQueryData['code'] == 1) {
//        }
//        return response()->success($resultQueryData);


//        $reqSn = date('YmdHis').mt_rand(100000,999999);
//        $resultQueryData = PayHelper::payAccountInfo($payType, $reqSn);
//        return response()->success($resultQueryData);

//        $reqSn = date('YmdHis').mt_rand(100000,999999);
//        $startDay = date('Ymd', strtotime(date("Y-m-d")." -2 day"));
//        $endDay = date('Ymd');
//        $resultQueryData = PayHelper::payAccountHistoryBalanceAmount($payType, $reqSn, $startDay, $endDay);
//        return response()->success($resultQueryData);

//        dd(json_encode($resultQueryData));
//        dd($resultDataMsg);


//        $financeMerchantStat = new FinanceMerchantStat();
//        $financeMerchantStat['pay_merchant_source'] = "ALLINPAY";
//        $financeMerchantStat['distribution_channel_id'] = 1;
//        $withdraw_cash_id = 68;
//
//        PaymentService::makeThreeSourcePayment(1, $withdraw_cash_id, 0.01, "测试", $financeMerchantStat);






        $payType = "LIANLIANPAY";
//        $transactionSerialNumber = date('YmdHis').mt_rand(10,99)."_1";
//        $bankCode = "102";
//        $bankName = '';
//        $bankAccountNO = "6222031202001646388";
//        $bankAccountName = "宋栋波";
//        $amount = 0.01;
//        $summary = "summary";
//        $remark = "remark";
//        $channelId = 1;
//        $isCompany = 0;
//        $resultPayData = PayHelper::pay($payType, $transactionSerialNumber, $bankCode, $bankName, $bankAccountNO, $bankAccountName, $amount, $summary, $remark, $channelId, $isCompany);
//        $resultDataMsg = $remark;
//        if(!empty($resultPayData) && !empty($resultPayData['msg'])) {
//            $resultDataMsg = $resultDataMsg."_【".$resultPayData['msg']."】";
//        }
////        dd($transactionSerialNumber);
//        return response()->success($resultPayData);

//        $liquidatedStat = new LiquidatedStat();
//        $liquidatedStat['pay_merchant_source'] = $payType;
//        $withdraw_cash_id = 392;
//        PaymentService::makeThreeSourcePayment(1, $withdraw_cash_id, 1.09, "测试", $liquidatedStat);

//        $transactionSerialNumber = '2017122916450888_1';
//        $resultDataMsg = '';
//        $reqSn = date('YmdHis').mt_rand(100000,999999);
//        $resultQueryData = PayHelper::payQuery($payType, $transactionSerialNumber, $reqSn);
//        if(!empty($resultQueryData) && !empty($resultQueryData['msg'])) {
//            $resultDataMsg = $resultDataMsg."_【".$resultQueryData['msg']."】";
//        }
//        if(!empty($resultQueryData) && $resultQueryData['code'] == 1) {
//        }
//        return response()->success($resultQueryData);

//        $reqSn = date('YmdHis').mt_rand(100000,999999);
//        $resultQueryData = PayHelper::payAccountInfo($payType, $reqSn);
//        return response()->success($resultQueryData);

        return response()->success();
    }
}